The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden;
on the containing element. For example
.parent {_x000D_
background: red;_x000D_
overflow: hidden;_x000D_
}_x000D_
.segment-a {_x000D_
float: left;_x000D_
}_x000D_
.segment-b {_x000D_
float: right;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="segment-a">_x000D_
Float left_x000D_
</div>_x000D_
<div class="segment-b">_x000D_
Float right_x000D_
</div>_x000D_
</div>
_x000D_
Of course this can only be used in instances where you never wish the content to overflow.
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.
float
vs display:inline
Before the invention of display:inline-block
, websites use float
to set elements beside each other. float
is preferred over display:inline
since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.
The main problem is that we're using float
against its intended purpose.
Another is that while float
allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute
, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>
, the <div>
will not impart 100px in height to the container.
Unlike position:absolute
, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.
What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear
.
Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear
property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.
Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:
The first clearfix you have appends an invisible pseudo-element, which is styled clear:both
, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.
The second one appends the style display:inline-block
which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.
This was the reapplication of display:block
due to IE-MAC rule above. This rule was "hidden" from IE-MAC.
All in all, these 3 rules keep the .clearfix
working cross-browser, with old browsers in mind.
With LESS (http://lesscss.org/), one can create a handy clearfix helper:
.clearfix() {
zoom: 1;
&:before {
content: '';
display: block;
}
&:after {
content: '';
display: table;
clear: both;
}
}
And then use it with problematic containers, for example:
<!-- HTML -->
<div id="container">
<div id="content"></div>
<div id="sidebar"></div>
</div>
/* LESS */
div#container {
.clearfix();
}
I believe Twitter Bootstrap has a class called clearfix
that you can use to clear the floating.
<ul class="nav nav-tabs span2 clearfix">
My favourite method is using a clearfix class for parent element
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
/// <summary>
/// https://stackoverflow.com/a/45620698/2390270
/// Compare a source and target datatables and return the row that are the same, different, added, and removed
/// </summary>
/// <param name="dtOld">DataTable to compare</param>
/// <param name="dtNew">DataTable to compare to dtOld</param>
/// <param name="dtSame">DataTable that would give you the common rows in both</param>
/// <param name="dtDifferences">DataTable that would give you the difference</param>
/// <param name="dtAdded">DataTable that would give you the rows added going from dtOld to dtNew</param>
/// <param name="dtRemoved">DataTable that would give you the rows removed going from dtOld to dtNew</param>
public static void GetTableDiff(DataTable dtOld, DataTable dtNew, ref DataTable dtSame, ref DataTable dtDifferences, ref DataTable dtAdded, ref DataTable dtRemoved)
{
try
{
dtAdded = dtOld.Clone();
dtAdded.Clear();
dtRemoved = dtOld.Clone();
dtRemoved.Clear();
dtSame = dtOld.Clone();
dtSame.Clear();
if (dtNew.Rows.Count > 0) dtDifferences.Merge(dtNew.AsEnumerable().Except(dtOld.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>());
if (dtOld.Rows.Count > 0) dtDifferences.Merge(dtOld.AsEnumerable().Except(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>());
if (dtOld.Rows.Count > 0 && dtNew.Rows.Count > 0) dtSame = dtOld.AsEnumerable().Intersect(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>();
foreach (DataRow row in dtDifferences.Rows)
{
if (dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))
&& !dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)))
{
dtRemoved.Rows.Add(row.ItemArray);
}
else if (dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))
&& !dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)))
{
dtAdded.Rows.Add(row.ItemArray);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
Try this for a clean approach.
var $toptitle = $('#toptitle');
if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.
$toptitle.text('New Word');
A few comments:
import sun.misc.*;
Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.
byte[] encVal = c.doFinal(Data.getBytes());
You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
Defaults might be different in different places.
As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.
In fact, in common usage, word has become synonymous with 16 bits, much like byte has with 8 bits. Can get a little confusing since the "word size" on a 32-bit CPU is 32-bits, but when talking about a word of data, one would mean 16-bits. Microcontrollers with a 32-bit word size have taken to calling their instructions "longs" (supposedly to try and avoid the word/doubleword confusion).
look at the image :)
Main program calls library function (which might be system level function also) with callback function name. This callback function might be implemented in multiple way. The main program choose one callback as per requirement.
Finally, the library function calls the callback function during execution.
The -i
flag probably doesn't work for you, because you followed an example for GNU sed while macOS uses BSD sed and they have a slightly different syntax.
All the other answers tell you how to correct the syntax to work with BSD sed. The alternative is to install GNU sed on your macOS with:
brew install gsed
and then use it instead of the sed
version shipped with macOS (note the g
prefix), e.g:
gsed -i 's/oldword/newword/' file1.txt
If you want GNU sed commands to be always portable to your macOS, you could prepend "gnubin" directory to your path, by adding something like this to your .bashrc
/.zshrc
file (run brew info gsed
to see what exactly you need to do):
export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"
and from then on the GNU sed becomes your default sed and you can simply run:
sed -i 's/oldword/newword/' file1.txt
Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');
To do this using Python code:
importlib.metadata.version
import importlib.metadata
importlib.metadata.version('beautifulsoup4')
'4.9.1'
(using importlib_metadata.version
)
!pip install importlib-metadata
import importlib_metadata
importlib_metadata.version('beautifulsoup4')
'4.9.1'
pkg_resources.Distribution
import pkg_resources
pkg_resources.get_distribution('beautifulsoup4').version
'4.9.1'
pkg_resources.get_distribution('beautifulsoup4').parsed_version
<Version('4.9.1')>
Credited to comments by sinoroc and mirekphd.
gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo"
and #include <zap>
will search on your system, I recommend:
$ touch a.c
$ gcc -v -E a.c
...
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/lib/gcc/i686-apple-darwin9/4.0.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"
This is one way to see the search lists for included files, including (if any) directories into which #include "..."
will look but #include <...>
won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ...
here;-) on any system on which gcc runs properly.
This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#
If you are writing in C++ you are probably writing for performance. Using new and the free store is much slower than using the stack (especially when using threads) so only use it when you need it.
As others have said, you need new when your object needs to live outside the function or object scope, the object is really large or when you don't know the size of an array at compile time.
Also, try to avoid ever using delete. Wrap your new into a smart pointer instead. Let the smart pointer call delete for you.
There are some cases where a smart pointer isn't smart. Never store std::auto_ptr<> inside a STL container. It will delete the pointer too soon because of copy operations inside the container. Another case is when you have a really large STL container of pointers to objects. boost::shared_ptr<> will have a ton of speed overhead as it bumps the reference counts up and down. The better way to go in that case is to put the STL container into another object and give that object a destructor that will call delete on every pointer in the container.
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://stackoverflow.com")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print ('Website is working fine')
Works on Python 3
Have a look at Spring framework source, it has excellent javadocs
First, I wouldn't use document.body. Instead add an empty container:
index.html:
<html>
<head></head>
<body>
<div id="app"></div>
</body>
</html>
Then opt to only render your <App />
element:
main.js:
var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));
Within App.js
you can import your other components and ignore your DOM render code completely:
App.js:
var SampleComponent = require('./SampleComponent.js');
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component!</h1>
<SampleComponent name="SomeName" />
</div>
);
}
});
SampleComponent.js:
var SampleComponent = React.createClass({
render: function() {
return (
<div>
<h1>Sample Component!</h1>
</div>
);
}
});
Then you can programmatically interact with any number of components by importing them into the necessary component files using require
.
I use WinForms and my way to use File.Exists(string path) is the next one:
public bool FileExists(string fileName)
{
var workingDirectory = Environment.CurrentDirectory;
var file = $"{workingDirectory}\{fileName}";
return File.Exists(file);
}
fileName must include the extension like myfile.txt
You should add the following lines in your gradle build file (build.gradle)
dependencies {
compile files('/usr/share/stuff')
..
}
This can be easily done using the CSS3 Flexbox, a feature which will be used in the future(When <IE9
is completely dead) by almost every browser.
Check the Browser Compatibility Table
HTML
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>
CSS
.container {
display: flex;
flex-flow: row nowrap; /* Align on the same line */
justify-content: space-between; /* Equal margin between the child elements */
}
Output:
.container {_x000D_
display: flex;_x000D_
flex-flow: row nowrap; /* Align on the same line */_x000D_
justify-content: space-between; /* Equal margin between the child elements */_x000D_
}_x000D_
_x000D_
/* For Presentation, not needed */_x000D_
_x000D_
.container > div {_x000D_
background: #5F85DB;_x000D_
padding: 5px;_x000D_
color: #fff;_x000D_
font-weight: bold;_x000D_
font-family: Tahoma;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">_x000D_
Left_x000D_
</div>_x000D_
<div class="center">_x000D_
Center_x000D_
</div>_x000D_
<div class="right">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
Try this:
<div id="mainTable" style="width:100px; height:200px;"></div>
$(document).ready(function() {
$("#mainTable").width(100).height(200);
}) ;
sudo apt-get install python3-pymysql
This command also works for me to install the package required for Flask app to tun on ubuntu 16x with WISG module on APACHE2 server.
BY default on WSGI uses python 3 installation of UBUNTU.
Anaconda custom installation won't work.
This's a jQuery free solution that can work with SPA inside the iframe
document.getElementById('iframe-id').addEventListener('load', function () {
let that = this;
setTimeout(function () {
that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
}, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});
Considering that the accepted answer is probably inefficient for large arrays, O(nm), I usually prefer this approach, O(2n + 2m):
function mergeArrays(arr1 = [], arr2 = []){
//Creates an object map of id to object in arr1
const arr1Map = arr1.reduce((acc, o) => {
acc[o.id] = o;
return acc;
}, {});
//Updates the object with corresponding id in arr1Map from arr2,
//creates a new object if none exists (upsert)
arr2.forEach(o => {
arr1Map[o.id] = o;
});
//Return the merged values in arr1Map as an array
return Object.values(arr1Map);
}
Unit test:
it('Merges two arrays using id as the key', () => {
var arr1 = [{id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'}];
var arr2 = [{id:'124',name:'ttt'}, {id:'45',name:'yyy'}];
const actual = mergeArrays(arr1, arr2);
const expected = [{id:'124',name:'ttt'}, {id:'589',name:'www'}, {id:'45',name:'yyy'}, {id:'567',name:'rrr'}];
expect(actual.sort((a, b) => (a.id < b.id)? -1: 1)).toEqual(expected.sort((a, b) => (a.id < b.id)? -1: 1));
})
Applying the text-align:center
style to an element containing elements will center those elements.
<div id="method-one" style="text-align:center">
CSS `text-align:center`
</div>
Thomas Shields mentions this method
Applying the margin:0 auto
style to a block element will center it within the element it is in.
<div id="method-two" style="background-color:green">
<div style="margin:0 auto;width:50%;background-color:lightblue">
CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
</div>
</div>
user1468562 mentions this method
My original answer was that you can use the <center></center>
tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center>
is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.
<h3>Method 3</h1>
<div id="method-three">
<center>Center tag (not recommended and deprecated in HTML4)</center>
</div>
You can see these three code samples in action in this jsfiddle.
I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.
If you have a Uri
that conforms to the DocumentContract
then you probably don't want to use File
.
If you are on kotlin, use DocumentFile
to do stuff you would in the old World use File
for, and use ContentResolver
to get streams.
Everything else is pretty much guaranteed to break.
I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"
Wrong one: ng-moel="user.name" Right one: ng-model="user.name"
Probably the easiest way is to use the timers plugin. http://plugins.jquery.com/project/timers and then call something like
$(this).oneTime(1000, function() {
$("#something").hide();
});
You have to use .onload
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
const drawImage = (url) => {
const image = new Image();
image.src = url;
image.onload = () => {
ctx.drawImage(image, 0, 0)
}
}
Here's Why
If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()
Here is a simple interpretation about your problem:
== (equal to) used to evaluate arithmetic expression
where as
equals() method used to compare string
Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
From IE9 and above you can use SVG in a ordinary IMG tag..
<img src="/static/image.svg">
As a quick and very scoped solution:
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
For Cordova based project, run cordova clean android
before build again, as @mkimmet suggested.
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
I have faced the same issue using Google Chrome browser. Same website was opening normally using the incognito mode and different browsers. At first, I cleared cached files and cookies over the past 24 hours, but this didn't help.
I realized that my first visit to the website was during the past 10 days. So, I cleared cached files and cookies over the past 4 weeks and that resolved the problem.
Note: I didn't clear my browsing history data
Change setTimeout("changeImage()", 30000);
to setInterval("changeImage()", 30000);
and remove var timerid = setInterval(changeImage, 30000);
.
I found that JToken.Parse incorrectly parses invalid JSON such as the following:
{
"Id" : ,
"Status" : 2
}
Paste the JSON string into http://jsonlint.com/ - it is invalid.
So I use:
public static bool IsValidJson(this string input)
{
input = input.Trim();
if ((input.StartsWith("{") && input.EndsWith("}")) || //For object
(input.StartsWith("[") && input.EndsWith("]"))) //For array
{
try
{
//parse the input into a JObject
var jObject = JObject.Parse(input);
foreach(var jo in jObject)
{
string name = jo.Key;
JToken value = jo.Value;
//if the element has a missing value, it will be Undefined - this is invalid
if (value.Type == JTokenType.Undefined)
{
return false;
}
}
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
return true;
}
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):
Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )
Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.
Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.
Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64
Find extension on this site, then put them into the python folder, and install .whl extension with pip:
python -m pip install extensionname.whl
Enjoy
Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})
Result:
{
"_id": ObjectId("..."),
"list": [{a: 1}]
}
After several tries, I got it! I'm setting the keyboard values programmatically like this:
myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
Or if you want you can edit the XML like so:
android: inputType = "numberPassword"
Both configs will display password bullets, so we need to create a custom ClickableSpan
class:
private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
Finally we need to implement it on the EditText
in order to display the characters typed.
myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
This is how my keyboard looks like now:
You can check if a element is disabled or not with this:
if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice
}
If you can use a C++ compiler to build the object file that you want to contain your version string, then we can do exactly what you want! The only magic here is that C++ allows you to use expressions to statically initialize an array, while C doesn't. The expressions need to be fully computable at compile time, but these expressions are, so it's no problem.
We build up the version string one byte at a time, and get exactly what we want.
// source file version_num.h
#ifndef VERSION_NUM_H
#define VERSION_NUM_H
#define VERSION_MAJOR 1
#define VERSION_MINOR 4
#endif // VERSION_NUM_H
// source file build_defs.h
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// 01234567890
#define BUILD_YEAR_CH0 (__DATE__[ 7])
#define BUILD_YEAR_CH1 (__DATE__[ 8])
#define BUILD_YEAR_CH2 (__DATE__[ 9])
#define BUILD_YEAR_CH3 (__DATE__[10])
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define BUILD_MONTH_CH0 \
((BUILD_MONTH_IS_OCT || BUILD_MONTH_IS_NOV || BUILD_MONTH_IS_DEC) ? '1' : '0')
#define BUILD_MONTH_CH1 \
( \
(BUILD_MONTH_IS_JAN) ? '1' : \
(BUILD_MONTH_IS_FEB) ? '2' : \
(BUILD_MONTH_IS_MAR) ? '3' : \
(BUILD_MONTH_IS_APR) ? '4' : \
(BUILD_MONTH_IS_MAY) ? '5' : \
(BUILD_MONTH_IS_JUN) ? '6' : \
(BUILD_MONTH_IS_JUL) ? '7' : \
(BUILD_MONTH_IS_AUG) ? '8' : \
(BUILD_MONTH_IS_SEP) ? '9' : \
(BUILD_MONTH_IS_OCT) ? '0' : \
(BUILD_MONTH_IS_NOV) ? '1' : \
(BUILD_MONTH_IS_DEC) ? '2' : \
/* error default */ '?' \
)
#define BUILD_DAY_CH0 ((__DATE__[4] >= '0') ? (__DATE__[4]) : '0')
#define BUILD_DAY_CH1 (__DATE__[ 5])
// Example of __TIME__ string: "21:06:19"
// 01234567
#define BUILD_HOUR_CH0 (__TIME__[0])
#define BUILD_HOUR_CH1 (__TIME__[1])
#define BUILD_MIN_CH0 (__TIME__[3])
#define BUILD_MIN_CH1 (__TIME__[4])
#define BUILD_SEC_CH0 (__TIME__[6])
#define BUILD_SEC_CH1 (__TIME__[7])
#if VERSION_MAJOR > 100
#define VERSION_MAJOR_INIT \
((VERSION_MAJOR / 100) + '0'), \
(((VERSION_MAJOR % 100) / 10) + '0'), \
((VERSION_MAJOR % 10) + '0')
#elif VERSION_MAJOR > 10
#define VERSION_MAJOR_INIT \
((VERSION_MAJOR / 10) + '0'), \
((VERSION_MAJOR % 10) + '0')
#else
#define VERSION_MAJOR_INIT \
(VERSION_MAJOR + '0')
#endif
#if VERSION_MINOR > 100
#define VERSION_MINOR_INIT \
((VERSION_MINOR / 100) + '0'), \
(((VERSION_MINOR % 100) / 10) + '0'), \
((VERSION_MINOR % 10) + '0')
#elif VERSION_MINOR > 10
#define VERSION_MINOR_INIT \
((VERSION_MINOR / 10) + '0'), \
((VERSION_MINOR % 10) + '0')
#else
#define VERSION_MINOR_INIT \
(VERSION_MINOR + '0')
#endif
#endif // BUILD_DEFS_H
// source file main.c
#include "version_num.h"
#include "build_defs.h"
// want something like: 1.4.1432.2234
const unsigned char completeVersion[] =
{
VERSION_MAJOR_INIT,
'.',
VERSION_MINOR_INIT,
'-', 'V', '-',
BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3,
'-',
BUILD_MONTH_CH0, BUILD_MONTH_CH1,
'-',
BUILD_DAY_CH0, BUILD_DAY_CH1,
'T',
BUILD_HOUR_CH0, BUILD_HOUR_CH1,
':',
BUILD_MIN_CH0, BUILD_MIN_CH1,
':',
BUILD_SEC_CH0, BUILD_SEC_CH1,
'\0'
};
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s\n", completeVersion);
// prints something similar to: 1.4-V-2013-05-09T15:34:49
}
This isn't exactly the format you asked for, but I still don't fully understand how you want days and hours mapped to an integer. I think it's pretty clear how to make this produce any desired string.
If it ain't broke - fix it till it is...just kidding :)
But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.
add your file android/app/build.gradle
defaultConfig {
applicationId "com.ubicacion"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true // ?
missingDimensionStrategy 'react-native-camera', 'general'
}
I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.
It all depends on the type of classification problem you are dealing with. There are three main categories
In the first case, binary cross-entropy should be used and targets should be encoded as one-hot vectors.
In the second case, categorical cross-entropy should be used and targets should be encoded as one-hot vectors.
In the last case, binary cross-entropy should be used and targets should be encoded as one-hot vectors. Each output neuron (or unit) is considered as a separate random binary variable, and the loss for the entire vector of outputs is the product of the loss of single binary variables. Therefore it is the product of binary cross-entropy for each single output unit.
The binary cross-entropy is defined as
and categorical cross-entropy is defined as
where c
is the index running over the number of classes C
.
This should work for you
sed -e 's_^all: .*_& anotherthing_'
Using s command (substitute) you can search for a line which satisfies a regular expression. In the command above, &
stands for the matched string.
Working Example here - add /edit to the URL to play with the code
You just need to use JavaScript setInterval
function
$('html').addClass('js');_x000D_
_x000D_
$(function() {_x000D_
_x000D_
var timer = setInterval(showDiv, 5000);_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
function showDiv() {_x000D_
if (counter == 0) {_x000D_
counter++;_x000D_
return;_x000D_
}_x000D_
_x000D_
$('div', '#container')_x000D_
.stop()_x000D_
.hide()_x000D_
.filter(function() {_x000D_
return this.id.match('div' + counter);_x000D_
})_x000D_
.show('fast');_x000D_
counter == 3 ? counter = 0 : counter++;_x000D_
_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<title>Sandbox</title>_x000D_
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />_x000D_
<style type="text/css" media="screen">_x000D_
body {_x000D_
background-color: #fff;_x000D_
font: 16px Helvetica, Arial;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.display {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
border: 2px solid #000;_x000D_
}_x000D_
_x000D_
.js .display {_x000D_
display: none;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h2>Example of using setInterval to trigger display of Div</h2>_x000D_
<p>The first div will display after 10 seconds...</p>_x000D_
<div id='container'>_x000D_
<div id='div1' class='display' style="background-color: red;">_x000D_
div1_x000D_
</div>_x000D_
<div id='div2' class='display' style="background-color: green;">_x000D_
div2_x000D_
</div>_x000D_
<div id='div3' class='display' style="background-color: blue;">_x000D_
div3_x000D_
</div>_x000D_
<div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
EDIT:
In response to your comment about the container div, just modify this
$('div','#container')
to this
$('#div1, #div2, #div3')
In JavaScript you simple test for the cookieEnabled property, which is supported in all major browsers. If you deal with an older browser, you can set a cookie and check if it exists. (borrowed from Modernizer):
if (navigator.cookieEnabled) return true;
// set and read cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;
// delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
In PHP it is rather "complicated" since you have to refresh the page or redirect to another script. Here I will use two scripts:
somescript.php
<?php
session_start();
setcookie('foo', 'bar', time()+3600);
header("location: check.php");
check.php
<?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps
For the Single line and double line break here are the following codes.
Single break: %0D0A
Double break: %0D0A%0D0A
You can use the -B
and -A
to print lines before and after the match.
grep -i -B 10 'error' data
Will print the 10 lines before the match, including the matching line itself.
I want to mention one important note regarding req.query
, because currently I am working on pagination functionality based on req.query
and I have one interesting example to demonstrate to you...
Example:
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;
const patientQuery = Patient.find();
let fetchedPatients;
// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
/**
* Construct two different queries
* - Fetch all patients
* - Adjusted one to only fetch a selected slice of patients for a given page
*/
patientQuery
/**
* This means I will not retrieve all patients I find, but I will skip the first "n" patients
* For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
*
* Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
* so I want to skip (7 * (2 - 1)) => 7 items
*/
.skip(pageSize * (currentPage - 1))
/**
* Narrow dont the amound documents I retreive for the current page
* Limits the amount of returned documents
*
* For example: If I got 7 items per page, then I want to limit the query to only
* return 7 items.
*/
.limit(pageSize);
}
patientQuery.then(documents => {
res.status(200).json({
message: 'Patients fetched successfully',
patients: documents
});
});
};
You will noticed +
sign in front of req.query.pageSize
and req.query.currentPage
Why? If you delete +
in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).
Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.
If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.
SQL>
SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division
FROM interview
JOIN jobsdev.employer
ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;
When in doubt, read the documentation:
filename = "C:\Temp\vblist.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
WScript.Echo f.ReadLine
Loop
f.Close
Git’s executable is actually located in:
C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin\git.exe
Now that we have located the executable all we have to do is add it to our PATH:
;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd
I don't think that best practice will be passing a variable like req.YOUR_VAR
. You might want to consider req.YOUR_APP_NAME.YOUR_VAR
or req.mw_params.YOUR_VAR
.
It will help you avoid overwriting other attributes.
Update May 31, 2020
res.locals is what you're looking for, the object is scoped to the request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
Short answer: Yes, you need to rename .cpp files to c, so you can write C: https://msdn.microsoft.com/en-us/library/bb384838.aspx?f=255&MSPPError=-2147217396
From the link above:
By default, the Visual C++ compiler treats all files that end in .c as C source code, and all files that end in .cpp as C++ source code. To force the compiler to treat all files as C regardless of file name extension, use the /Tc compiler option.
That being said, I do not recommend learning C language in Visual Studio, why VS? It does have lots of features you are not going to use while learning C
The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.
as:
<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />
In this example I set the limite to 65536 bytes= 64*1024.
Hope this will help.
USE style="max-width:90%;"
<select name=countries style="max-width:90%;">
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}
my_url("?z=z", { page_name : "pageX" /* no table_name and optionResult */ } );
/* Returns:
?z=z&page_name=pageX
*/
This avoids using typeof whatever === "undefined"
. (Also, there isn't any string concatenation.)
Interesting one. I love collecting quotes about quotes handling in cmd/command.
Your particular scripts gets fixed by using %1 instead of "%1" !!!
By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.
Here's a simple way.
/**
* Add css to the document
* @param {string} css
*/
function addCssToDocument(css){
var style = document.createElement('style')
style.innerText = css
document.head.appendChild(style)
}
You are lucky that you didn't complete the rebase, so you can still do git rebase --abort
. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.
To find out if a path is a valid directory try:
file.info(cacheDir)[1,"isdir"]
file.info
does not care about a slash on the end.
file.exists
on Windows will fail for a directory if it ends in a slash, and succeeds without it. So this cannot be used to determine if a path is a directory.
file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE
file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE
file.info(cacheDir)["isdir"]
Using alternative dplyr package:
library("dplyr") # or library("tidyverse")
df <- df %>% mutate(id = row_number())
I have faced this situation and in my case, I was using two git id's simultaneously. so what it does it will update the credentials in the credential Manager
Control Panel\User Accounts\Credential Manager
inside Credential Manager, you will find the git hub credentials inside the Generic credentials there you have to update your git credentials.
@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")
You need a space on either side of the !=
. Change your code to:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/
The easiest way I've seen is to use Google Fonts.
Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.
Then add this to your custom.css:
h1, h2, h3, h4, h5, h6 {
font-family: 'Your Font' !important;
}
p, div {
font-family: 'Your Font' !important;
}
or
body {
font-family: 'Your Font' !important;
}
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
You cannot treat ==
or ||
as chars, since they are not chars, but a sequence of chars.
You could make your switch...case work on strings instead.
Throwable
is super class of Exception
as well as Error
. In normal cases we should always catch sub-classes of Exception
, so that the root cause doesn't get lost.
Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error
or Throwable
.
I remember catching Throwable to flag that a native library is not loaded.
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
Here is some example about getting print out the list component:
public class ListExample {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
// TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example
// Print the name from the list....
for(Model model : models) {
System.out.println(model.getName());
}
// Or like this...
for(int i = 0; i < models.size(); i++) {
System.out.println(models.get(i).getName());
}
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
To answer your first question, the way you load a module is depending on the module entry point and the main parameter of the package.json.
Let's say you have the following file structure:
my-npm-module
|-- lib
| |-- module.js
|-- package.json
Without main parameter in the package.json, you have to load the module by giving the module entry point: require('my-npm-module/lib/module.js')
.
If you set the package.json main parameter as follows "main": "lib/module.js"
, you will be able to load the module this way: require('my-npm-module')
.
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
The solution of so-called problem is to use a spy
Mockito.spy(...) instead of a mock
Mockito.mock(..).
Spy enables us to partial mocking. Mockito is good at this matter. Because you have class which is not complete, in this way you mock some required place in this class.
DECLARE @MYVAR NVARCHAR(100)
DECLARE @step int
SET @step = 0;
DECLARE MYTESTCURSOR CURSOR
DYNAMIC
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
WHILE @step < 10
BEGIN
FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
SET @step = @step + 1;
END
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR
You only need a minimal change; single-quote the here-document delimiter after <<
.
cat <<'EOF' >> brightup.sh
or equivalently backslash-escape it:
cat <<\EOF >>brightup.sh
Without quoting, the here document will undergo variable substitution, backticks will be evaluated, etc, like you discovered.
If you need to expand some, but not all, values, you need to individually escape the ones you want to prevent.
cat <<EOF >>brightup.sh
#!/bin/sh
# Created on $(date # : <<-- this will be evaluated before cat;)
echo "\$HOME will not be evaluated because it is backslash-escaped"
EOF
will produce
#!/bin/sh
# Created on Fri Feb 16 11:00:18 UTC 2018
echo "$HOME will not be evaluated because it is backslash-escaped"
As suggested by @fedorqui, here is the relevant section from man bash
:
Here Documents
This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence
\<newline>
is ignored, and\
must be used to quote the characters\
,$
, and`
.
You need selector like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- State when a row is being pressed, but hasn't yet been activated (finger down) -->
<item android:drawable="@color/app_primary_color_light" android:state_pressed="true" />
<!-- Used when the view is "activated". -->
<item android:drawable="@color/app_primary_color" android:state_activated="true" />
<!-- Default, "just hangin' out" state. -->
<item android:drawable="@android:color/transparent" /></selector>
And then set android:choiceMode="singleChoice"
to your ListView.
Bash is the benchmark, but that's mostly because you can be reasonably sure it's installed on every *nix out there. If you're planning to distribute the scripts, use Bash.
I can not really address the actual programming differences between the shells, unfortunately.
PHP CLI SAPI is using different php.ini
than CGI or Apache module.
Find line ;extension=php_openssl.dll
in wamp/bin/php/php#.#.##/php.ini
and uncomment it by removing the semicolon (;
) from the beginning of the line.
I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).
public class ResourceLoader {
public static URL getResource(String resource) {
final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
classLoaders.add(Thread.currentThread().getContextClassLoader());
classLoaders.add(ResourceLoader.class.getClassLoader());
for (ClassLoader classLoader : classLoaders) {
final URL url = getResourceWith(classLoader, resource);
if (url != null) {
return url;
}
}
final URL systemResource = ClassLoader.getSystemResource(resource);
if (systemResource != null) {
return systemResource;
} else {
try {
return new File(resource).toURI().toURL();
} catch (MalformedURLException e) {
return null;
}
}
}
private static URL getResourceWith(ClassLoader classLoader, String resource) {
if (classLoader != null) {
return classLoader.getResource(resource);
}
return null;
}
}
I prefer onKeyUp
since it only fires when the key is released. onKeyDown
, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter
key to make a network request, you don't want that to fire multiple times since it can be expensive.
// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />
handleKeyPress(e) {
if (e.key === 'Enter') {
// do whatever
}
}
Also, stay away from keyCode
since it will be deprecated some time.
"Why does a scipy get so complicated?
It gets so complicated because Python's package management system is built to track Python package dependencies, and SciPy and other scientific tools have dependencies beyond Python. Wheels fix part of the problem, but my experience is that tools like pip
/virtualenv
are just not sufficient for installing and managing a scientific Python stack.
If you want an easy way to get up and running with SciPy, I would highly suggest the Anaconda distribution. It will give you everything you need for scientific computing in Python.
If you want a "short way" of doing this (I'm interpreting that as "I don't want to install a huge distribution"), you might try miniconda and then run conda install scipy
.
Moreover, Please refer to load(Reader reader) method from Property
class on javadoc
In load(Reader reader)
method documentation it says
The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped
'='
,':'
, or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character; for example,\:\=
would be the two-character key
":=".
Line terminator characters can be included using\r
and\n
escape sequences. Any white space after the key is skipped; if the first non-white space character after the key is'='
or':'
, then it is ignored and any white space characters after it are also skipped. All remaining characters on the line become part of the associated element string; if there are no remaining characters, the element is the empty string""
. Once the raw character sequences constituting the key and element are identified, escape processing is performed as described above.
Hope that helps.
This can be done quite easily if you:
Use str
to convert the number into a string so that you can iterate over it.
Use a list comprehension to split the string into individual digits.
Use int
to convert the digits back into integers.
Below is a demonstration:
>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
I was faced with the same issue in windows 10, Updating the environment variable following steps, it's working fine.
I know It is a lengthy answer for the simple environment setups, I thought it's may be useful for the new window 10 users.
1) Open Anaconda Prompt:
2) Check Conda Installed Location.
where conda
3) Open Advanced System Settings
4) Click on Environment Variables
5) Edit Path
6) Add New Path
C:\Users\RajaRama\Anaconda3\Scripts
C:\Users\RajaRama\Anaconda3
C:\Users\RajaRama\Anaconda3\Library\bin
7) Open Command Prompt and Check Versions
8) After 7th step type conda install anaconda-navigator in cmd then press y
In HTML:
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />
In PHP:
if (isset($_POST["btnSubmit"])){
// "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
// "Delete" clicked
}
Swift version, works perfectly globally:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal)
UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted)
return true
}
Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:
find . -cmin +<time>
find . -cmin -<time>
find . -cmin <time>
In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:
find . -cmin -5
Use the start and end delimiters: ^abc$
As of API 21, you could also use:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
you can Add contextual classes to every single row as follows:
<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>
You can also add them to table data same as above
You can set your table size by setting classes as table-sm and so on.
You can add custom classes and add your own styling:
<table class="table">
<thead style = "color:red;background-color:blue">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Asdf</td>
<td>qwerty</td>
</tr>
</tbody>
</table>
This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.
You can use canvas’ context.translate & context.rotate to do rotate your image
Here’s a function to draw an image that is rotated by the specified degrees:
function drawRotated(degrees){
context.clearRect(0,0,canvas.width,canvas.height);
// save the unrotated context of the canvas so we can restore it later
// the alternative is to untranslate & unrotate after drawing
context.save();
// move to the center of the canvas
context.translate(canvas.width/2,canvas.height/2);
// rotate the canvas to the specified degrees
context.rotate(degrees*Math.PI/180);
// draw the image
// since the context is rotated, the image will be rotated also
context.drawImage(image,-image.width/2,-image.width/2);
// we’re done with the rotating so restore the unrotated context
context.restore();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/6ZsCz/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
}
image.src="houseicon.png";
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){
angleInDegrees-=30;
drawRotated(angleInDegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,-image.width/2,-image.width/2);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>
</body>
</html>
I think, that will be good solution: /\S\w*/
I guess this may work, in Eclipse select your project ? then click on project menu bar on top ? goto to properties ? click on Targeted Runtimes ? now you must select a check box next to the server you are using to run current project ? click Apply ? then click OK button. That's it, give a try.
Out of all the code samples I've used to get the height of the status bar, the only one that actually appears to work in the onCreate
method of an Activity
is this:
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
Apparently the actual height of the status bar is kept as an Android resource. The above code can be added to a ContextWrapper
class (e.g. an Activity
).
Found at http://mrtn.me/blog/2012/03/17/get-the-height-of-the-status-bar-in-android/
The following worked for me
const conString = "postgres://YourUserName:YourPassword@YourHostname:5432/YourDatabaseName";
1 ) Open the jenkins.xml file
2 ) Search for the "--httpPort=8080" Text and replace the port number 8080 with your custom port number (like 7070 , 9090 )
3 ) Go to your services running your machine & find out the Jenkins service and click on restart.
This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.
browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");
Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).
To specifically address your problem, you should remove the brackets after donothing
in your setTimeout
call, and make waitsecs
a number not a string:
console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
But that won't stop execution; "after" will be logged before your function runs.
To wait properly, you can use anonymous functions:
console.log('before');
setTimeout(function(){
console.log('after');
},500);
All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval
/ clearInterval
if it needs to loop.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
This runs fine on Java 1.6
~ % javac RemoveListElementDemo.java
~ % java RemoveListElementDemo
~ % cat RemoveListElementDemo.java
import java.util.*;
public class RemoveListElementDemo {
private static final List<Integer> integerList;
static {
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
}
public static void remove(Integer remove) {
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
public static void main(String... args) {
remove(Integer.valueOf(2));
Integer remove = Integer.valueOf(3);
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
}
~ %
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
There are several tools which can import Excel to SQL Server.
I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...
I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.
Configure web.xml with setting
<error-page>
<error-code>500</error-code>
<location>/error/500</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/404</location>
</error-page>
Create new controller
/**
* Error Controller. handles the calls for 404, 500 and 401 HTTP Status codes.
*/
@Controller
@RequestMapping(value = ErrorController.ERROR_URL, produces = MediaType.APPLICATION_XHTML_XML_VALUE)
public class ErrorController {
/**
* The constant ERROR_URL.
*/
public static final String ERROR_URL = "/error";
/**
* The constant TILE_ERROR.
*/
public static final String TILE_ERROR = "error.page";
/**
* Page Not Found.
*
* @return Home Page
*/
@RequestMapping(value = "/404", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
public ModelAndView notFound() {
ModelAndView model = new ModelAndView(TILE_ERROR);
model.addObject("message", "The page you requested could not be found. This location may not be current.");
return model;
}
/**
* Error page.
*
* @return the model and view
*/
@RequestMapping(value = "/500", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
public ModelAndView errorPage() {
ModelAndView model = new ModelAndView(TILE_ERROR);
model.addObject("message", "The page you requested could not be found. This location may not be current, due to the recent site redesign.");
return model;
}
}
Ron's answer contains an error. It uses 2:00 AM local time where the UTC equivalent is required. I don't have enough reputation points to comment on Ron's answer so a corrected version appears below:
-- =============================================
-- Author: Ron Smith
-- Create date: 2013-10-23
-- Description: Converts UTC to DST
-- based on passed Standard offset
-- =============================================
CREATE FUNCTION [dbo].[fn_UTC_to_DST]
(
@UTC datetime,
@StandardOffset int
)
RETURNS datetime
AS
BEGIN
declare
@DST datetime,
@SSM datetime, -- Second Sunday in March
@FSN datetime -- First Sunday in November
-- get DST Range
set @SSM = datename(year,@UTC) + '0314'
set @SSM = dateadd(hour,2 - @StandardOffset,dateadd(day,datepart(dw,@SSM)*-1+1,@SSM))
set @FSN = datename(year,@UTC) + '1107'
set @FSN = dateadd(second,-1,dateadd(hour,2 - (@StandardOffset + 1),dateadd(day,datepart(dw,@FSN)*-1+1,@FSN)))
-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
set @StandardOffset = @StandardOffset + 1
-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)
-- return converted datetime
return @DST
END
Also you may omit the AS keyword.
SELECT row1 Price, row2 'Other Price' FROM exampleDB.table1;
in this option readability is a bit degraded but you have desired result.
@toivotuo 's method worked best and most reliably for me under python3. My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic.
import magic
filename = "./datasets/test"
def file_mime_type(filename):
m = magic.open(magic.MAGIC_MIME)
m.load()
return(m.file(filename))
print(file_mime_type(filename))
for a gzipped file it returns: application/gzip; charset=binary
for an unzipped txt file (iostat data): text/plain; charset=us-ascii
for a tar file: application/x-tar; charset=binary
for a bz2 file: application/x-bzip2; charset=binary
and last but not least for me a .zip file: application/zip; charset=binary
Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:
proxy = yourproxy.com:8080
I believe you can write it as such:
coll.stream().collect(Collectors.toList())
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.
Also put all your enum strings together in one array:-
static const char * allEnums[] = {
"Undefined",
"apple",
"orange"
/* etc */
};
define the indices in a header file:-
#define ID_undefined 0
#define ID_fruit_apple 1
#define ID_fruit_orange 2
/* etc */
Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.
Using a macro, also in the header file:-
#define CASE(type,val) case val: index = ID_##type##_##val; break;
Make a function with a switch statement, this should return a const char *
because the strings static consts:-
const char * FruitString(enum fruit e){
unsigned int index;
switch(e){
CASE(fruit, apple)
CASE(fruit, orange)
CASE(fruit, banana)
/* etc */
default: index = ID_undefined;
}
return allEnums[index];
}
If programming with Windows then the ID_ values can be resource values.
(If using C++ then all the functions can have the same name.
string EnumToString(fruit e);
)
Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.
I'm guessing that the error either happens right away, with a large file, or happens later after several requests.
If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.
If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.
I added a "Height" to my ListBox and it added the scrollbar nicely.
In case you want to use a WKWebView
to load a .svg image that is coming from a URLRequest
, you can simply achieve it like this:
Swift 4
if let request = URLRequest(url: urlString), let svgString = try? String(contentsOf: request) {
wkWebView.loadHTMLString(svgString, baseURL: request)
}
It's much simpler than the other ways of doing it, and you can also persist your .svg string somewhere to load it later, even offline if you need to.
If you can add another wrapping div "block3" you could do something like this.
<html>
<head>
<style type="text/css">
.block1 {color:red;width:120px;border:1px solid green; height: 100px;}
.block3 {float:left; width:10px;}
.block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
</style>
</head>
<body>
<div class='block1'>
<div class='block3'>
<p>text1</p>
<p>text2</p>
</div>
<div class='block2'>block2</DIV>
</div>
</body>
</html>
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Cells
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
Try:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Worked for me!
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:
const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);
Yes include the first file into the second. That's all.
See an example below,
File1.php :
<?php
function first($int, $string){ //function parameters, two variables.
return $string; //returns the second argument passed into the function
}
?>
Now Using include
(http://php.net/include) to include the File1.php
to make its content available for use in the second file:
File2.php :
<?php
include 'File1.php';
echo first(1,"omg lol"); //returns omg lol;
?>
Some people might be experiencing a solid line. I got around this by adding android:layerType="software"
to the view referencing the drawable.
You can use %in%
data[data$Code %in% selected,]
Code Value
1 A 1
2 B 2
7 A 3
8 A 4
Yes, you can set the line height after defining the border like this:
border-right: 1px solid;
line-height: 10px;
The method below sets a field on your object even if the field is in a superclass
/**
* Sets a field value on a given object
*
* @param targetObject the object to set the field value on
* @param fieldName exact name of the field
* @param fieldValue value to set on the field
* @return true if the value was successfully set, false otherwise
*/
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
Field field;
try {
field = targetObject.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = null;
}
Class superClass = targetObject.getClass().getSuperclass();
while (field == null && superClass != null) {
try {
field = superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
superClass = superClass.getSuperclass();
}
}
if (field == null) {
return false;
}
field.setAccessible(true);
try {
field.set(targetObject, fieldValue);
return true;
} catch (IllegalAccessException e) {
return false;
}
}
Hi I face the same problem today. After reading "Spentak"'s answer i tried to make code signing of my target to set to iOSDeveloper, and still did not work. But after i changing "Provisioning Profile" to "Automatic", the project got built and ran without any code signing errors.
Are you sure that this is a bottleneck? Have you done any performance analysis?
Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.
Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.
package main
import (
"fmt"
"strings"
)
func main() {
strs := strings.Split("127.0.0.1:5432", ":")
ip := strs[0]
port := strs[1]
fmt.Println(ip, port)
}
Here is the definition for strings.Split
// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
System.out.println(myList.size());
Since no elements are in the list
output => 0
myList.add("newString"); // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());
Since one element is added to the list
output => 1
C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.
Another weird solution to achieve a relative fixed position is converting your container into an iframe, that way your fixed element can be fixed to it's container's viewport and not the entire page.
Your code can't find the figure or the name of your figure named the by error message. Solution:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_width, new_height);
Graphics g = Graphics.FromImage((Image)new_image );
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
When you call document.write
after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);
If you want to use jQuery you get some better APIs to deal with. For example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');
If you need the code to run after the new window's DOM is ready try:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
$(OpenWindow.document.body).append('<p>hi</p>');
});
To remove a specific variable from the session use:
session_unregister('variableName');
(see documentation) or
unset($_SESSION['variableName']);
NOTE:
session_unregister()
has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
When dealing with a hash {}
, use both the key and value to the block inside the ||
.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]
Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:
import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)
ALLOWED_HOSTS = ['*']
then ran the server with:
python manage.py runserver 0.0.0.0:9595
Also ensure that the firewall allows connections to that port
As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:
<style>
body {
padding-top: 60px;
}
</style>
Like so:
<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
body {
padding-top: 60px;
}
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
Hopefully someone else finds this useful:
Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.
To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):
= "Select * from tProducts Where 1 = 1 "
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")
In your Parameter do the following:
SELECT -1 As ProductID, 'All' as ProductName Union All
Select
tProducts.ProductID,tProducts.ProductName
FROM
tProducts
By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.
Try the following (Which does not print -1 at the end now!)
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe
or something like that. NSIS uninstallers support /S
flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S
From NSIS documentation:
3.2.1 Common Options
/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.
I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.
I had that problem, but it was because my images changed them manually from .JPG to .PNG, so I just changed them with PNG paint and solved the problem
You can use various options with FINDSTR to remove the lines do not want, like so:
DIR /S | FINDSTR "\-" | FINDSTR /VI DIR
Normal output contains entries like these:
28-Aug-14 05:14 PM <DIR> .
28-Aug-14 05:14 PM <DIR> ..
You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.
There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.
So the the number of values we can represent with n bits is just 2^n (2 to the power n)
You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.
getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:
class ParentClass{
}
public class SubClass extends ParentClass{
public static void main(String []args){
ParentClass parentClassInstance = new ParentClass();
SubClass subClassInstance = new SubClass();
if(subClassInstance instanceof ParentClass){
System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
}
if(subClassInstance.getClass() != parentClassInstance.getClass()){
System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
}
}
}
Outputs:
SubClass extends ParentClass. subClassInstance is instanceof ParentClass.
Different getClass() return results with subClassInstance and parentClassInstance.
Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:
perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
If you are using XAMPP rather than WAMP, the path you go to is:
C:\xampp\phpMyAdmin\config.inc.php
To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.
Use Jenkins' way to stop that protects from data loss.
http://[jenkins-server]/[command]
where [command] can be any one of the following
Example: if my local PC is running Jenkins at port 8080, it will be
http://localhost:8080/exit
Check out numpy.count_nonzero.
>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
I think you're talking about the logical meaning of both operators, here you have a table-resume:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.
this works for me
$(window).bind('beforeunload', function() {
return 'Do you really want to leave?' ;
});
I don't know of any full Chrome component, but you could use WebKit, which is the rendering engine that Chrome uses. The Mono project made WebKit Sharp, which might work for you.
You have to encode your parameters.
Something like this will do:
import java.net.*;
import java.io.*;
public class EncodeParameter {
public static void main( String [] args ) throws URISyntaxException ,
UnsupportedEncodingException {
String myQuery = "^IXIC";
URI uri = new URI( String.format(
"http://finance.yahoo.com/q/h?s=%s",
URLEncoder.encode( myQuery , "UTF8" ) ) );
System.out.println( uri );
}
}
http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
this can be resolved by copying the below code in application.properties
spring.thymeleaf.enabled=false
#For brevity, I didn't define a function.
#Place the directories you want to exclude in this array.
#Case insensitive and exact match. So 'archive' and
#'ArcHive' will match but 'BuildArchive' will not.
$noDirs = @('archive')
#Build a regex using array of excludes
$excRgx = '^{0}$' -f ($noDirs -join ('$|^'))
#Rather than use the gci -Recurse option, use a more
#performant approach by not processing the match(s) as
#soon as they are located.
$cmd = {
Param([string]$Path)
Get-ChildItem $Path -Directory |
ForEach-Object {
if ($_.Name -inotmatch $excRgx) {
#Recurse back into the scriptblock
Invoke-Command $cmd -ArgumentList $_.FullName;
#If you want all directory info change to return $_
return $_.FullName
}
}
}
#In this example, start with the current directory
$searchPath = .
#Start the Recursion
Invoke-Command $cmd -ArgumentList $searchPath
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
You have to learn Smarty syntax. That's a template system.
Look for a string which contains an unescaped single qoute that may be inserted by some server side code.
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
Take the width of the table and divide it by the number of cell ().
PerformanceTable {width:500px;}
PerformanceTable.td {width:100px;}
If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.
Hopefully this is the simplest way
string Commaseplist;
string[] itemList = { "Test1", "Test2", "Test3" };
Commaseplist = string.join(",",itemList);
Console.WriteLine(Commaseplist); //Outputs Test1,Test2,Test3
For image purpose you can do something like this
img {
width: calc(100% + 20px); // twice the value of the parent's padding
margin-left: -10px; // -1 * parent's padding
}
String ordinal(int num)
{
String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int m = num % 100;
return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
}
According to this message on the GCC mailing list, you can use the file "nul" instead of /dev/null:
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
(Credits to Danny for this code; copy-pasted from his message.)
You can also use this special "nul" file through redirection.
This is the fastest way:
if ($coll->isEmpty()) {...}
Other solutions like count
do a bit more than you need which costs slightly more time.
Plus, the isEmpty()
name quite precisely describes what you want to check there so your code will be more readable.
You could use IsEmpty()
function like this:
...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...
you could also use following:
If ActiveCell.Value = vbNullString Then ...
Here is a compilation of verified information from the various answers and cited references in this thread:
command.com
is the 16-bit command processor introduced in MS-DOS and was also used in the Win9x series of operating systems.cmd.exe
is the 32-bit command processor in Windows NT (64-bit Windows OSes also have a 64-bit version). cmd.exe
was never part of Windows 9x. It originated in OS/2 version 1.0, and the OS/2 version of cmd
began 16-bit (but was nonetheless a fully fledged protected mode program with commands like start
). Windows NT inherited cmd
from OS/2, but Windows NT's Win32 version started off 32-bit. Although OS/2 went 32-bit in 1992, its cmd
remained a 16-bit OS/2 1.x program.ComSpec
env variable defines which program is launched by .bat
and .cmd
scripts. (Starting with WinNT this defaults to cmd.exe
.)cmd.exe
is backward compatible with command.com
.cmd.exe
can be named .cmd
to prevent accidental execution on Windows 9x. This filename extension also dates back to OS/2 version 1.0 and 1987.Here is a list of cmd.exe
features that are not supported by command.com
:
^
(Use for: \ & | > < ^
)PUSHD
/POPD
SET /A i+=1
SET %varname:expression%
FOR /F
(existed before, has been enhanced)CALL :label
Order of Execution:
If both .bat and .cmd versions of a script (test.bat, test.cmd) are in the same folder and you run the script without the extension (test), by default the .bat version of the script will run, even on 64-bit Windows 7. The order of execution is controlled by the PATHEXT environment variable. See Order in which Command Prompt executes files for more details.
References:
wikipedia: Comparison of command shells
I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
As you can see, $rootScope.$broadcast
hits a lot more listeners than $scope.$emit
.
Also, $scope.$emit
's bubbling effect can be cancelled, whereas $rootScope.$broadcast
cannot.
If you are looking for the last row of a column, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Other commands you will need to get familiar with are copy and paste commands:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finally, you can reference worksheets in other workbooks by using the following syntax:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
I think your best bet is to call GetOrdinal("columnName") on your DataReader up front, and catch an IndexOutOfRangeException in case the column isn't present.
In fact, let's make an extension method:
public static bool HasColumn(this IDataRecord r, string columnName)
{
try
{
return r.GetOrdinal(columnName) >= 0;
}
catch (IndexOutOfRangeException)
{
return false;
}
}
Edit
Ok, this post is starting to garner a few down-votes lately, and I can't delete it because it's the accepted answer, so I'm going to update it and (I hope) try to justify the use of exception handling as control flow.
The other way of achieving this, as posted by Chad Grant, is to loop through each field in the DataReader and do a case-insensitive comparison for the field name you're looking for. This will work really well, and truthfully will probably perform better than my method above. Certainly I would never use the method above inside a loop where performace was an issue.
I can think of one situation in which the try/GetOrdinal/catch method will work where the loop doesn't. It is, however, a completely hypothetical situation right now so it's a very flimsy justification. Regardless, bear with me and see what you think.
Imagine a database that allowed you to "alias" columns within a table. Imagine that I could define a table with a column called "EmployeeName" but also give it an alias of "EmpName", and doing a select for either name would return the data in that column. With me so far?
Now imagine that there's an ADO.NET provider for that database, and they've coded up an IDataReader implementation for it which takes column aliases into account.
Now, dr.GetName(i)
(as used in Chad's answer) can only return a single string, so it has to return only one of the "aliases" on a column. However, GetOrdinal("EmpName")
could use the internal implementation of this provider's fields to check each column's alias for the name you're looking for.
In this hypothetical "aliased columns" situation, the try/GetOrdinal/catch method would be the only way to be sure that you're checking for every variation of a column's name in the resultset.
Flimsy? Sure. But worth a thought. Honestly I'd much rather an "official" HasColumn method on IDataRecord.
maybe
string = document.location.href;
arrayOfStrings = string.toString().split('/');
assuming you want the current url
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
For the record, you can use POSIX standard exit codes defined here.
Example:
import sys, os
try:
config()
except:
sys.exit(os.EX_CONFIG)
try:
do_stuff()
except:
sys.exit(os.EX_SOFTWARE)
sys.exit(os.EX_OK) # code 0, all ok
Generics solution to covert any List<Type>
to String []
:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString()
method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
It is not a question of preference. /base
and /base/
have different semantics. In many cases, the difference is unimportant. But it is important when there are relative URLs.
child
relative to /base/
is /base/child
.child
relative to /base
is (perhaps surprisingly) /child
.Use the %
operator with a string:
irb(main):001:0> "%03d" % 5
=> "005"
The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:
irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"
Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C
function printf
, but similar formating functions are available in perl, ruby, python, java, php, etc.
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
There is a way to remove the line.
1) Follow this tutorial: android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.
Well this should change your format to text.
Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
0
\u0000
or 0
0.0
false
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.
This is a useful function for quick and easy xml parsing when an extension is not available:
<?php
/**
* Convert XML to an Array
*
* @param string $XML
* @return array
*/
function XMLtoArray($XML)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $XML, $vals);
xml_parser_free($xml_parser);
// wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
$_tmp='';
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_level!=1 && $x_type == 'close') {
if (isset($multi_key[$x_tag][$x_level]))
$multi_key[$x_tag][$x_level]=1;
else
$multi_key[$x_tag][$x_level]=0;
}
if ($x_level!=1 && $x_type == 'complete') {
if ($_tmp==$x_tag)
$multi_key[$x_tag][$x_level]=1;
$_tmp=$x_tag;
}
}
// jedziemy po tablicy
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_type == 'open')
$level[$x_level] = $x_tag;
$start_level = 1;
$php_stmt = '$xml_array';
if ($x_type=='close' && $x_level!=1)
$multi_key[$x_tag][$x_level]++;
while ($start_level < $x_level) {
$php_stmt .= '[$level['.$start_level.']]';
if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
$php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
$start_level++;
}
$add='';
if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
if (!isset($multi_key2[$x_tag][$x_level]))
$multi_key2[$x_tag][$x_level]=0;
else
$multi_key2[$x_tag][$x_level]++;
$add='['.$multi_key2[$x_tag][$x_level].']';
}
if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
if ($x_type == 'open')
$php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
else
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
if (array_key_exists('attributes', $xml_elem)) {
if (isset($xml_elem['value'])) {
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
foreach ($xml_elem['attributes'] as $key=>$value) {
$php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
eval($php_stmt_att);
}
}
}
return $xml_array;
}
?>
As @snapshoe says
flush()
sends your SQL statements to the database
commit()
commits the transaction.
When session.autocommit == False
:
commit()
will call flush()
if you set autoflush == True
.
When session.autocommit == True
:
You can't call commit()
if you haven't started a transaction (which you probably haven't since you would probably only use this mode to avoid manually managing transactions).
In this mode, you must call flush()
to save your ORM changes. The flush effectively also commits your data.
If you are using ExcelDataReader 3+
you will find that there isn't any method for AsDataSet()
for your reader object, You need to also install another package for ExcelDataReader.DataSet
, then you can use the AsDataSet()
method.
Also there is not a property for IsFirstRowAsColumnNames
instead you need to set it inside of ExcelDataSetConfiguration
.
Example:
using (var stream = File.Open(originalFileName, FileMode.Open, FileAccess.Read))
{
IExcelDataReader reader;
// Create Reader - old until 3.4+
////var file = new FileInfo(originalFileName);
////if (file.Extension.Equals(".xls"))
//// reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(stream);
////else if (file.Extension.Equals(".xlsx"))
//// reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream);
////else
//// throw new Exception("Invalid FileName");
// Or in 3.4+ you can only call this:
reader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream)
//// reader.IsFirstRowAsColumnNames
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
};
var dataSet = reader.AsDataSet(conf);
// Now you can get data from each sheet by its index or its "name"
var dataTable = dataSet.Tables[0];
//...
}
You can find row number and column number of a cell reference like this:
var cellStr = "AB2"; // var cellStr = "A1";
var match = Regex.Match(cellStr, @"(?<col>[A-Z]+)(?<row>\d+)");
var colStr = match.Groups["col"].ToString();
var col = colStr.Select((t, i) => (colStr[i] - 64) * Math.Pow(26, colStr.Length - i - 1)).Sum();
var row = int.Parse(match.Groups["row"].ToString());
Now you can use some loops to read data from that cell like this:
for (var i = row; i < dataTable.Rows.Count; i++)
{
for (var j = col; j < dataTable.Columns.Count; j++)
{
var data = dataTable.Rows[i][j];
}
}
Update:
You can filter rows and columns of your Excel sheet at read time with this config:
var i = 0;
var conf = new ExcelDataSetConfiguration
{
UseColumnDataType = true,
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
FilterRow = rowReader => fromRow <= ++i - 1,
FilterColumn = (rowReader, colIndex) => fromCol <= colIndex,
UseHeaderRow = true
}
};
Yes you can do that by just creating a BroadcastReceiver
that calls your Service
when your Application boots. Here is a complete answer given by me.
Android - Start service on boot
If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Just declare your Service
as declared normally.
WebKit is a layout engine designed to allow web browsers to render web pages. The WebKit engine provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited.
WebKit was originally created as a fork of KHTML as the layout engine for Apple's Safari; it is portable to many other computing platforms. It is also used in Google's Chrome Browser.
WebKit's WebCore and JavaScriptCore components are available under the GNU Lesser General Public License, and the rest of WebKit is available under a BSD-style license.
Source Wikipedia
For further information about layout engines you can look here
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.
The best that you can do is to try to parse "X-Forwarded-For"
and rely on request.getRemoteAddr();
public static String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return request.getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
// we only want the client
return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
}
}