A clone is simply a copy of a repository. On the surface, its result is equivalent to svn checkout
, where you download source code from some other repository. The difference between centralized VCS like Subversion and DVCSs like Git is that in Git, when you clone, you are actually copying the entire source repository, including all the history and branches. You now have a new repository on your machine and any commits you make go into that repository. Nobody will see any changes until you push those commits to another repository (or the original one) or until someone pulls commits from your repository, if it is publicly accessible.
A branch is something that is within a repository. Conceptually, it represents a thread of development. You usually have a master branch, but you may also have a branch where you are working on some feature xyz, and another one to fix bug abc. When you have checked out a branch, any commits you make will stay on that branch and not be shared with other branches until you merge them with or rebase them onto the branch in question. Of course, Git seems a little weird when it comes to branches until you look at the underlying model of how branches are implemented. Rather than explain it myself (I've already said too much, methinks), I'll link to the "computer science" explanation of how Git models branches and commits, taken from the Git website:
http://eagain.net/articles/git-for-computer-scientists/
A fork isn't a Git concept really, it's more a political/social idea. That is, if some people aren't happy with the way a project is going, they can take the source code and work on it themselves separate from the original developers. That would be considered a fork. Git makes forking easy because everyone already has their own "master" copy of the source code, so it's as simple as cutting ties with the original project developers and doesn't require exporting history from a shared repository like you might have to do with SVN.
EDIT: since I was not aware of the modern definition of "fork" as used by sites such as GitHub, please take a look at the comments and also Michael Durrant's answer below mine for more information.
Restart kernel and clear output (if not starting with new notebook), then run
%matplotlib tk
For more info go to Plotting with matplotlib
There are three parts to the answer
To get each character you can iterate through the String using the charAt()
or toCharArray()
methods.
for( char c : s.toCharArray() )
The value of the char is the Unicode value.
The Cyrillic Unicode characters are any character in the following ranges:
Cyrillic: U+0400–U+04FF ( 1024 - 1279)
Cyrillic Supplement: U+0500–U+052F ( 1280 - 1327)
Cyrillic Extended-A: U+2DE0–U+2DFF (11744 - 11775)
Cyrillic Extended-B: U+A640–U+A69F (42560 - 42655)
If it is in this range it is Cyrillic. Just perform an if check. If it is in the range use Integer.toHexString()
and prepend the "\\u"
. Put together it should look something like this:
final int[][] ranges = new int[][]{
{ 1024, 1279 },
{ 1280, 1327 },
{ 11744, 11775 },
{ 42560, 42655 },
};
StringBuilder b = new StringBuilder();
for( char c : s.toCharArray() ){
int[] insideRange = null;
for( int[] range : ranges ){
if( range[0] <= c && c <= range[1] ){
insideRange = range;
break;
}
}
if( insideRange != null ){
b.append( "\\u" ).append( Integer.toHexString(c) );
}else{
b.append( c );
}
}
return b.toString();
Edit: probably should make the check c < 128
and reverse the if
and the else
bodies; you probably should escape everything that isn't ASCII. I was probably too literal in my reading of your question.
if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:
/^123456$/
in perl the test for matching the password would be something like
print "MATCH_OK" if ($input_pass=~/^123456$/);
EDIT:
bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way
as a second thought, you may want to consider a safer authentication mechanism :)
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"}
is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:
=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))
I wrote git-playback for this exact purpose
pip install git-playback
git playback [filename]
This has the benefit of both displaying the results in the command line (like git log -p
) while also letting you step through each commit using the arrow keys (like gitk
).
Possibility 1: Just make 2 .bat files and write into the first:
start <filename> // name of 2nd batch file
exit
Batch file 2 is the file that wont close in the end. So now when you open batch nr.1 It will start the 2nd and cloe itself. When the 2nd finishes it will not close entirely (as long as you wont put exit at the end)
Possibility 2: Batch file 1:
call <filename>
cls
echo End of file
pause
<any code you want>
When the 2nd file ends then it will proceed to file 1 again and output the rest of it. With that you can even make error handlers. If nr.1 crashes it goes into nr.2 and displays it
Another option that may be suitable in this situation is using XML
The XML option to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.
The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).
Vertical expansion
Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.
Horizontal expansion
Unlike the PIVOT, newly added documents can be displayed without altering the script.
Performance breakdown
In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.
You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
I found the easy way
--- right click the webconfig or app config file and click EDIT WCF CONFIGURATION and got to bingdigs ans select yore service and right side show maxReciveMessageSize give a large number ---
You can use this drawable xml and set as background to cardview :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff"/>
<stroke android:width="1dp"
android:color="#ff000000"
/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
/>
<corners
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Since XCode 4.3 the location has changed, the simulator can now be found at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/
Boost.Regex is very good and is slated to become part of the C++0x standard (it's already in TR1).
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
Update: If you're using a C++11 compliant compiler (gcc 4.8 is NOT!), use std::regex unless you have good reason to use something else.
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
You need to put background-color
on the option
tag and not the select
tag...
select option {
margin: 40px;
background: rgba(0, 0, 0, 0.3);
color: #fff;
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
If you want to style each one of the option
tags.. use the css attribute
selector:
select option {_x000D_
margin: 40px;_x000D_
background: rgba(0, 0, 0, 0.3);_x000D_
color: #fff;_x000D_
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
}_x000D_
_x000D_
select option[value="1"] {_x000D_
background: rgba(100, 100, 100, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="2"] {_x000D_
background: rgba(150, 150, 150, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="3"] {_x000D_
background: rgba(200, 200, 200, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="4"] {_x000D_
background: rgba(250, 250, 250, 0.3);_x000D_
}
_x000D_
<select>_x000D_
<option value="">Please choose</option>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option>_x000D_
<option value="3">Option 3</option>_x000D_
<option value="4">Option 4</option>_x000D_
</select>
_x000D_
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
It will return the index of the item in the array. If it's not found you will get -1
Another option is to use the cross-platform AutoPy package. This package has two different options for moving the mouse:
This code snippet will instantly move the cursor to position (200,200):
import autopy
autopy.mouse.move(200,200)
If you instead want the cursor to visibly move across the screen to a given location, you can use the smooth_move command:
import autopy
autopy.mouse.smooth_move(200,200)
When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe
I had to choose the following options to get the management Tools:
When I was done I had an option "SQL Server Management Studio" within my Start Menu.
Searching for "Management" pulled it up faster within the Start Menu.
In windows 7, you may have to edit this file
C:\Users\<UserName>\AppData\Roaming\Subversion\servers
[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
This is the code I'm using right now for a website I'm making that needs to get the leading paragraphs / summary / section 0 of off Wikipedia articles, and it's all done within the browser (client side javascript) thanks to the magick of JSONP! --> http://jsfiddle.net/gautamadude/HMJJg/1/
It uses the Wikipedia API to get the leading paragraphs (called section 0) in HTML like so: http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text§ion=0&callback=?
It then strips the HTML and other undesired data, giving you a clean string of an article summary, if you want you can, with a little tweaking, get a "p" html tag around the leading paragraphs but right now there is just a newline character between them.
Code:
var url = "http://en.wikipedia.org/wiki/Stack_Overflow";
var title = url.split("/").slice(4).join("/");
//Get Leading paragraphs (section 0)
$.getJSON("http://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text§ion=0&callback=?", function (data) {
for (text in data.parse.text) {
var text = data.parse.text[text].split("<p>");
var pText = "";
for (p in text) {
//Remove html comment
text[p] = text[p].split("<!--");
if (text[p].length > 1) {
text[p][0] = text[p][0].split(/\r\n|\r|\n/);
text[p][0] = text[p][0][0];
text[p][0] += "</p> ";
}
text[p] = text[p][0];
//Construct a string from paragraphs
if (text[p].indexOf("</p>") == text[p].length - 5) {
var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
for (newline in splitNewline) {
if (splitNewline[newline].substring(0, 11) != "Cite error:") {
pText += splitNewline[newline];
pText += "\n";
}
}
}
}
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
document.getElementById('textarea').value = pText
document.getElementById('div_text').textContent = pText
}
});
You have to add reference to
Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
It can be found at C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\
directory (for VS2010 professional or above; .NET Framework 4.0).
or right click on your project and select: Add Reference... > .NET:
If you have more then 1 dimension array
with open("file.txt", 'w') as output:
for row in values:
output.write(str(row) + '\n')
Code to write without '[' and ']'
with open("file.txt", 'w') as file:
for row in values:
s = " ".join(map(str, row))
file.write(s+'\n')
with your own soup object:
soup.p.next_sibling.strip()
soup.p
*(this hinges on it being the first <p> in the parse tree)next_sibling
on the tag object that soup.p
returns since the desired text is nested at the same level of the parse tree as the <p> .strip()
is just a Python str method to remove leading and trailing whitespace*otherwise just find the element using your choice of filter(s)
in the interpreter this looks something like:
In [4]: soup.p
Out[4]: <p>something</p>
In [5]: type(soup.p)
Out[5]: bs4.element.Tag
In [6]: soup.p.next_sibling
Out[6]: u'\n THIS IS MY TEXT\n '
In [7]: type(soup.p.next_sibling)
Out[7]: bs4.element.NavigableString
In [8]: soup.p.next_sibling.strip()
Out[8]: u'THIS IS MY TEXT'
In [9]: type(soup.p.next_sibling.strip())
Out[9]: unicode
MJB
Please try this
In eclipse "Right click" on the text file u wanna use, see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")
put this complete path and try.
if it works then class-path issue else GOK :)
When I open a "DOS" command prompt, I use a batch file which sets all of the options I need and adds my old-time dos utilities to the path too.
@set path=%path%;c:\utils
@doskey cd=cd/d $*
@cd \wip
@cmd.exe
The doskey line sets the CD command so that it will do both drive and folder simultaneously. If this doesn't work, it is possibly because of the version of windows that you're running.
As mentioned already primitives can not be set to the Object type null.
What I do in such cases is just to use -1
or Long.MIN_VALUE
.
I was trying to import numpy in python 3.2.1 on windows 7.
Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it
cd numpy-1.6
python setup.py install
but got an error with a statement as below
unable to find vcvarsall.bat
For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.
In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"
Installation went smoothly and now I am able to import numpy without using mingW.
Long story short try using windows installer for numpy, if one is available.
square = function(a) {
if ((a * 0) == 0) {
return a*a;
} else {
return "Enter a valid number.";
}
}
It is not entirely clear what you want, but I would use numpy.random.randint:
import numpy.random as nprnd
import timeit
t1 = timeit.Timer('[random.randint(0, 1000) for r in xrange(10000)]', 'import random') # v1
### Change v2 so that it picks numbers in (0, 10000) and thus runs...
t2 = timeit.Timer('random.sample(range(10000), 10000)', 'import random') # v2
t3 = timeit.Timer('nprnd.randint(1000, size=10000)', 'import numpy.random as nprnd') # v3
print t1.timeit(1000)/1000
print t2.timeit(1000)/1000
print t3.timeit(1000)/1000
which gives on my machine:
0.0233682730198
0.00781716918945
0.000147947072983
Note that randint is very different from random.sample (in order for it to work in your case I had to change the 1,000 to 10,000 as one of the commentators pointed out -- if you really want them from 0 to 1,000 you could divide by 10).
And if you really don't care what distribution you are getting then it is possible that you either don't understand your problem very well, or random numbers -- with apologies if that sounds rude...
I ended up adding the following method to jQuery in my script:
jQuery["postJSON"] = function( url, data, callback ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
contentType:"application/json; charset=utf-8",
dataType: "json",
data: data,
success: callback
});
};
And to use it
$.postJSON('http://url', {data: 'goes', here: 'yey'}, function (data, status, xhr) {
alert('Nailed it!')
});
This was done by simply copying the code of "get" and "post" from the original JQuery sources and hardcoding a few parameters to force a JSON POST.
Thanks!
That way you haven't installed pip, you installed just the easy_install
i.e. setuptools
.
First you should remove all the packages you installed with easy_install
using (see uninstall):
easy_install -m PackageName
This includes pip
if you installed it using easy_install pip
.
After this you remove the setuptools
following the instructions from here:
If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:
setuptools-*.egg
If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:
pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
It is quite useful, when you are running on the unix platform, and need to create a text file which will be opened on the dos platform.
Unix uses '\n' as its line terminator, and dos uses '\r\n' as its line terminator, so you can use it to create a dos text file.
The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers
) mandates that identifiers must not start with a digit:
identifier:
identifier-nondigit
identifier identifier-nondigit
identifier digit
identifier-nondigit:
nondigit
universal-character-name
other implementation-defined characters>
nondigit: one of
_ a b c d e f g h i j k l m
n o p q r s t u v w x y z
A B C D E F G H I J K L M
N O P Q R S T U V W X Y Z
digit: one of
0 1 2 3 4 5 6 7 8 9
The correct form for using the pre-processor to block out code is:
#if 0
: : :
#endif
You can also use:
#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif
but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED
or DONOTCOMPILE
which others may also use. To be safe, the #if
option should be preferred.
The link posted by Jose has been updated and pylab now has a tight_layout()
function that does this automatically (in matplotlib version 1.1.0).
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout
http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout
// usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd -
// prereqs: , nodejs , mocha
// URI = scheme:[//authority]path[?paramName1=paramValue1¶mName2=paramValue2][#fragment]
// call by: uri = uri.setUriParam("as","md")
String.prototype.setUriParam = function (paramName, paramValue) {
var uri = this
var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0]
if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' }
uri = uri.replace ( '?' + paramName , '?&' + paramName)
var toRepl = (paramValue != null) ? ('$1' + paramValue) : ''
var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)')
uri = uri.replace(toSrch,toRepl)
if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) {
var ampersandMayBe = uri.endsWith('&') ? '' : '&'
uri = uri + ampersandMayBe + paramName + "=" + String(paramValue)
}
uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment
return uri
}
var assert = require('assert');
describe('replacing url param value', function () {
// scheme://authority/path[?p1=v1&p2=v2#fragment
// a clean url
it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with num value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? but string value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz'
var uriActual = uri.setUriParam("bid","boo-bar-baz")
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& but string value
it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param
it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param
it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param with fragment
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param with fragment
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// add a new param name , param value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f'
var uriActual = uri.setUriParam("bid","foo-bar")
assert.equal(uriActual, uriExpected);
});
});
HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen
in php.ini is set to true.
The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:
v = numpy.diff(t)
Simply defining an app namespace in your xml file can cause this. This was a completely innocuous line that only selected out one symbol (out of many) to make unresolved. Simply removing the entire line, greyed in the pic below, enabled my code to reference to unresolved symbol. Even when I added the line back it decided to build without problem. Go figure.
Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...
This works from my Windows 10's cmd.exe prompt
powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"
This example shows
Try this:
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = DataGridView1.Rows.Add();
DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
if ((bool)item["productstatus"])
{
DataGridView1.Rows[n].Cells[3].Value = "Active";
}
else
{
DataGridView1.Rows[n].Cells[3].Value = "Deactive";
}
If your data may contain multi-byte sequences (not a plain ASCII sequence) and your browser has TextDecoder, then you should use that to decode your data (specify the required encoding for the TextDecoder):
var u8 = new Uint8Array([65, 66, 67, 68]);
var decoder = new TextDecoder('utf8');
var b64encoded = btoa(decoder.decode(u8));
If you need to support browsers that do not have TextDecoder (currently just IE and Edge), then the best option is to use a TextDecoder polyfill.
If your data contains plain ASCII (not multibyte Unicode/UTF-8) then there is a simple alternative using String.fromCharCode
that should be fairly universally supported:
var ascii = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(String.fromCharCode.apply(null, ascii));
And to decode the base64 string back to a Uint8Array:
var u8_2 = new Uint8Array(atob(b64encoded).split("").map(function(c) {
return c.charCodeAt(0); }));
If you have very large array buffers then the apply may fail and you may need to chunk the buffer (based on the one posted by @RohitSengar). Again, note that this is only correct if your buffer only contains non-multibyte ASCII characters:
function Uint8ToString(u8a){
var CHUNK_SZ = 0x8000;
var c = [];
for (var i=0; i < u8a.length; i+=CHUNK_SZ) {
c.push(String.fromCharCode.apply(null, u8a.subarray(i, i+CHUNK_SZ)));
}
return c.join("");
}
// Usage
var u8 = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(Uint8ToString(u8));
you need to initialize the object elements of the array.
GameObject[] houses = new GameObject[200];
for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}
Of course you initialize elements selectively using different constructors anywhere else before you reference them.
In my case the problem happened after we migrated to AndroidX. For some reason, app was calling MultiDex.install() with reflection:
final Class<?> clazz = Class.forName("android.support.multidex.MultiDex");
final Method method = clazz.getDeclaredMethod("install", Context.class);
method.invoke(null, this);
I changed package from android.support.multidex.MultiDex
to androidx.multidex.MultiDex
. It worked.
The list of unstaged modified can be obtained using git status
and the grep
command like below. Something like git status -s | grep M
:
root@user-ubuntu:~/project-repo-directory# git status -s | grep '^ M'
M src/.../file1.js
M src/.../file2.js
M src/.../file3.js
....
You can Use ngValue
. ngValue
passes sting and object both.
Pass as Object:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj.value">
{{obj.value}}
</option>
</select>
Pass as String:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj">
{{obj.value}}
</option>
</select>
None of the answers satisfied my needs fully, so here we go:
git branch --merged | grep -E "(feature|bugfix|hotfix)/" | xargs git branch -D && git remote prune origin
This will delete all local branches which are merged and starting with feature/
, bugfix/
or hotfix/
. Afterwards the upstream remote origin
is pruned (you may have to enter a password).
Works on Git 1.9.5.
float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);
Let's define a list first:
lst=[1,2,3]
You can directly write your list to a file:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
To read your list from text file first you read the file and store in a variable:
f=open("filename.txt","r")
lst=f.read()
f.close()
The type of variable lst
is of course string. You can convert this string into array using eval
function.
lst=eval(lst)
The probably only way which is marginally faster than
d = [[] for x in xrange(n)]
is
from itertools import repeat
d = [[] for i in repeat(None, n)]
It does not have to create a new int
object in every iteration and is about 15 % faster on my machine.
Edit: Using NumPy, you can avoid the Python loop using
d = numpy.empty((n, 0)).tolist()
but this is actually 2.5 times slower than the list comprehension.
I prefer this
if(in_array($id,$user_access_arr) == false)
respective
if (in_array(search_value, array) == false)
// value is not in array
document.getElementById("address_box").value =
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
Try to add this hotfix: hotfixv4.microsoft.com/Windows%207/Windows%20Server2008%20R2%20SP1/sp2/Fix362872/7600/free/427221_intl_i386_zip.exe
Do as Rabbott says, or if you refuse jQuery:
<script type="text/javascript">
function get_action() { // inside script tags
return form_action;
}
</script>
<form action="" onsubmit="this.action=get_action();">
...
</form>
If you want to exclude all the standard properties of the window object and view application-specific globals, this will print them to the Chrome console:
{
const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);
for (const key of Object.keys(window)) {
if (!standardGlobals.has(key)) {
console.log(key)
}
}
}
The script works well as a bookmarklet. To use the script as a bookmarklet, create a new bookmark and replace the URL with the following:
javascript:(() => {
const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);
for (const key of Object.keys(window)) {
if (!standardGlobals.has(key)) {
console.log(key)
}
}
})()
With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.
However, in the old days, when memory was at a premium, the common practice was to read strings in chunks. fgets
reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.
in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readinput()
{
#define CHUNK 200
char* input = NULL;
char tempbuf[CHUNK];
size_t inputlen = 0, templen = 0;
do {
fgets(tempbuf, CHUNK, stdin);
templen = strlen(tempbuf);
input = realloc(input, inputlen+templen+1);
strcpy(input+inputlen, tempbuf);
inputlen += templen;
} while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n');
return input;
}
int main()
{
char* result = readinput();
printf("And the result is [%s]\n", result);
free(result);
return 0;
}
Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of fgets
.
Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.
If you want to avoid that on client side you can add something like ?v=1.x
to css file link, when the file content is changed. for example if there was <link rel="stylesheet" type="text/css" href="css-file-name.css">
you can change it to <link rel="stylesheet" type="text/css" href="css-file-name.css?v=1.1">
this will bypass caching.
No matter how many times you call Class.forName() method, Only once the static block gets executed not multiple time:
package forNameMethodDemo;
public class MainClass {
public static void main(String[] args) throws Exception {
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
DemoClass demoClass = (DemoClass)Class.forName("forNameMethodDemo.DemoClass").newInstance();
}
}
public class DemoClass {
static {
System.out.println("in Static block");
}
{
System.out.println("in Instance block");
}
}
output will be:
in Static block
in Instance block
This in Static block
statement is printed only once not three times.
To resolve the conflicts, use Git stash to save away your uncommitted changes; then pull down the remote repository change set; then pop your local stash to reapply your uncommitted changes.
In Eclipse v4.5 (Mars) to stash changes (a relatively recent addition, wasn't in previous EGit) I do this: right-click on a top-level Eclipse project that's in Git control, pick Team, pick Stashes, pick Stash Changes; a dialog opens to request a stash commit message.
You must use the context menu on a top level project! If I right click on a directory or file within a Git-controlled project I don't get the appropriate context menu.
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
I think you need the Web Tools Platform package for this. Not very sure though. You can add it to your current eclipse through Help > install new software.
Then add the software repository site location for WTP for your version of eclipse. This is how you can install plugins in eclipse.
Now, Use command
Update 2020: 04
To install Java7 with homebrew run:
brew tap homebrew/cask-versions
brew cask install java7
Hope this help.
PK - Primary Key
NN - Not Null
BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)
UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)
UQ - Create/remove Unique Key
ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )
AI - Auto Increment
G - Generated column. i.e. value generated by a formula based on the other columns
In a simple manner you can also try to just run a pre-packaged docker with intellij, I found the good job of @dlsniper : https://hub.docker.com/r/dlsniper/docker-intellij/
you just need to have docker installed and to run :
docker run -tdi \
--net="host" \
--privileged=true \
-e DISPLAY=${DISPLAY} \
-v /tmp/.X11-unix:/tmp/.X11-unix \
-v ${HOME}/.IdeaIC2016.1_docker:/home/developer/.IdeaIC2016.1 \
-v ${GOPATH}:/home/developer/go \
dlsniper/docker-intellij
I wouldn't recommend doing this, but you can override the ngClick
directive to do what you are looking for. That's not saying, you should.
With the original implementation in mind:
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
We can do this to override it:
// Go into your config block and inject $provide.
app.config(function ($provide) {
// Decorate the ngClick directive.
$provide.decorator('ngClickDirective', function ($delegate) {
// Grab the actual directive from the returned $delegate array.
var directive = $delegate[0];
// Stow away the original compile function of the ngClick directive.
var origCompile = directive.compile;
// Overwrite the original compile function.
directive.compile = function (el, attrs) {
// Apply the original compile function.
origCompile.apply(this, arguments);
// Return a new link function with our custom behaviour.
return function (scope, el, attrs) {
// Get the name of the passed in function.
var fn = attrs.ngClick;
el.on('click', function (event) {
scope.$apply(function () {
// If no property on scope matches the passed in fn, return.
if (!scope[fn]) {
return;
}
// Throw an error if we misused the new ngClick directive.
if (typeof scope[fn] !== 'function') {
throw new Error('Property ' + fn + ' is not a function on ' + scope);
}
// Call the passed in function with the event.
scope[fn].call(null, event);
});
});
};
};
return $delegate;
});
});
Then you'd pass in your functions like this:
<div ng-click="func"></div>
as opposed to:
<div ng-click="func()"></div>
jsBin: http://jsbin.com/piwafeke/3/edit
Like I said, I would not recommend doing this but it's a proof of concept showing you that, yes - you can in fact overwrite/extend/augment the builtin angular behaviour to fit your needs. Without having to dig all that deep into the original implementation.
Do please use it with care, if you were to decide on going down this path (it's a lot of fun though).
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
You can also reset page number counter:
\setcounter{page}{1}
However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:
\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...
if you're not using the ->
format, you can do this:
$a = "SQL command...";
if ($b = mysqli_query($con,$a)) {
// results was successful
} else {
// result was not successful
}
Thanks to this thread (https://community.oracle.com/thread/473276)
select sys_context('userenv','service_name') from dual;
It can be executed with a regular user account, no need for sysdba rights
In my case issue was that numberOfRowsInSection
was returning similar number of rows after calling tableView.deleteRows(...)
.
Since this was the required behaviour in my case, I ended up calling tableView.reloadData()
instead of tableView.deleteRows(...)
in cases where numberOfRowsInSection
will remain same after deleting a row.
My solution:
First create "<style>" tags with an ID.
<style id="YourID">
.YourClass {background-color:red}
</style>
Then, I create a function in JavaScript like this:
document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'
Worked like a charm for me.
That's right. You could try it in the interpreter like this:
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
Imagine a counter with an initial value of 0
.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
The file extension tells you how the image is saved. Some of those formats just save the bits as they are, some compress the image in different ways, including lossless and lossy methods. The Web can tell you, although I know some of the patient responders will outline them here.
The web favors gif, jpg, and png, mostly. JPEG is the same (or very close) to jpg.
$aa = fopen('a.txt','r');
echo fread($aa,filesize('a.txt'));
$a = fopen('a.txt','r');
while(!feof($a)){echo fgets($a)."<br>";}
fclose($a);
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):
JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2
The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.
Creating a new React app in C:\Users\CM\Downloads\react\github-profile.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
npm ERR! path C:\Users\CM\AppData\Roaming\npm-cache_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996b1fa335b1
0893d67f7339e4af62bb688c0da2aaca839d4c9d51e2eb015eec65545008a3cad93d00f806
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall lstat
npm ERR! Error: EPERM: operation not permitted, lstat
'C:\Users\CM\AppData\Roaming\npm-cache_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996
b1fa335b10893d67f7339e4af62bb688c0da2aaca839d4c9d51e2eb015eec6
5545008a3cad93d00f806'
npm ERR! { [Error: EPERM: operation not permitted, lstat
'C:\Users\CM\AppData\Roaming\npm-cache_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996b1f
a335b10893d67f7339e4af62bb688c0da2aaca839d4c9d51e2eb015eec6554500
8a3cad93d00f806']
npm ERR! cause:
npm ERR! { Error: EPERM: operation not permitted, lstat
'C:\Users\CM\AppData\Roaming\npm-cache_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996b1
fa335b10893d67f7339e4
af62bb688c0da2aaca839d4c9d51e2eb015eec65545008a3cad93d00f806'
npm ERR! errno: -4048,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'lstat',
npm ERR! path:
npm ERR! 'C:\Users\CM\AppData\Roaming\npm-cache\_cacache\content-
npm ERR! stack:
npm ERR! 'Error: EPERM: operation not permitted, lstat
'C:\Users\CM\AppData\Roaming\npm-cache\_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996
b1fa335b10893d67f7339e4af62bb688c0da2aaca839d4c9d51e2eb015
eec65545008a3cad93d00f806'',
npm ERR! errno: -4048,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'lstat',
npm ERR! path:
npm ERR! 'C:\Users\CM\AppData\Roaming\npm-cache\_cacache\content-
v2\sha512\36\c6\c3e97514319bc1c6d40026e58325e782e1016c996b1fa335
b10893d67f7339e4af62bb688c0da2aaca839d4c9d51e2eb015eec65545008a3cad93
d00f806',
npm ERR! parent: 'postcss-image-set-function' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a
text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-
check thenpm ERR! permissions of the file and its containing directories, or
try running
npm ERR! the command again as root/Administrator (though this is not
recommended).
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\CM\AppData\Roaming\npm-cache_logs\2019-03-22T10_
27_19_722Z-debug.log
Aborting installation.
npm install --save --save-exact --loglevel error react react-dom react-
scripts has failed.
Deleting generated file... node_modules
Deleting generated file... package.json
Deleting GitHub-profile/ from C:\Users\CM\Downloads\reactDone.``
i was facing similar error but i tried to run create-react-app command many times and finally it was created , this was the problem with my internet connection. check your internet connection
Whenever you update your Gradle files do not forget to check the compatible Gradle wrapper distibutionUrl
, in your case it happened because of the same.
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip
As @Didier said, you can change your delimiter to something other than /
:
grep -rl $oldstring /path/to/folder | xargs sed -i s@$oldstring@$newstring@g
Use the where
command. The first result in the list is the one that will execute.
C:\> where notepad C:\Windows\System32\notepad.exe C:\Windows\notepad.exe
According to this blog post, where.exe
is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.
On Linux, the equivalent is the which
command, e.g. which ssh
.
You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.
If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:
-- dummy ITEM table as we don't know what the real ones looks like
create table item(
item_num number,
currency varchar2(9)
)
/
insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');
create package so_5165580 as
type exch_row is record(
exch_rt_eur number,
exch_rt_usd number);
type exch_tbl is table of exch_row index by varchar2(9);
exch_rt exch_tbl;
procedure show_items;
end so_5165580;
/
create package body so_5165580 as
procedure populate_rates is
rate exch_row;
begin
rate.exch_rt_eur := 0.614394;
rate.exch_rt_usd := 0.8494;
exch_rt('GBP') := rate;
rate.exch_rt_eur := 0.9817;
rate.exch_rt_usd := 1.3572;
exch_rt('AUD') := rate;
end;
procedure show_items is
cursor c0 is
select i.*
from item i;
begin
for r0 in c0 loop
if exch_rt.exists(r0.currency) then
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' EUR ' || exch_rt(r0.currency).exch_rt_eur
|| ' USD ' || exch_rt(r0.currency).exch_rt_usd);
else
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' ** no rates defined **');
end if;
end loop;
end;
begin
populate_rates;
end so_5165580;
/
So inside your loop, wherever you would have expected to use r0.exch_rt_eur
you instead use exch_rt(r0.currency).exch_rt_eur
, and the same for USD. Testing from an anonymous block:
begin
so_5165580.show_items;
end;
/
Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **
Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert
statement. Assuming EXCH
holds exchange rates of other currencies against the Euro, including USD with currency_key=1
:
insert into detail_items
with rt as (select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key)
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
With items valued at 19.99 GBP and 25.00 AUD, you get detail_items
:
DOC DOC_CURRENCY NET_VALUE NET_VALUE_IN_USD NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1 GBP 19.99 32.53611 23.53426
2 AUD 25 25.46041 18.41621
If you want the currency stuff to be more re-usable you could create a view:
create view rt as
select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;
And then insert using values from that:
insert into detail_items
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
It is about mathematical data transformations over time (or ignoring time).
In code this means functional purity and declarative programming.
State bugs are a huge problem in the standard imperative paradigm. Various bits of code may change some shared state at different "times" in the programs execution. This is hard to deal with.
In FRP you describe (like in declarative programming) how data transforms from one state to another and what triggers it. This allows you to ignore time because your function is simply reacting to its inputs and using their current values to create a new one. This means that the state is contained in the graph (or tree) of transformation nodes and is functionally pure.
This massively reduces complexity and debugging time.
Think of the difference between A=B+C in math and A=B+C in a program. In math you are describing a relationship that will never change. In a program, its says that "Right now" A is B+C. But the next command might be B++ in which case A is not equal to B+C. In math or declarative programming A will always be equal to B+C no matter what point in time you ask.
So by removing the complexities of shared state and changing values over time. You program is much easier to reason about.
An EventStream is an EventStream + some transformation function.
A Behaviour is an EventStream + Some value in memory.
When the event fires the value is updated by running the transformation function. The value that this produces is stored in the behaviours memory.
Behaviours can be composed to produce new behaviours that are a transformation on N other behaviours. This composed value will recalculate as the input events (behaviours) fire.
"Since observers are stateless, we often need several of them to simulate a state machine as in the drag example. We have to save the state where it is accessible to all involved observers such as in the variable path above."
Quote from - Deprecating The Observer Pattern http://infoscience.epfl.ch/record/148043/files/DeprecatingObserversTR2010.pdf
This is a very simple script to solve the problem
export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`
And for testing:
echo $JAVA_HOME
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
To write inline styling use:
<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>
Inline styling serves a purpose however, it is not recommended in most situations.
The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.
if you have the file structure:
index.html
>>/css/
>>/css/styles.css
Then in your HTML document between <head>
and </head>
write:
<link href="css/styles.css" rel="stylesheet" />
Then, change your div structure to be:
<div id="someidname" class="someclassname">
asdfashdjkfhaskjdf
</div>
In css, you can reference your div from the ID or the CLASS.
To do so write:
.someclassname { height: 100px; }
OR
#someidname { height: 100px; }
Note that if you do both, the one that comes further down the file structure will be the one that actually works.
For example... If you have:
.someclassname { height: 100px; }
.someclassname { height: 150px; }
Then in this situation the height will be 150px.
EDIT:
To answer your secondary question from your edit, probably need overflow: hidden;
or overflow: visible;
. You could also do this:
<div class="span12">
<div style="height:100px;">
asdfashdjkfhaskjdf
</div>
</div>
If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.
You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:
1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)
2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)
3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized
4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request
5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.
Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken
Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.
One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).
You can learn more about JWTs from this link
Just use TreeMap
new TreeMap<String, String>(unsortMap);
Be aware that the TreeMap is sorted according to the natural ordering of its 'keys'
You can simply use a controller method like this:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile file) {
try {
// Handle the received file here
// ...
}
catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile
Without any additional configurations for Spring Boot.
Using the following html form client side:
<html>
<body>
<form action="/uploadFile" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
If you want to set limits on files size you can do it in the application.properties
:
# File size limit
multipart.maxFileSize = 3Mb
# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb
Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/
Just in case of someone has the same problem. I'am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8"
, the problem is gone.
Here's a bit of a polyfill that leverages document.CurrentScript
if it exists and falls back to finding the script by ID.
<script id="uniqueScriptId">
(function () {
var thisScript = document.CurrentScript || document.getElementByID('uniqueScriptId');
// your code referencing thisScript here
());
</script>
If you include this at the top of every script tag I believe you'll be able to consistently know which script tag is being fired, and you'll also be able to reference the script tag in the context of an asynchronous callback.
Untested, so leave feedback for others if you try it.
Since NumPy version 1.13 it contains an isnat
function:
>>> import numpy as np
>>> np.isnat(np.datetime64('nat'))
True
It also works for arrays:
>>> np.isnat(np.array(['nat', 1, 2, 3, 4, 'nat', 5], dtype='datetime64[D]'))
array([ True, False, False, False, False, True, False], dtype=bool)
The following construction was not working correctly for me:
request.Credentials = new NetworkCredential("user", "pass");
I have used CredentialCache
instead:
CredentialCache credentialCache = new CredentialCache
{
{
new Uri($"http://{request.Host}/"), "Basic",
new NetworkCredential("user", "pass")
}
};
request.Credentials = credentialCache;
However, if you would like to add multiple basic auth credentials (for example if there is redirection that you are aware of) you can use following function that I have made:
private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential)
{
if (request.Credentials == null)
{
request.Credentials = new CredentialCache();
}
if (request.Credentials.GetCredential(uriPrefix, authType) == null)
{
(request.Credentials as CredentialCache).Add(uriPrefix, authType, credential);
}
}
I hope it will help somebody in the future.
If you're using Ubuntu, you can put a shell script in one of these folders: /etc/cron.daily
, /etc/cron.hourly
, /etc/cron.monthly
or /etc/cron.weekly
.
For more detail, check out this post: https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job
For some reason the above accepted answer does not work in New versions of Angular (V6).
for that use this..
async delay(ms: number) {
await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}
above worked for me.
Usage:
this.delay(3000);
OR more accurate way
this.delay(3000).then(any=>{
//your task after delay.
});
Finally, Anaconda3-2020.07 is out and its core is Python 3.8!
You can now download Anaconda packed with Python 3.8 goodness at:
Straightforward way:
char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];
Safer way:
char aChar = '0' + i;
Generic way:
itoa(i, ...)
Handy way:
sprintf(myString, "%d", i)
C++ way: (taken from Dave18 answer)
std::ostringstream oss;
oss << 6;
Boss way:
Joe, write me an int to char converter
Studboss way:
char aChar = '6';
Joe's way:
char aChar = '6'; //int i = 6;
Nasa's way:
//Waiting for reply from satellite...
Alien's way: '9'
//Greetings.
God's way:
Bruh I built this
Peter Pan's way:
char aChar;
switch (i)
{
case 0:
aChar = '0';
break;
case 1:
aChar = '1';
break;
case 2:
aChar = '2';
break;
case 3:
aChar = '3';
break;
case 4:
aChar = '4';
break;
case 5:
aChar = '5';
break;
case 6:
aChar = '6';
break;
case 7:
aChar = '7';
break;
case 8:
aChar = '8';
break;
case 9:
aChar = '9';
break;
default:
aChar = '?';
break;
}
Santa Claus's way:
//Wait till Christmas!
sleep(457347347);
Gravity's way:
//What
'6' (Jersey) Mikes'™ way:
//
SO way:
Guys, how do I avoid reading beginner's guide to C++?
My way:
or the highway.
Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.
Edit: satisfied?
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.
(By the way, I'm a little worried about your method being const
and returning a non-const
attribute. For philosophical reasons, I'd suggest returning const Attr *
. If you also may want to modify this attribute, you can overload with a non-const
method returning a non-const
attribute as well.)
You're mistaken on point three. Two entries can have the same hash code but not be equal. Take a look at the implementation of HashMap.get from the OpenJdk. You can see that it checks that the hashes are equal and the keys are equal. Were point three true, then it would be unnecessary to check that the keys are equal. The hash code is compared before the key because the former is a more efficient comparison.
If you're interested in learning a little more about this, take a look at the Wikipedia article on Open Addressing collision resolution, which I believe is the mechanism that the OpenJdk implementation uses. That mechanism is subtly different than the "bucket" approach one of the other answers mentions.
this:
$('#rblDiv input').click(function(){
alert($('#rblDiv input').index(this));
});
will get you the index of the radio button that was clicked (i think, untested) (note you've had to wrap your RBL in #rblDiv
you could then use that to display the corresponding div like this:
$('.divCollection div:eq(' + $('#rblDiv input').index(this) +')').show();
Is that what you meant?
Edit: Another approach would be to give the rbl a class name, then go:
$('.rblClass').val();
You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange
can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed.
If you are looking for the more advanced solution, I would suggest checking Resilio Connect.
It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.
Firefox stores that number in this setting (you find it in about:config
): network.http.max-connections-per-server
For the max connections, Firefox stores that in this setting: network.http.max-connections
On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...
This is an easy way to add an underline, while maintaining other settings:
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
In my case, the reason the buttons got pushed up was because the view above them was a ScrollView
, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode
I was setting.
I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting
android:isScrollContainer="false"
on the ScrollView
that sits above the buttons.
Most browsers don't fully support the numerical values for font-weight
. Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.
If you need something bolder then you might want to try using a different font that's bolder than your existing one. Naturally, you could probably adjust the font size for a similar effect.
You can toggle filterstatus
value like this
filterstatus ^= 1;
So your function looks like
function showFilterItem(objButton) {
if (filterstatus == 0) {
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
objButton.value = "Hide Filter";
}
else {
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
objButton.value = "Show filter";
}
filterstatus ^= 1;
}
If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser
)
db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser;
GRANT
db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser;
GRANT
db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser;
GRANT
If your database is using customschema
, execute the above but add one more command:
db=> ALTER USER readonlyuser SET search_path=customschema, public;
ALTER ROLE
setSize
will resize the component to the specified size.
setPreferredSize
sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.
You could also create an ssh tunnel.
docker-compose.yml
:
---
version: '2'
services:
kibana:
image: "kibana:4.5.1"
links:
- elasticsearch
volumes:
- ./config/kibana:/opt/kibana/config:ro
elasticsearch:
build:
context: .
dockerfile: ./docker/Dockerfile.tunnel
entrypoint: ssh
command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"
docker/Dockerfile.tunnel
:
FROM buildpack-deps:jessie
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install ssh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/config && \
chown $USER:$USER -R /root/.ssh
config/ssh/config
:
# Elasticsearch Server
Host elasticsearch
HostName jump.host.czerasz.com
User czerasz
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
This way the elasticsearch
has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
Faced this issue recently with TypeScript 1.0.1, and solved this way:
enum IEvents {
/** A click on a product or product link for one or more products. */
CLICK,
/** A view of product details. */
DETAIL,
/** Adding one or more products to a shopping cart. */
ADD,
/** Remove one or more products from a shopping cart. */
REMOVE,
/** Initiating the checkout process for one or more products. */
CHECKOUT,
/** Sending the option value for a given checkout step. */
CHECKOUT_OPTION,
/** The sale of one or more products. */
PURCHASE,
/** The refund of one or more products. */
REFUND,
/** A click on an internal promotion. */
PROMO_CLICK
}
var Events = [
'click',
'detail',
'add',
'remove',
'checkout',
'checkout_option',
'purchase',
'refund',
'promo_click'
];
function stuff(event: IEvents):boolean {
// event can now be only IEvents constants
Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)
int *pointer[280];
//Creates 280 pointers of type int.
In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.
int (*pointer)[100][280];
// Creates only one pointer which is used to point an array of [100][280] ints.
Here only 4 bytes.
Coming to your question, int (*pointer)[280];
and int (*pointer)[100][280];
are different though it points to same 2D array of [100][280].
Because if int (*pointer)[280];
is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280];
crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.
Adding http://minifiedjs.com/ to the list of answers :)
Code is similar to underscore and others:
var l123 = _.range(1, 4); // same as _(1, 2, 3)
var l0123 = _.range(3); // same as _(0, 1, 2)
var neg123 = _.range(-3, 0); // same as _(-3, -2, -1)
var empty = _.range(2,1); // same as _()
Docs here: http://minifiedjs.com/api/range.html
I use minified.js because it solves all my problems with low footprint and easy to understand syntax. For me, it is a replacement for jQuery, MustacheJS and Underscore/SugarJS in one framework.
Of course, it is not that popular as underscore. This might be a concern for some.
Minified was made available by Tim Jansen using the CC-0 (public domain) license.
for replace all (') in your string, use
.replace(/\'/g,"''")
example:
sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")
it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit
if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte
when in doubt, use VARCHAR2(1 CHAR)
same thing answered here Difference between BYTE and CHAR in column datatypes
Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB
in Oracle, don't use VARCHAR
Adding additional information to emboss's answer.
To put it simply, there is an incorrect cert in your certificate chain.
For example, your certificate authority will have most likely given you 3 files.
You most likely combined all of these files into one bundle.
-----BEGIN CERTIFICATE-----
(Your Primary SSL certificate: your_domain_name.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Intermediate certificate: DigiCertCA.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Root certificate: TrustedRoot.crt)
-----END CERTIFICATE-----
If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.
Redownload all certs from your certificate authority and make a fresh bundle.
All of the previous answer doesn't work if the desired focus element is injected in a directive template. The following directive fit to both simple element or directive injected element (I wrote it in typescript). it accept selector for inner focusable element. if you just need to focus the self element - don't send any selector parameter to the directive :
module APP.Directives {
export class FocusOnLoadDirective implements ng.IDirective {
priority = 0;
restrict = 'A';
constructor(private $interval:any, private $timeout:any) {
}
link = (scope:ng.IScope, element:JQuery, attrs:any) => {
var _self = this;
var intervalId:number = 0;
var clearInterval = function () {
if (intervalId != 0) {
_self.$interval.cancel(intervalId);
intervalId = 0;
}
};
_self.$timeout(function(){
intervalId = _self.$interval(function () {
let focusableElement = null;
if (attrs.focusOnLoad != '') {
focusableElement = element.find(attrs.focusOnLoad);
}
else {
focusableElement = element;
}
console.debug('focusOnLoad directive: trying to focus');
focusableElement.focus();
if (document.activeElement === focusableElement[0]) {
clearInterval();
}
}, 100);
scope.$on('$destroy', function () {
// Make sure that the interval is destroyed too
clearInterval();
});
});
};
public static factory = ():ng.IDirectiveFactory => {
let directive = ($interval:any, $timeout:any) => new FocusOnLoadDirective($interval, $timeout);
directive.$inject = ['$interval', '$timeout'];
return directive;
};
}
angular.module('common').directive('focusOnLoad', FocusOnLoadDirective.factory());
}
usage example for simple element:
<button tabindex="0" focus-on-load />
usage example for inner element (usually for dynamic injected element like directive with template):
<my-directive focus-on-load="input" />
you can use any jQuery selector instead of "input"
=iferror(counta(unique(A1:A100)))
counts number of unique cells from A1 to A100
var nationality = $("#dancerCountry").val();
should work. Are you sure that the element selector is working properly? Perhaps you should try:
var nationality = $('select[name="dancerCountry"]').val();
According to the YAML spec, neither the :
nor the -
should be a problem. :
is only a key separator with a space after it, and -
is only an array indicator at the start of a line with a space after it.
But if your YAML implementation has a problem with it, you potentially have lots of options:
- url: 'http://www.example-site.com/'
- url: "http://www.example-site.com/"
- url:
http://www.example-site.com/
- url: >-
http://www.example-site.com/
- url: |-
http://www.example-site.com/
There is explicitly no form of escaping possible in "plain style", however.
For those who want to implement a hack for Safari 7.0 and below, but not 7.1 and above -- use:
.myclass { (;property: value;); }
.myclass { [;property: value;]; }
Use localStorage to store the fact that you opened the page :
$(document).ready(function() {
var yetVisited = localStorage['visited'];
if (!yetVisited) {
// open popup
localStorage['visited'] = "yes";
}
});
I am using Bootstrap & HTML5. I wanted to override the look of the toggle button.
.navbar-toggle{
background-color: #5DADB0;
color: #F3DBAA;
border:none;
}
.navbar-toggle.but-menu:link {
color: #F00;
background-color: #CF995F;
}
.navbar-toggle.but-menu:visited {
color: #FFF;
background-color: #CF995F;
}
.navbar-toggle.but-menu:hover {
color: #FFF0C9;
background-color: #CF995F;
}
.navbar-toggle.but-menu:active {
color: #FFF;
background-color: #CF995F;
}
.navbar-toggle.but-menu:focus {
color: #FFF;
background-color: #CF995F;
}
I would suggest something like:
$text =~ m{(.*)$find(.*)};
$text = $1 . $replace . $2;
It is quite readable and seems to be safe. If multiple replace is needed, it is easy:
while ($text =~ m{(.*)$find(.*)}){
$text = $1 . $replace . $2;
}
Laravel 5 compatible and generic way:
I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique
and insert an exclude automatically (if needed).
Create a BaseModel
class and let all your models inherit from it:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
/**
* The validation rules for this model
*
* @var array
*/
protected static $rules = [];
/**
* Return model validation rules
*
* @return array
*/
public static function getRules() {
return static::$rules;
}
/**
* Return model validation rules for an update
* Add exception to :unique validations where necessary
* That means: enforce unique if a unique field changed.
* But relax unique if a unique field did not change
*
* @return array;
*/
public function getUpdateRules() {
$updateRules = [];
foreach(self::getRules() as $field => $rule) {
$newRule = [];
// Split rule up into parts
$ruleParts = explode('|',$rule);
// Check each part for unique
foreach($ruleParts as $part) {
if(strpos($part,'unique:') === 0) {
// Check if field was unchanged
if ( ! $this->isDirty($field)) {
// Field did not change, make exception for this model
$part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
}
}
// All other go directly back to the newRule Array
$newRule[] = $part;
}
// Add newRule to updateRules
$updateRules[$field] = join('|', $newRule);
}
return $updateRules;
}
}
You now define your rules in your model like you are used to:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the code after it.
public function postCreate(Request $request)
{
// Validate
$this->validate($request, Role::getRules());
// Validation successful -> create role
Role::create($request->all());
return redirect()->route('admin.role.index');
}
public function postEdit(Request $request, Role $role)
{
// Validate
$this->validate($request, $role->getUpdateRules());
// Validation successful -> update role
$role->update($request->input());
return redirect()->route('admin.role.index');
}
That's it! :) Note that on creation we call Role::getRules()
and on edit we call $role->getUpdateRules()
.
In Swift 2.0 you can use this method:
let registrationView = LMRegistration()
self.presentViewController(registrationView, animated: true, completion: nil)
For Reactive Forms, you can subscribe to the changes made to all fields or just a particular field.
Get all changes of a FormGroup:
this.orderForm.valueChanges.subscribe(value => {
console.dir(value);
});
Get the change of a specific field:
this.orderForm.get('orderPriority').valueChanges.subscribe(value => {
console.log(value);
});
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.
I though the perfect solution would be to have a timer handle the delayed action. FxCop doesn't like when you have an interval less then one second. I need to delay my actions until AFTER my DataGrid has completed sorting by column. I figured a one-shot timer (AutoReset = false) would be the solution, and it works perfectly. AND, FxCop will not let me suppress the warning!
There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:
OpenJDK Runtime Environment (Java SE 6)
yum install java-1.6.0-openjdk
OpenJDK Runtime Environment (Java SE 7)
yum install java-1.7.0-openjdk
OpenJDK Development Environment (Java SE 7)
yum install java-1.7.0-openjdk-devel
OpenJDK Development Environment (Java SE 6)
yum install java-1.6.0-openjdk-devel
Update for Java 8
In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:
OpenJDK Runtime Environment (Java SE 8)
yum install java-1.8.0-openjdk
OpenJDK Development Environment (Java SE 8)
yum install java-1.8.0-openjdk-devel
There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:
OpenJDK Runtime Environment - Headless (Java SE 8)
yum install java-1.8.0-openjdk-headless
Try this in a Thread (not the UI-Thread):
final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
@Override
public void run() {
OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
latch.countDown();
}
};
AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
.setMessage(msg).setPositiveButton("OK", okListener).create();
dialog.show();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
For me .exists
doesn't work, so I use the index :
if ($("#elem").index() ! = -1) {}
Once you generated the file, and changed your password, you can run as below,
cntlm -H
Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following
cntlm -v
The javascript array has a constructor that accepts the length of the array:
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]
However, this is just the initial size, there's no restriction on changing that:
arr.push(5);
console.log(arr); // [undefined × 3, 5]
Typescript has tuple types which let you define an array with a specific length and types:
let arr: [number, number, number];
arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'
I had this problem because my entitlements file was malformed due to previous manual editing. I removed the wrongly formatted entitlement entry syntax and then i could click "fix" in the capabilities tab and Xcode added the entitlement to my file.
Here is an example of a properly formatted entitlements file ("Runner.entitlements
"):
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
</dict>
</plist>
I want my python function to split a sentence (input) and store each word in a list
The str().split()
method does this, it takes a string, splits it into a list:
>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0
The problem you're having is because of a typo, you wrote print(words)
instead of print(word)
:
Renaming the word
variable to current_word
, this is what you had:
def split_line(text):
words = text.split()
for current_word in words:
print(words)
..when you should have done:
def split_line(text):
words = text.split()
for current_word in words:
print(current_word)
If for some reason you want to manually construct a list in the for loop, you would use the list append()
method, perhaps because you want to lower-case all words (for example):
my_list = [] # make empty list
for current_word in words:
my_list.append(current_word.lower())
Or more a bit neater, using a list-comprehension:
my_list = [current_word.lower() for current_word in words]
MyClass
and YourClass
could both be derived from SomeonesClass
which has an abstract (virtual) Callback
method. Your addHandler
would accept objects of type SomeonesClass
and MyClass
and YourClass
can override Callback
to provide their specific implementation of callback behavior.
Would it not be better to use java.util.Observable
and java.util.Observer
that will cause the table to update?
I tried all the above no good. So I just add a padding individually:
#button {
font-size: 20px;
color: white;
background: crimson;
border: 2px solid rgb(37, 34, 34);
border-radius: 10px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 10px;
padding-left: 10px;
}
The comment for orderBy
source code notes: Keys are field and values are the order, being either ASC or DESC.
. So you can do orderBy->(['field' => Criteria::ASC])
.
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:
print ("\n" * 100)
Though you could put this in a function:
def cls(): print ("\n" * 100)
And then call it when needed as cls()
You can use while(in.available() != 0)
instead of while(true)
.
The classic way would be to add commas to the left and right:
select * from shirts where CONCAT(',', colors, ',') like '%,1,%'
But find_in_set also works:
select * from shirts where find_in_set('1',colors) <> 0
Use this function to calculate the number of business days excluding Saturday and Sunday. Also it will exclude start date and it will include end date.
-- Select [dbo].[GetBussinessDays] ('02/18/2021', '03/06/2021') -- 11 days
CREATE or ALTER FUNCTION [dbo].[GetBussinessDays] (
@StartDate DATETIME,
@EndDate DATETIME
)
returns INT AS
BEGIN
DECLARE @tempStartDate DATETIME= @StartDate;
DECLARE @tempEndDate DATETIME = @EndDate;
IF(@tempStartDate IS NULL
OR
@tempEndDate IS NULL)
BEGIN
RETURN NULL;
END
--To avoid negative values reverse the date if StartDate is grater than EndDate
IF(@StartDate > @EndDate)
BEGIN
SET @StartDate = @tempEndDate;
SET @EndDate = @tempStartDate;
END
DECLARE @Counter INT = Datediff(day,@StartDate ,@EndDate);
DECLARE @TempCounter INT = 0;
DECLARE @TotalBusinessDays INT = 0;
WHILE @Counter >= 0
BEGIN
IF(@TempCounter > 0 OR @Counter = 1) -- To ignore first day's calculation
Begin
SET @TotalBusinessDays = @TotalBusinessDays + Iif(Datename(dw, Dateadd(day,@TempCounter,@StartDate)) IN('Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday'),1,0)
END
SET @Counter = @Counter - 1
SET @TempCounter = @TempCounter +1
END
RETURN @TotalBusinessDays;
END
Regex: match everything but:
foo
):
world.
at the end):
foo
) (no POSIX compliant patern, sorry):
|
symbol):
foo
):
cat
): /cat(*SKIP)(*FAIL)|[^c]*(?:c(?!at)[^c]*)*/i
or /cat(*SKIP)(*FAIL)|(?:(?!cat).)+/is
(cat)|[^c]*(?:c(?!at)[^c]*)*
(or (?s)(cat)|(?:(?!cat).)*
, or (cat)|[^c]+(?:c(?!at)[^c]*)*|(?:c(?!at)[^c]*)+[^c]*
) and then check with language means: if Group 1 matched, it is not what we need, else, grab the match value if not empty[^a-z]+
(any char other than a lowercase ASCII letter)|
: [^|]+
Demo note: the newline \n
is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.
Anchor note: In many languages, use \A
to define the unambiguous start of string, and \z
(in Python, it is \Z
, in JavaScript, $
is OK) to define the very end of the string.
Dot note: In many flavors (but not POSIX, TRE, TCL), .
matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s
in PCRE/Boost/.NET/Python/Java and /m
in Ruby) for the .
to match any char including a newline.
Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n
for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\.
will be declared as "world\\."
, or use a character class: "world[.]"
). Use raw string literals (Python r'\bworld\b'
), C# verbatim string literals @"world\."
, or slashy strings/regex literal notations like /world\./
.
Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.
Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.
Here's some updated code:
var myarray = [];
$("#test").click(function() {
myarray.push($("#drop").val());
alert(myarray);
});
$http is a promise too, you can make it simpler:
return $q.all(tasks.map(function(d){
return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
}));
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
I'm on Ubuntu 15.04. This seemed to work:
$ sudo pip3 install numpy
On RHEL this worked:
$ sudo python3 -m pip install numpy
You can do it by running with following command.
php -S localhost:8888
it worked for me after deleting and adding the server back.
I found a solution for animate hiding cells in static table.
// Class for wrapping Objective-C block
typedef BOOL (^HidableCellVisibilityFunctor)();
@interface BlockExecutor : NSObject
@property (strong,nonatomic) HidableCellVisibilityFunctor block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block;
@end
@implementation BlockExecutor
@synthesize block = _block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block
{
BlockExecutor * executor = [[BlockExecutor alloc] init];
executor.block = block;
return executor;
}
@end
Only one additional dictionary needed:
@interface MyTableViewController ()
@property (nonatomic) NSMutableDictionary * hidableCellsDict;
@property (weak, nonatomic) IBOutlet UISwitch * birthdaySwitch;
@end
And look at implementation of MyTableViewController. We need two methods to convert indexPath between visible and invisible indexes...
- (NSIndexPath*)recoverIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row <= indexPath.row + rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row+rowDelta inSection:indexPath.section];
}
- (NSIndexPath*)mapToNewIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row < indexPath.row - rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row-rowDelta inSection:indexPath.section];
}
One IBAction on UISwitch value changing:
- (IBAction)birthdaySwitchChanged:(id)sender
{
NSIndexPath * indexPath = [self mapToNewIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
if (self.birthdaySwitch.on)
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
else
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
Some UITableViewDataSource and UITableViewDelegate methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int numberOfRows = [super tableView:tableView numberOfRowsInSection:section];
for (NSIndexPath * indexPath in [self.hidableCellsDict allKeys])
if (indexPath.section == section)
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:indexPath];
numberOfRows -= (executor.block()?0:1);
}
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// initializing dictionary
self.hidableCellsDict = [NSMutableDictionary dictionary];
[self.hidableCellsDict setObject:[BlockExecutor executorWithBlock:^(){return self.birthdaySwitch.on;}] forKey:[NSIndexPath indexPathForRow:1 inSection:1]];
}
- (void)viewDidUnload
{
[self setBirthdaySwitch:nil];
[super viewDidUnload];
}
@end
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
File.WriteAllText("test.csv", result.ToString());
Ctrl + MouseWheel works on almost anything...not just visual studio
see if you are placing the client section in the correct web.config file. SharePoint has around 6 to 7 config files. http://msdn.microsoft.com/en-us/library/office/ms460914(v=office.14).aspx (http://msdn.microsoft.com/en-us/library/office/ms460914%28v=office.14%29.aspx)
Post this you can simply try
ServiceClient client = new ServiceClient("ServiceSOAP");
How about making your app agnostic of the server's timezone?
Owing to any of these possible scenarios:
All of the above scenarios give rise to breaking of your application's time calculations. Thus it appears that the better approach is to make your application work independent of the server's timezone.
The idea is simply to always create dates in UTC before storing them into the database, and always re-create them from the stored values in UTC as well. This way, the time calculations won't ever be incorrect, because they're always in UTC. This can be achieved by explicity stating the DateTimeZone
parameter when creating a PHP DateTime
object.
On the other hand, the client side functionality can be configured to convert all dates/times received from the server to the client's timezone. Libraries like moment.js make this super easy to do.
For example, when storing a date in the database, instead of using the NOW()
function of MySQL, create the timestamp string in UTC as follows:
// Storing dates
$date = new DateTime('now', new DateTimeZone('UTC'));
$sql = 'insert into table_name (date_column) values ("' . $date . '")';
// Retreiving dates
$sql = 'select date_column from table_name where condition';
$dateInUTC = new DateTime($date_string_from_db, new DateTimeZone('UTC'));
You can set the default timezone in PHP for all dates created, thus eliminating the need to initialize the DateTimeZone class every time you want to create a date.
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
JSONArray array;
@Override
protected JSONArray doInBackground(Void... params) {
try {
commonurl cu = new commonurl();
String u = cu.geturl("tempshowusermain.php");
URL url =new URL(u);
// URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
JSONObject jsonObject=new JSONObject();
jsonObject.put("lid",lid);
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.write(jsonObject.toString().getBytes("UTF-8"));
int code = httpURLConnection.getResponseCode();
if (code == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
object = new JSONObject(stringBuffer.toString());
// array = new JSONArray(stringBuffer.toString());
array = object.getJSONArray("response");
}
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
try {
for (int x = 0; x < array.length(); x++) {
object = array.getJSONObject(x);
ComonUserView commUserView=new ComonUserView();// commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
//pidArray.add(jsonObject2.getString("pid").toString());
commUserView.setLid(object.get("lid").toString());
commUserView.setUname(object.get("uname").toString());
commUserView.setAboutme(object.get("aboutme").toString());
commUserView.setHeight(object.get("height").toString());
commUserView.setAge(object.get("age").toString());
commUserView.setWeight(object.get("weight").toString());
commUserView.setBodytype(object.get("bodytype").toString());
commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
commUserView.setImagepath(object.get("imagepath").toString());
commUserView.setDistance(object.get("distance").toString());
commUserView.setLookingfor(object.get("lookingfor").toString());
commUserView.setStatus(object.get("status").toString());
cm.add(commUserView);
}
custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
gridusername.setAdapter(custuserprof);
// listusername.setAdapter(custuserprof);
} catch (Exception e) {
e.printStackTrace();
}
}
Use double quotes instead of single quote eg :
where('customer.name', 'LIKE', "%$findcustomer%")
Below is my code:
public function searchCustomer($findcustomer)
{
$customer = DB::table('customer')
->where('customer.name', 'LIKE', "%$findcustomer%")
->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
->get();
return View::make("your view here");
}
Simply go to /opt/lampp/var/mysql
There You can find your database
name.
Open that folder. Remove if any files in it
Now come to phpmyadmin
and drop that database
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
I usually go with varchar(255) (255 being the maximum length of a varchar type in MySQL).
You are really asking a couple of questions here:
1) Why does the price of SSL certificates vary so much
2) Where can I get good, cheap SSL certificates?
The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).
You can read more on this subject here
For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.
Sure.
.orElseThrow(() -> new MyException(someArgument))
The accepted answers gives the code for a histogram with overlapping bars, but in case you want each bar to be side-by-side (as I did), try the variation below:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')
x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
bins = np.linspace(-10, 10, 30)
plt.hist([x, y], bins, label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()
Reference: http://matplotlib.org/examples/statistics/histogram_demo_multihist.html
EDIT [2018/03/16]: Updated to allow plotting of arrays of different sizes, as suggested by @stochastic_zeitgeist
You have to access to your class atributes.
To access to it atributes, you have to do:
person.id
person.name
where
person
is an instance of your class Person.
This can be done if the attibutes can be accessed, if not, you must use setters and getters...
It worked for me just by adding serverTimeZone=UTC on application.properties.
spring.datasource.url=jdbc:mysql://localhost/db?serverTimezone=UTC
DELETE statement can have a WHERE clause to delete specific records whereas TRUNCATE statement does not require any and wipes the entire table. Importantly, the DELETE statement logs the deleted date whereas the TRUNCATE statement does not.
If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
All these answers with .ReadAllBytes()
. Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?
A comment was made on one of the posts regarding .ReadAllBytes()
:
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
A better approach, to me, would be something like this, with BinaryReader
:
public static byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
var binaryReader = new BinaryReader(fs);
fileData = binaryReader.ReadBytes((int)fs.Length);
}
return fileData;
}
But that's just me...
Of course, this all assumes you have the memory to handle the byte[]
once it is read in, and I didn't put in the File.Exists
check to ensure the file is there before proceeding, as you'd do that before calling this code.
A ListView
let you define a set of views
for it and gives you a native way (WPF
binding
support) to control the display of ListView
by using defined views
.
Example:
XAML
<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
<ListView.Resources>
<GridView x:Key="one">
<GridViewColumn Header="ID" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding id}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
<GridView x:Key="two">
<GridViewColumn Header="Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.Resources>
<ListView.Style>
<Style TargetType="ListView">
<Style.Triggers>
<DataTrigger Binding="{Binding ViewType}" Value="1">
<Setter Property="View" Value="{StaticResource one}" />
</DataTrigger>
</Style.Triggers>
<Setter Property="View" Value="{StaticResource two}" />
</Style>
</ListView.Style>
Code Behind:
private int viewType;
public int ViewType
{
get { return viewType; }
set
{
viewType = value;
UpdateProperty("ViewType");
}
}
private void listv_MouseEnter(object sender, MouseEventArgs e)
{
ViewType = 1;
}
private void listv_MouseLeave(object sender, MouseEventArgs e)
{
ViewType = 2;
}
OUTPUT:
Normal View: View 2 in above XAML
MouseOver View: View 1 in above XAML
If you try to achieve above in a
ListBox
, probably you'll end up writing a lot more code forControlTempalate
/ItemTemplate
ofListBox
.
For OOXML to work you need the POI-OOXML jar which is separately packaged from the POI jar.
Download the POI-OOXML jar from the following location -
http://repo1.maven.org/maven2/org/apache/poi/poi-ooxml/3.11/poi-ooxml-3.11.jar
For Maven2 add the below dependency -
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
My experience shows that the -o option doesn't work properly and that the go-offline goal is far from sufficient to allow a full offline build:
The solution I could validate includes the use of the --legacy-local-repository
maven option rather than the -o
(offline) one and
the use of the local repository in place of the distribution repository
In addition, I had to copy every maven-metadata-maven2_central.xml
files of the local-repo into the maven-metadata.xml
form expected by maven.
See the solution I found here.
You can also use a TextView and set the background image to what you wanted in the ImageView
. Furthermore if you were using the ImageView
as a button you can set it to click-able
Here is some basic code for a TextView
that shows an image with text on top of it.
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/your_image"
android:text="your text here" />
On Linux there is unshield
, which worked well for me (even if the GUI includes custom deterrents like license key prompts). It is included in the repositories of all major distributions (arch, suse, debian- and fedora-based) and its source is available at https://github.com/twogood/unshield
If you're using GoogleFireBaseMessaging, you can set "icon id" in the "notification" payload (it helps me to solve the white bar icon problem):
{
"to":"<fb_id>",
"priority" : "high",
"notification" :
{
"title" : "title",
"body" : "body" ,
"sound" : "default",
"icon" : "ic_notification"
}
}
set ic_notification to your own id from R.drawable.
For anyone who is facing this problem with Spring Boot 2
by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml
<hibernate.version>5.4.2.Final</hibernate.version>
and error was gone. Reason for error is already explained in posts above
If you want to see all the Enviroment Variables on execution time just write in some nodejs file like server.js:
console.log(process.env);
See the traceback
module, specifically the format_exc()
function. Here.
import traceback
try:
raise ValueError
except ValueError:
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
The only working condition, after several attempts, was to remove the hidden .idea folder from the root project folder and re-import it from Intellij
Antonio's answer
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
is wrong; it may produce incorrect results!
For example, if "number" is 12345.67, the resulting string would be:
'12.346,67'
instead of
'12.345,67'
because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!
What you COULD use is
CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
The problem is that you are returning the toString()
of the call to Base64.encodeBase64(bytes)
which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.
Instead, you should do:
encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");
Since you mention you have a proxy connection I will tell you what worked for me: I went to properties (as friedrich mentioned) ensuring the Offline Work was unchecked. I opened up the gradle.properties file in the IDE and added my proxy settings. Here's a generic version:
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
Then at the top of the properties file in the IDE there was a "Try Again" link which I clicked. That did it.
This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
If you're using local workspaces (TFS 2012+) you can now use the .tfignore
file to exclude local folders and files from being checked in.
If you add that file to source control you can ensure others on your team share the same exclusion settings.
Full details on MSDN - http://msdn.microsoft.com/en-us/library/ms245454.aspx#tfignore
For the lazy:
You can configure which kinds of files are ignored by placing a text file called
.tfignore
in the folder where you want rules to apply. The effects of the.tfignore
file are recursive. However, you can create .tfignore files in sub-folders to override the effects of a.tfignore
file in a parent folder.The following rules apply to a .tfignore file:
#
begins a comment line- The * and ? wildcards are supported.
- A filespec is recursive unless prefixed by the \ character.
- ! negates a filespec (files that match the pattern are not ignored)
Example file:
# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
#
# Ignore .txt files in this folder
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll
I always use this python solution due to its compactness.
def isPalindrome(number):
return int(str(number)[::-1])==number
Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.
None of the answers here addressed all of my needs.
A little background: I am using a ThreadPoolExecutor to manage a pool of threads, each launching a subprocess and running them concurrency. (In Python2.7, but this should work in newer 3.x as well). I don't want to use threads just for output gathering as I want as many available as possible for other things (a pool of 20 processes would be using 40 threads just to run; 1 for the process thread and 1 for stdout...and more if you want stderr I guess)
I'm stripping back a lot of exception and such here so this is based on code that works in production. Hopefully I didn't ruin it in the copy and paste. Also, feedback very much welcome!
import time
import fcntl
import subprocess
import time
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Make stdout non-blocking when using read/readline
proc_stdout = proc.stdout
fl = fcntl.fcntl(proc_stdout, fcntl.F_GETFL)
fcntl.fcntl(proc_stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
def handle_stdout(proc_stream, my_buffer, echo_streams=True, log_file=None):
"""A little inline function to handle the stdout business. """
# fcntl makes readline non-blocking so it raises an IOError when empty
try:
for s in iter(proc_stream.readline, ''): # replace '' with b'' for Python 3
my_buffer.append(s)
if echo_streams:
sys.stdout.write(s)
if log_file:
log_file.write(s)
except IOError:
pass
# The main loop while subprocess is running
stdout_parts = []
while proc.poll() is None:
handle_stdout(proc_stdout, stdout_parts)
# ...Check for other things here...
# For example, check a multiprocessor.Value('b') to proc.kill()
time.sleep(0.01)
# Not sure if this is needed, but run it again just to be sure we got it all?
handle_stdout(proc_stdout, stdout_parts)
stdout_str = "".join(stdout_parts) # Just to demo
I'm sure there is overhead being added here but it is not a concern in my case. Functionally it does what I need. The only thing I haven't solved is why this works perfectly for log messages but I see some print
messages show up later and all at once.