jenkins default administrator password is logged in log file in ubuntu
log file is situated in /var/log/jenkins/jenkins.log folder
password will be placed after this, Jenkins initial setup is required. An admin user has been created and a password generated. Please use the following password to proceed to installation:
Here is the working solution bro. It's guranteed.
[email protected]
Open this link below:
Here is my code:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmail {
final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
public static void main(String[] args) {
SendEmail mailSender;
mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
}
}
tracert
/traceroute
to find number of hopsas 'Praveen M P' said you can install font-awesome as a package. if you have yarn you can run:
yarn add font-awesome
If you don't have yarn do as Praveen said and do:
npm install --save font-awesome
this will add the package to your projects dependencies and install the package in your node_modules folder. in your App.js file add
import 'font-awesome/css/font-awesome.min.css'
You can use text
.
text(x, y, s, fontsize=12)
text
coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:
The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::
text(0.5, 0.5,'matplotlib',
horizontalalignment='center',
verticalalignment='center',
transform = ax.transAxes)
To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))
) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.
EDIT: here you have an example:
In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:
The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.
By the way, instead of generating the x and y coordinates yourself, you can also use the curve()
function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).
see
help(curve)
and its examples.
And if you want to add som text to properly label the mean and standard deviations, you can use the text()
function (see also plotmath
, for annotations with mathematical symbols) .
see
help(text)
help(plotmath)
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Yes. You can use *args
as a non-keyword argument. You will then be able to pass any number of arguments.
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)
As you can see, Python will unpack the arguments as a single tuple with all the arguments.
For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.
You may try the following: Open anaconda command prompt and type
conda remove --name myenv --all
This will remove the entire environment.
Further reading: docs.conda.io > Manage Environments
Use the snippet of code below
File file= new File("/sdcard/test.pdf");
Uri path=Uri.fromFile(file);
Intent i =new Intent(Intent.ACTION_VIEW);
i.setDataAndType(path,"application/pdf");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
Dan Beaulieu's answer in swift5 (also working since swift 3.0.1).
extension DispatchQueue {
static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
DispatchQueue.global(qos: .background).async {
background?()
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
completion()
})
}
}
}
}
DispatchQueue.background(delay: 3.0, background: {
// do something in background
}, completion: {
// when background job finishes, wait 3 seconds and do something in main thread
})
DispatchQueue.background(background: {
// do something in background
}, completion:{
// when background job finished, do something in main thread
})
DispatchQueue.background(delay: 3.0, completion:{
// do something in main thread after 3 seconds
})
To get the latest Lollipop Pull-To Refresh:
android.support.v4.widget.SwipeRefreshLayout
plus android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener
Detailed guide could be found here: http://antonioleiva.com/swiperefreshlayout/
Plus for ListView I recommend to read about canChildScrollUp()
in the comments ;)
Here is a special case, but might inspire you to create your own work around. The goal here is to count the total number of records from two different tables where records meet a particular criteria. I believe this technique will work for any case where you need to aggregate data from across multiple tables/sources.
I have some special intermediate classes setup, so the code which calls the named query is short and sweet, but you can use whatever method you normally use in conjunction with named queries to execute your query.
QueryParms parms=new QueryParms();
parms.put("PROCDATE",PROCDATE);
Long pixelAll = ((SourceCount)Fetch.row("PIXEL_ALL",parms,logger)).getCOUNT();
As you can see here, the named query begins to look an aweful lot like a union statement:
@Entity
@NamedQueries({
@NamedQuery(
name ="PIXEL_ALL",
query = "" +
" SELECT new SourceCount(" +
" (select count(a) from PIXEL_LOG_CURR1 a " +
" where to_char(a.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
" )," +
" (select count(b) from PIXEL_LOG_CURR2 b" +
" where to_char(b.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
" )" +
") from Dual1" +
""
)
})
public class SourceCount {
@Id
private Long COUNT;
public SourceCount(Long COUNT1, Long COUNT2) {
this.COUNT = COUNT1+COUNT2;
}
public Long getCOUNT() {
return COUNT;
}
public void setCOUNT(Long COUNT) {
this.COUNT = COUNT;
}
}
Part of the magic here is to create a dummy table and insert one record into it. In my case, I named it dual1 because my database is Oracle, but I don't think it matters what you call the dummy table.
@Entity
@Table(name="DUAL1")
public class Dual1 {
@Id
Long ID;
}
Don't forget to insert your dummy record:
SQL> insert into dual1 values (1);
This works relatively well. It flattens the json to write it to a csv file. Nested elements are managed :)
That's for python 3
import json
o = json.loads('your json string') # Be careful, o must be a list, each of its objects will make a line of the csv.
def flatten(o, k='/'):
global l, c_line
if isinstance(o, dict):
for key, value in o.items():
flatten(value, k + '/' + key)
elif isinstance(o, list):
for ov in o:
flatten(ov, '')
elif isinstance(o, str):
o = o.replace('\r',' ').replace('\n',' ').replace(';', ',')
if not k in l:
l[k]={}
l[k][c_line]=o
def render_csv(l):
ftime = True
for i in range(100): #len(l[list(l.keys())[0]])
for k in l:
if ftime :
print('%s;' % k, end='')
continue
v = l[k]
try:
print('%s;' % v[i], end='')
except:
print(';', end='')
print()
ftime = False
i = 0
def json_to_csv(object_list):
global l, c_line
l = {}
c_line = 0
for ov in object_list : # Assumes json is a list of objects
flatten(ov)
c_line += 1
render_csv(l)
json_to_csv(o)
enjoy.
Bootstrap 4 has added .no-gutters class.
Bootstrap 3.4 has added .row-no-gutters class
Bootstrap 3: I always add this style to my Bootstrap LESS / SASS:
.row-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Then in the HTML you can write:
<div class="row row-no-padding">
If you want to only target the child columns you can use the child selector (Thanks John Wu).
.row-no-padding > [class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
You may also want to remove padding only for certain device sizes (SASS example):
/* Small devices (tablets, 768px and up) */
@media (min-width: $screen-sm-min) and (max-width: $screen-sm-max) {
.row-sm-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
}
You can remove the max-width part of the media query if you want it to support small devices upwards.
Some process is using this port, so you can change the port that is used by xampp, to be able to use it. For this job you have to do this:
1- Open httpd-ssl.conf in xampp\apache\conf\extra
2- Look for the line containing Listen 443
3- Change port number to anything you want. I use 4430. ex. Listen 4430.
4- Replace every 443 strings in that file with 4430.
5- Save the file.
CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,
However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).
You can read blog from Simon here . He also recommends CSS over Xpath.
If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.
Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better
i use dumpsys to catch if app is crashed and process is still active. situation i used it is to find about remote machine app is crashed or not.
dumpsys | grep myapp | grep "Application Error"
or
adb shell dumpsys | grep myapp | grep Error
or anything that helps...etc
if app is not running you will get nothing as result. When app is stoped messsage is shown on screen by android, process is still active and if you check via "ps" command or anything else, you will see process state is not showing any error or crash meaning. But when you click button to close message, app process will cleaned from process list. so catching crash state without any code in application is hard to find. but dumpsys helps you.
For clear all options en Important en FOR : remove(0) - Important: 0
var select = document.getElementById("element_select");
var length = select.length;
for (i = 0; i < length; i++) {
select.remove(0);
// or
// select.options[0] = null;
}
Following work for me:
Keep following setting blank if you have made in build.gradle.
signingConfigs {
release {
storePassword ""
keyAlias ""
keyPassword ""
}
}
and choose Gradle Task from your Editor window. It will show list of all flavor if you have created.
When you analyze critically from the base classes of these two annotations.You will realize the following differences.
@Autowired
uses AutowiredAnnotationBeanPostProcessor
to inject dependencies.
@Resource
uses CommonAnnotationBeanPostProcessor
to inject dependencies.
Even though they use different post processor classes they all behave nearly identically. The differences critically lie in their execution paths, which I have highlighted below.
@Autowired / @Inject
1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name
@Resource
1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)
If you want a string mm/dd/yyyy
instead of the datetime
object, you can use strftime
(string format time):
>>> dt.datetime.today().strftime("%m/%d/%Y")
# ^ note parentheses
'02/12/2014'
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
It depends on windows system but usually:
<sdk>\extras\google\usb_driver\i386
(or amd64 for and).For my mobile it works, but depend on your mobile if it work or not.
Hope this help, bye.
The URL which worked for me is http://download.eclipse.org/tools/pdt/updates/2.0/interim/.
See also Stack Overflow question Installing PDT in Eclipse - No runtime option .. only SDK.
This look like a duplicate of JSTL conditional check.
The error is having the &&
outside the expression. Instead use
<c:if test="${ISAJAX == 0 && ISDATE == 0}">
But, sometimes, even with user-select
and touch-callout
turned off, cursor: pointer;
may cause this effect, so, just set cursor: default;
and it'll work.
thanks friends, after trying all and not getting desired result i think to use a hidden div with that arabic message and with jQuery fading affects solved the problem. Script I wrote is: .js file
$('#enterOpeningPrice').fadeIn();
$('#enterOpeningPrice').fadeOut(10000);
.html file
<div id="enterOpeningPrice">
<p>???? ??? ????????</p>
</div>
Thanks to all..
The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch'
ref using any Git client tool".
The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>
. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>
; it lies to the git client.
Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH>
refs.
When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].
After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>
. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository
.
Note that the file:///
scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
//start the program
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'datapullman',
password: 'system',
server: 'localhost',
database: 'chat6'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * From emp", function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//create a table as emp in a database (i have created as chat6)
// programs ends here
//save it as app.js and run as node app.js //open in you browser as localhost:5000
You can also leverage the numpy library for logical operations. Its pretty fast.
df[np.logical_and(df['A'] == 1 ,df['B'] == 6)]
They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.
See Dive into Python for a relatively detailed introduction.
So first of all, pandas updates using the index. When an update command does not update anything, check both left-hand side and right-hand side. If you don't update the indices to follow your identification logic, you can do something along the lines of
>>> df.loc[df.filename == 'test2.dat', 'n'] = df2[df2.filename == 'test2.dat'].loc[0]['n']
>>> df
Out[331]:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16
If you want to do this for the whole table, I suggest a method I believe is superior to the previously mentioned ones: since your identifier is filename
, set filename
as your index, and then use update()
as you wanted to. Both merge
and the apply()
approach contain unnecessary overhead:
>>> df.set_index('filename', inplace=True)
>>> df2.set_index('filename', inplace=True)
>>> df.update(df2)
>>> df
Out[292]:
m n
filename
test0.dat 12 None
test2.dat 13 16
Add the border to each cell with this:
table > tbody > tr > td { border: 1px solid rgba(255, 255, 255, 0.1); }
Remove the top border from all the cells in the first row:
table > tbody > tr:first-child > td { border-top: 0; }
Remove the left border from the cells in the first column:
table > tbody > tr > td:first-child { border-left: 0; }
Remove the right border from the cells in the last column:
table > tbody > tr > td:last-child { border-right: 0; }
Remove the bottom border from the cells in the last row:
table > tbody > tr:last-child > td { border-bottom: 0; }
DocumentElement
is the root node of the document so childNodes[1]
doesn't exist in that document. childNodes[0]
would be the <Settings> node
As @Jthorpe alluded to, ComponentClass
only allows either Component
or PureComponent
but not a FunctionComponent
.
If you attempt to pass a FunctionComponent
, typescript will throw an error similar to...
Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.
However, by using ComponentType
rather than ComponentClass
you allow for both cases. Per the react declaration file the type is defined as...
type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>
I'm posting this as an answer because it deserves to be it's own answer rather than a comment under a less useful answer. I find this method much better than the accepted answer since it can keep all the js in a separate file from the HTML.
Answer provided by Jamrelian in his comment under the accepted answer.
$("#myelement").on("input change", function() {
//do something
});
Just be aware of this comment by Jaime though
Just note that with this solution, in chrome you will get two calls to the handler (one per event), so if you care for that, then you need to guard against it.
As in it will fire the event when you have stopped moving the mouse, and then again when you release the mouse button.
In relation to the change
event and input
event causing the functionality to trigger twice, this is pretty much a non-issue.
If you have a function firing off on input
, it is extremely unlikely that there will be a problem when the change
event fires.
input
fires rapidly as you drag a range input slider. Worrying about one more function call firing at the end is like worrying about a single drop of water compared to the ocean of water that is the input
events.
The reason for even including the change
event at all is for the sake of browser compatibility (mainly with IE).
As of Swift 4:
button.setTitle("Click", for: .normal)
<?php
$smarty = new Smarty;
$smarty->assign('test', "This is a \n Test");
$smarty->display('index.tpl');
?>
In index.tpl
{$test|nl2br}
In HTML
This is a<br />
test
I created a class wrapped in an ES6 module that solves exactly this.
It's 103 lines, no dependencies, and fairly nicely structured and documented, meant to be easy to modify/reuse.
Handles all 8 possible orientations, and is Promise-based.
Here you go, hope this still helps someone: https://gist.github.com/vdavid/3f9b66b60f52204317a4cc0e77097913
This is not "auto-completion", this is automation. One common tool for these things is called Expect.
You might also get away with just piping input from yes
.
You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:
Obj.prototype.toString= function(){
var A= [];
for(var p in this){
if(this.hasOwnProperty(p)){
A[A.length]= p+'='+this[p];
}
}
return A.join(', ');
}
r := strings(byteData)
This also works to turn []byte
into io.Reader
Here's yet another option to add to the mix:
$ du -b file.txt
That is: estimate file space usage of file.txt in bytes.
I solved this by below codes:
Client Side (Js):
$http({
url: me.serverPath,
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}).
success(function (serverData) {
console.log("ServerData:", serverData);
......
notice that data is an object.
On the server (ASP.NET MVC):
[AllowCrossSiteJson]
public string Api()
{
var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
if (data == null) return "Null Request";
var bl = Page.Bl = new Core(this);
return data.methodName;
}
and 'AllowCrossSiteJsonAttribute' is needed for cross domain requests:
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
Hope this was useful.
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
Scrollbars etc have an effect on the window size so you may want to tweak to desired size.
The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).
The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.
So what was missing was:
Response.End();
See also: Trying to stream a PDF file with asp.net is producing a "damaged file"
I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).
I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:
find /etc -type f -exec grep -nHi -e "widehat" {} \;
Instead of:
grep -nRHi -e "widehat" /etc
The more secure option would be to add allowedHosts to your Webpack config like this:
module.exports = {
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
The array contains all allowed host, you can also specify subdomians. check out more here
Try looking at the BigDecimal Class. It is the go to class for currency and support accurate rounding.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
coffee-script
can accomplish this with aplomb..
for x in [ 'a', 'b', 'c' ] then "#{x}" : true
[ { a: true }, { b: true }, { c: true } ]
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
I use this on my macbook:
" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab
" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab " enter spaces when tab is pressed
set textwidth=120 " break lines when line length increases
set tabstop=4 " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4 " number of spaces to use for auto indent
set autoindent " copy indent from current line when starting a new line
" make backspaces more powerfull
set backspace=indent,eol,start
set ruler " show line and column number
syntax on " syntax highlighting
set showcmd " show (partial) command in status line
(edited to only show stuff related to indent / tabs)
Anyway, here is how to fix it:
Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
taken from this link
You can convert the URL
to a String
and use it to create a new File
. e.g.
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());
sed -e '/^ *$/d' input > output
Deletes all lines which consist only of blanks (or is completely empty). You can change the blank to [ \t]
where the \t
is a representation for tab. Whether your shell or your sed
will do the expansion varies, but you can probably type the tab character directly. And if you're using GNU or BSD sed
, you can do the edit in-place, if that's what you want, with the -i
option.
If I execute the above command still I have blank lines in my output file. What could be the reason?
There could be several reasons. It might be that you don't have blank lines but you have lots of spaces at the end of a line so it looks like you have blank lines when you cat the file to the screen. If that's the problem, then:
sed -e 's/ *$//' -e '/^ *$/d' input > output
The new regex removes repeated blanks at the end of the line; see previous discussion for blanks or tabs.
Another possibility is that your data file came from Windows and has CRLF line endings. Unix sees the carriage return at the end of the line; it isn't a blank, so the line is not removed. There are multiple ways to deal with that. A reliable one is tr
to delete (-d
) character code octal 15, aka control-M or \r
or carriage return:
tr -d '\015' < input | sed -e 's/ *$//' -e '/^ *$/d' > output
If neither of those works, then you need to show a hex dump or octal dump (od -c
) of the first two lines of the file, so we can see what we're up against:
head -n 2 input | od -c
Judging from the comments that sed -i
does not work for you, you are not working on Linux or Mac OS X or BSD — which platform are you working on? (AIX, Solaris, HP-UX spring to mind as relatively plausible possibilities, but there are plenty of other less plausible ones too.)
You can try the POSIX named character classes such as sed -e '/^[[:space:]]*$/d'
; it will probably work, but is not guaranteed. You can try it with:
echo "Hello World" | sed 's/[[:space:]][[:space:]]*/ /'
If it works, there'll be three spaces between the 'Hello' and the 'World'. If not, you'll probably get an error from sed
. That might save you grief over getting tabs typed on the command line.
Try this:
$month = ( isset($_POST['month']) ) ? $_POST['month'] : '';
$op = ( isset($_POST['op']) ) ? $_POST['op'] : '';
It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,
cat hello.py | ssh [email protected] python -
Run python --help for more info.
Try:
System.getProperty("os.name");
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29
Should be :
<h2 class="col-md-4 col-md-offset-1">Browse.</h2>
<h2 class="col-md-4 col-md-offset-2">create.</h2>
<h2 class="col-md-4 col-md-offset-3">share.</h2>
public class NavigateUsingAllBrowsers {
public static void main(String[] args) {
WebDriver driverFF= new FirefoxDriver();
driverFF.navigate().to("http://www.firefox.com");
File file =new File("C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driverIE=new InternetExplorerDriver();
driverIE.navigate().to("http://www.msn.com");
// Download Chrome Driver from http://code.google.com/p/chromedriver/downloads/list
file =new File("C:/Users/mkv/workspace/ServerDrivers/ChromeDriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driverChrome=new ChromeDriver();
driverChrome.navigate().to("http://www.chrome.com");
}
}
Use a JOIN
in the DELETE
statement.
DELETE p, pa
FROM pets p
JOIN pets_activities pa ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
Alternatively you can use...
DELETE pa
FROM pets_activities pa
JOIN pets p ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
...to delete only from pets_activities
See this.
For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS
, NOT EXISTS
, IN
, NOT IN
and etc. But the one above where you specify from which tables to delete with an alias before the FROM
clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS
in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.
You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x
p <- ggplot(plot, aes(x = pred, y = value)) +
geom_point(size = 2.5) +
theme_bw()+
coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p
dt
is nullable
you need to access its Value
if (datetime.HasValue)
dt = datetime.Value;
It is important to remember that it can be NULL
. That is why the nullable
struct has the HasValue
property that tells you if it is NULL
or not.
You can also use the null-coalescing operator
??
to assign a default value
dt = datetime ?? DateTime.Now;
This will assign the value on the right if the value on the left is NULL
Actually an other way to solve this could be, overwriting the CSS with insertRule
.
It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
Demo with my 4 years old original example: http://jsfiddle.net/raPeX/21/
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?) {
Field field = null;
int resId = 0;
try {
field = ?.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.
so something
is not a valid JSON but "something"
is.
A valid JSON is -
JSON = null
/* boolean literal */
or true or false
/* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
or JSONNumber
/* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
or JSONString
/* Property names must be double-quoted strings; trailing commas are forbidden. */
or JSONObject
or JSONArray
Examples -
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.parse("'foo'"); // error since string should be wrapped by double quotes
You may want to look JSON.
It seems all the answers assume high level languages and mainly C/C++.
But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:
byte = 8 bits
word = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")
import subprocess
cmd = "vsish -e ls /vmkModules/lsom/disks/ | cut -d '/' -f 1 | while read diskID ; do echo $diskID; vsish -e cat /vmkModules/lsom/disks/$diskID/virstoStats | grep -iE 'Delete pending |trims currently queued' ; echo '====================' ;done ;"
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
for line in proc_stdout.decode().split('\n'):
print (line)
subprocess_cmd(cmd)
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
android:layout_weight=".YOURVALUE" is best way to implement in percentage
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/logTextBox"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".20"
android:maxLines="500"
android:scrollbars="vertical"
android:singleLine="false"
android:text="@string/logText" >
</TextView>
</LinearLayout>
You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]
the important line is a[-9:]
In Laravel 5.1, this works in a Blade:
<?php
switch( $machine->disposal ) {
case 'DISPO': echo 'Send to Property Disposition'; break;
case 'UNIT': echo 'Send to Unit'; break;
case 'CASCADE': echo 'Cascade the machine'; break;
case 'TBD': echo 'To Be Determined (TBD)'; break;
}
?>
Validate email while typing, with button state handling.
$("#email").on("input", function(){
var email = $("#email").val();
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!filter.test(email)) {
$(".invalid-email:empty").append("Invalid Email Address");
$("#submit").attr("disabled", true);
} else {
$("#submit").attr("disabled", false);
$(".invalid-email").empty();
}
});
Well, that's easy. The purpose of lambda expression is to implement Functional Interface. It is the interface with only one method. Here is awesone article about predefined and legacy functional interfaces.
Anyway, if you want to implement your own functional interface, make it. Just for simple example:
public interface MyFunctionalInterface {
String makeIt(String s);
}
So let's make a class, where we will create a method, which accepts the type of MyFunctionalInterface :
public class Main {
static void printIt(String s, MyFunctionalInterface f) {
System.out.println(f.makeIt(s));
}
public static void main(String[] args) {
}
}
The last thing you should do is to pass the implementation of the MyFunctionalInterface to the method we've defined:
public class Main {
static void printIt(String s, MyFunctionalInterface f) {
System.out.println(f.makeIt(s));
}
public static void main(String[] args) {
printIt("Java", s -> s + " is Awesome");
}
}
That's it!
I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.
You can access this by
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
If you want to do this inline, just cast the NSUInteger
or NSInteger
to an int
:
int i = -1;
NSUInteger row = 100;
i > row // true, since the signed int is implicitly converted to an unsigned int
i > (int)row // false
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
There was almost the same question on GitHub a year ago.
The idea was to rename the master branch:
git branch -m master development
git branch -m published master
git push -f origin master
Making master have what you want people to use, and do all other work in branches.
(a "git-symbolic-ref HEAD refs/head/published
" would not be propagated to the remote repo)
This is similar to "How do I delete origin/master in Git".
As said in this thread: (emphasis mine)
"
git clone
" creates only a single local branch.
To do that, it looks at theHEAD ref
of the remote repo, and creates a local branch with the same name as the remote branch referenced by it.So to wrap that up, you have repo
A
and clone it:
HEAD
referencesrefs/heads/master
and that exists
-> you get a local branch calledmaster
, starting fromorigin/master
HEAD references
refs/heads/anotherBranch
and that exists
-> you get a local branch calledanotherBranch
, starting fromorigin/anotherBranch
HEAD references
refs/heads/master
and that doesn't exist
-> "git clone
" complainsNot sure if there's any way to directly modify the
HEAD
ref in a repo.
(which is the all point of your question, I know ;) )
Maybe the only way would be a "publication for the poor", where you:
$ git-symbolic-ref HEAD refs/head/published
$ git-update-server-info
$ rsync -az .git/* server:/local_path_to/git/myRepo.git/
But that would involve write access to the server, which is not always possible.
As I explain in "Git: Correct way to change Active Branch in a bare repository?", git remote set-head
wouldn't change anything on the remote repo.
It would only change the remote tracking branch stored locally in your local repo, in remotes/<name>/HEAD
.
With Git 2.29 (Q4 2020), "git remote set-head
(man)" that failed still said something that hints the operation went through, which was misleading.
See commit 5a07c6c (17 Sep 2020) by Christian Schlack (cschlack
).
(Merged by Junio C Hamano -- gitster
-- in commit 39149df, 22 Sep 2020)
remote
: don't show success message whenset-head
failsSigned-off-by: Christian Schlack
Suppress the message 'origin/HEAD set to master' in case of an error.
$ git remote set-head origin -a error: Not a valid ref: refs/remotes/origin/master origin/HEAD set to master
For simplicity, you can use a Runnable:
private void runCallback(Runnable callback)
{
// Run callback
callback.run();
}
Usage:
runCallback(new Runnable()
{
@Override
public void run()
{
// Running callback
}
});
The length of the arrays must be the same and the numbers just be the same throughout(1st number in arrays must be the sasme and so on)
Based on this comment, then you already have your algorithm:
Check if both arrays have the same length:
array1.length == array2.length
The numbers must be the same in the same position:
array1[x] == array2[x]
Knowing this, you can create your code like this (this is not Java code, it's an algorithm):
function compareArrays(int[] array1, int[] array2) {
if (array1 == null) return false
if (array2 == null) return false
if array1.length != array2.length then return false
for i <- 0 to array1.length - 1
if array1[i] != array2[i] return false
return true
}
Note: your function should return a boolean
, not being a void
, then recover the return value in another variable and use it to print the message "true" or "false":
public static void main(String[] args) {
int[] array1;
int[] array2;
//initialize the arrays...
//fill the arrays with items...
//call the compare function
boolean arrayEquality = compareArrays(array1, array2);
if (arrayEquality) {
System.out.println("arrays are equals");
} else {
System.out.println("arrays are not equals");
}
}
Here is the class LocationFinder
to find the GPS location. This class will call MyLocation
, which will do the business.
LocationFinder
public class LocationFinder extends Activity {
int increment = 4;
MyLocation myLocation = new MyLocation();
// private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intermediat);
myLocation.getLocation(getApplicationContext(), locationResult);
boolean r = myLocation.getLocation(getApplicationContext(),
locationResult);
startActivity(new Intent(LocationFinder.this,
// Nearbyhotelfinder.class));
GPSMyListView.class));
finish();
}
public LocationResult locationResult = new LocationResult() {
@Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
double Longitude = location.getLongitude();
double Latitude = location.getLatitude();
Toast.makeText(getApplicationContext(), "Got Location",
Toast.LENGTH_LONG).show();
try {
SharedPreferences locationpref = getApplication()
.getSharedPreferences("location", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = locationpref.edit();
prefsEditor.putString("Longitude", Longitude + "");
prefsEditor.putString("Latitude", Latitude + "");
prefsEditor.commit();
System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// handler for the background updating
}
MyLocation
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
// Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
@Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Is there a TRY CATCH command in Bash?
No.
Bash doesn't have as many luxuries as one can find in many programming languages.
There is no try/catch
in bash; however, one can achieve similar behavior using &&
or ||
.
Using ||
:
if command1
fails then command2
runs as follows
command1 || command2
Similarly, using &&
, command2
will run if command1
is successful
The closest approximation of try/catch
is as follows
{ # try
command1 &&
#save your output
} || { # catch
# save log for exception
}
Also bash contains some error handling mechanisms, as well
set -e
it stops your script if any simple command fails.
And also why not if...else
. It is your best friend.
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>
_x000D_
F1 → open Keyboard Shortcuts → search for 'Indent Line', and change keybinding to Tab.
Right click > "Change when expression" to editorHasSelection && editorTextFocus && !editorReadonly
It will allow you to indent line when something in that line is selected (multiple lines still work).
Generally, when you want to wait for a thread to finish, you should call join() on it.
select * from users
WHERE NOT
( CHARINDEX(' ',LTRIM(RTRIM([Email]))) = 0
AND LEFT(LTRIM([Email]),1) <> '@'
AND RIGHT(RTRIM([Email]),1) <> '.'
AND CHARINDEX('.',[Email],CHARINDEX('@',[Email])) - CHARINDEX('@',[Email]) > 1
AND LEN(LTRIM(RTRIM([Email]))) - LEN(REPLACE(LTRIM(RTRIM([Email])),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM([Email])))) >= 3
AND (CHARINDEX('.@',[Email]) = 0 AND CHARINDEX('..',[Email]) = 0)
I would echo what Wyzard wrote but add that:
URLEncoder
should not be usedI wrote a blog post a while back about this subject: Java: safe character handling and URL building
If this is your detail.html
I don't see where do you load detail.js
?
Maybe this
<script src="js/index.js"></script>
should be this
<script src="js/detail.js"></script>
?
Easiest solution for this to remove the index.php code which is allocated on
xammp-> htdocs-> index.php
you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck
You probably haven't installed GLUT:
Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf
EDIT:
The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip
Folder references:
glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
glut32.dll: 'C:\Windows\System32\'
For 64-bit machines, you will want to do this.
glut32.dll: 'C:\Windows\SysWOW64\'
Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
1. Under Visual C++, select Empty Project.
2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
opengl32.lib
glu32.lib
glut32.lib
As always, http://www.csszengarden.com/. Note that the images aren't public domain.
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
From the most recent document, the select method takes an index or the id of the tab's panel (the href hash value). The documentation states:
Select a tab, as if it were clicked. The second argument is the zero-based index of the tab to be selected or the id selector of the panel the tab is associated with (the tab's href fragment identifier, e.g. hash, points to the panel's id).
So, given a layout like
<div id="myTabs">
<ul class="tabs">
<li><a href="#tabone">tabone</a></li>
<li><a href="#tabtwo">tabtwo</a></li>
</ul>
</div>
the following works
$('#myTabs').tabs('select', '#tabtwo');
Here is an example.
UPDATE
The above solution works in jQuery UI versions less than 1.9. For a solution in versions 1.9+ see @stankovski's answer.
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
Not an answer Or Why 'tricky' is bad:
>> a = Array(1)
>> a = Split(Join(a, "||") & "||2", "||")
>> WScript.Echo a(0) + a(1)
>>
12
You can use the code below to hide the scroll bar, but while still being able to scroll:
.element::-webkit-scrollbar {
width: 0 !important
}
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
The best way to catch the position is by FindIndex
This function is available only for List<>
Example
int id = listMyObject.FindIndex(x => x.Id == 15);
If you have enumerator or array use this way
int id = myEnumerator.ToList().FindIndex(x => x.Id == 15);
or
int id = myArray.ToList().FindIndex(x => x.Id == 15);
@Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml
code to this:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"> <!-- Just add this line -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
I think you should check the following project at codeplex.com http://autoupdater.codeplex.com/
This sample application is developed in C# as a library with the project name “AutoUpdater”. The DLL “AutoUpdater” can be used in a C# Windows application(WinForm and WPF).
There are certain features about the AutoUpdater:
How to use?
In the program that you want to be auto updateable, you just need to call the AutoUpdate function in the Main procedure. The AutoUpdate function will check the version with the one read from a file located in a Web Site/FTP. If the program version is lower than the one read the program downloads the auto update program and launches it and the function returns True, which means that an auto update will run and the current program should be closed. The auto update program receives several parameters from the program to be updated and performs the auto update necessary and after that launches the updated system.
#region check and download new version program
bool bSuccess = false;
IAutoUpdater autoUpdater = new AutoUpdater();
try
{
autoUpdater.Update();
bSuccess = true;
}
catch (WebException exp)
{
MessageBox.Show("Can not find the specified resource");
}
catch (XmlException exp)
{
MessageBox.Show("Download the upgrade file error");
}
catch (NotSupportedException exp)
{
MessageBox.Show("Upgrade address configuration error");
}
catch (ArgumentException exp)
{
MessageBox.Show("Download the upgrade file error");
}
catch (Exception exp)
{
MessageBox.Show("An error occurred during the upgrade process");
}
finally
{
if (bSuccess == false)
{
try
{
autoUpdater.RollBack();
}
catch (Exception)
{
//Log the message to your file or database
}
}
}
#endregion
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
First of all we will need serializeObject();
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
then you make a basic post and get response
$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true
}
else
{
//do false
}
});
The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.
That being said, I personally go with inline comment style occasionally.
def complex( # Form a complex number
real=0.0, # the real part (default 0.0)
imag=0.0 # the imaginary part (default 0.0)
): # Returns a complex number.
"""Form a complex number.
I may still use the mainstream docstring notation,
if I foresee a need to use some other tools
to generate an HTML online doc later
"""
if imag == 0.0 and real == 0.0:
return complex_zero
other_code()
One more example here, with some tiny details documented inline:
def foo( # Note that how I use the parenthesis rather than backslash "\"
# to natually break the function definition into multiple lines.
a_very_long_parameter_name,
# The "inline" text does not really have to be at same line,
# when your parameter name is very long.
# Besides, you can use this way to have multiple lines doc too.
# The one extra level indentation here natually matches the
# original Python indentation style.
#
# This parameter represents blah blah
# blah blah
# blah blah
param_b, # Some description about parameter B.
# Some more description about parameter B.
# As you probably noticed, the vertical alignment of pound sign
# is less a concern IMHO, as long as your docs are intuitively
# readable.
last_param, # As a side note, you can use an optional comma for
# your last parameter, as you can do in multi-line list
# or dict declaration.
): # So this ending parenthesis occupying its own line provides a
# perfect chance to use inline doc to document the return value,
# despite of its unhappy face appearance. :)
pass
The benefits (as @mark-horvath already pointed out in another comment) are:
Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.
Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.
PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
There seems to be a bug in Visual Studio 2015 community. For a 64-bit project, the include folder isn't found unless it's in the win32 bit configuration Additional Include Folders list.
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:
class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}
This way variables penguin
and lion
infer concrete type Penguin
or Lion
even in the TypeScript intellisense.
const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.
const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.
Found a solution to this. Just ISNULL
the CASE
statement:
ISNULL(CASE x WHEN x THEN x ELSE x END, '') AS 'BLAH'
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
Starting Video with different browsers
For Opera 12
window.navigator.getUserMedia(param, function(stream) {
video.src =window.URL.createObjectURL(stream);
}, videoError );
For Firefox Nightly 18.0
window.navigator.mozGetUserMedia(param, function(stream) {
video.mozSrcObject = stream;
}, videoError );
For Chrome 22
window.navigator.webkitGetUserMedia(param, function(stream) {
video.src =window.webkitURL.createObjectURL(stream);
}, videoError );
Stopping video with different browsers
For Opera 12
video.pause();
video.src=null;
For Firefox Nightly 18.0
video.pause();
video.mozSrcObject=null;
For Chrome 22
video.pause();
video.src="";
Write these codes end of the C:\xampp\apache\conf\extra\httpd-vhosts.conf file,
DocumentRoot "D:/xampp/htdocs/foldername"
ServerName www.siteurl.com
ServerAlias www.siteurl.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
between the virtual host tag.
and edit the file System32/Drivers/etc/hosts use notepad as administrator
add bottom of the file
127.0.0.1 www.siteurl.com
An easy way is to use an online domain tool. My favorite is Domain Tools (formerly whois.sc). I'm not sure if they can resolve conflicting DNS records though. As an example, the DNS servers for stackoverflow.com are
NS51.DOMAINCONTROL.COM
NS52.DOMAINCONTROL.COM
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
A block width button could easily become responsive button if the parent container is responsive. I think that using a combination of a fixed width and a more detailed selector path instead of !important because:
1) Its not a hack (setting min-width and max-width the same is however hacky)
2) Does not use the !important tag which is bad practice
3) Uses width so will be very readable and anyone who understands how cascading works in CSS will see whats going on (maybe leave a CSS comment for this?)
4) Combine your selectors that apply to your targeted node for increased accuracy
.parent_element .btn.btn-primary.save-button {
width: 80px;
}
Iterate through a copy of the list and add new elements to the original list.
for (String s : new ArrayList<String>(list))
{
list.add("u");
}
See How to make a copy of ArrayList object which is type of List?
String to Time (using an arbitrary time):
String myTime = "10:00:00";
Time startingTime = new Time (myTime);
String to Time (using currentTime):
String currentTime = getCurrentTime();
Time startingTime = new Time (currentTime);
Time to String:
private String getCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("kkmmss");
String currentTime = dateFormat.format(System.currentTimeMillis());
return currentTime;
}
Actually, the correct way of checking for 32 bit or 64 bit platform is to use the Win64 constant which is defined in all versions of VBA (16 bit, 32 bit, and 64 bit versions).
#If Win64 Then
' Win64=true, Win32=true, Win16= false
#ElseIf Win32 Then
' Win32=true, Win16=false
#Else
' Win16=true
#End If
Source: VBA help on compiler constants
If you are using mongoose, I have found the following plugin to be a useful implementation of the JSON Patch format
The given answer assumes that the project in question use project inheritance in addition to module aggregation. In fact those are distinct concepts:
Some projects may be an aggregation of modules, yet not have a parent-child relationship between aggregator POM and the aggregated modules. (There may be no parent-child relationship at all, or the child modules may use a separate POM altogether as the "parent".) In these situations the given answer will not work.
After much reading and experimentation, it turns out there is a way to use the Versions Maven Plugin to update not only the aggregator POM but also all aggregated modules as well; it is the processAllModules
option. The following command must be done in the directory of the aggregator project:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules
The Versions Maven Plugin will not only update the versions of all contained modules, it will also update inter-module dependencies!!!! This is a huge win and will save a lot of time and prevent all sorts of problems.
Of course don't forget to commit the changes in all modules, which you can also do with the same switch:
mvn versions:commit -DprocessAllModules
You may decide to dispense with the backup POMS altogether and do everything in one command:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules -DgenerateBackupPoms=false
Try using a callback like this with the catch block.
document.getElementById("audio").play().catch(function() {
// do something
});
Based on the best answer:
file <- file("test.txt")
writeLines(yourObject, file)
close(file)
Note that the yourObject
needs to be in a string format; use as.character()
to convert if you need.
But this is too much typing for every save attempt. Let's create a snippet in RStudio.
In Global Options >> Code >> Snippet, type this:
snippet wfile
file <- file(${1:filename})
writeLines(${2:yourObject}, file)
close(file)
Then, during coding, type wfile
and press Tab.
If you don't require support for IE6:
h1 {margin-bottom:20px;}
div + div {margin-top:10px;}
The second line adds spacing between divs, but will not add any before the first div or after the last one.
If anyone is having issues with their FragmentStatePagerAdapter not properly restoring the state of its fragments...ie...new Fragments are being created by the FragmentStatePagerAdapter instead of it restoring them from state...
Make sure you call ViewPager.setOffscreenPageLimit()
BEFORE you call ViewPager.setAdapter(fragmentStatePagerAdapter)
Upon calling ViewPager.setOffscreenPageLimit()
...the ViewPager will immediately look to its adapter and try to get its fragments. This could happen before the ViewPager has a chance to restore the Fragments from savedInstanceState(thus creating new Fragments that can't be re-initialized from SavedInstanceState because they're new).
You can use require as well:
const moduleHolder = []
function loadModules(path) {
let stat = fs.lstatSync(path)
if (stat.isDirectory()) {
// we have a directory: do a tree walk
const files = fs.readdirSync(path)
let f,
l = files.length
for (var i = 0; i < l; i++) {
f = pathModule.join(path, files[i])
loadModules(f)
}
} else {
// we have a file: load it
var controller = require(path)
moduleHolder.push(controller)
}
}
Then use your moduleHolder with dynamically loaded controllers:
loadModules(DIR)
for (const controller of moduleHolder) {
controller(app, db)
}
Updating the ~/.profile
or ~/.bash_profile
does not work sometimes. I just deleted JDK 6 and source
d .bash_profile
.
Try running this:
sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo
Then, modify/add your JAVA_HOME and PATH variables.
source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH
Here is a small example you can run to test it:
[1,2,3,4,5,6,7,8,9].forEach(function(n){
var sum = 0;
console.log('Start for:' + n);
for (var i = 0; i < ( 10 - n) * 100000000; i++)
sum++;
console.log('Ended for:' + n, sum);
});
It will produce something like this(if it takes too less/much time, increase/decrease the number of iterations):
(index):48 Start for:1
(index):52 Ended for:1 900000000
(index):48 Start for:2
(index):52 Ended for:2 800000000
(index):48 Start for:3
(index):52 Ended for:3 700000000
(index):48 Start for:4
(index):52 Ended for:4 600000000
(index):48 Start for:5
(index):52 Ended for:5 500000000
(index):48 Start for:6
(index):52 Ended for:6 400000000
(index):48 Start for:7
(index):52 Ended for:7 300000000
(index):48 Start for:8
(index):52 Ended for:8 200000000
(index):48 Start for:9
(index):52 Ended for:9 100000000
(index):45 [Violation] 'load' handler took 7285ms
You can use the set() function to convert an iterable into a set, and then use standard set update operator (|=) to add the unique values from your new set into the existing one.
>>> a = { 1, 2, 3 }
>>> b = ( 3, 4, 5 )
>>> a |= set(b)
>>> a
set([1, 2, 3, 4, 5])
Example of AbstractMap.SimpleEntry:
import java.util.Map;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
Instantiate:
ArrayList<Map.Entry<Integer, Integer>> arr =
new ArrayList<Map.Entry<Integer, Integer>>();
Add rows:
arr.add(new AbstractMap.SimpleEntry(2, 3));
arr.add(new AbstractMap.SimpleEntry(20, 30));
arr.add(new AbstractMap.SimpleEntry(2, 4));
Fetch rows:
System.out.println(arr.get(0).getKey());
System.out.println(arr.get(0).getValue());
System.out.println(arr.get(1).getKey());
System.out.println(arr.get(1).getValue());
System.out.println(arr.get(2).getKey());
System.out.println(arr.get(2).getValue());
Should print:
2
3
20
30
2
4
It's good for defining edges of graph structures. Like the ones between neurons in your head.
You can do like this:
#mydiv {
position: fixed;
height: 30px;
top: 0;
left: 0;
width: 100%;
}
This will create a div
, that will be fixed on top of your screen. - fixed
for a = 1 to 100 step 1
Command line in Windows . Please use %%a if running in Batch file.
for /L %a in (1,1,100) Do echo %a
Well, here is one solution I ended up with, but I hope there's a more elegant one...
StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
char tmpChar = name.charAt( i );
if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
result.append( tmpChar );
}
}
result
ends up with the desired result...
Check this: http://en.wikipedia.org/wiki/Pigeonhole_principle. If A, B and C are of same type, it cannot be done. If A and B are 16-bit integers, and C is 32-bit, then you can simply use shifting.
The very nature of hashing algorithms is that they cannot provide a unique hash for each different input.
I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.
You are looking for size
:
In [11]: df.groupby(['col5', 'col2']).size()
Out[11]:
col5 col2
1 A 1
D 3
2 B 2
3 A 3
C 1
4 B 1
5 B 2
6 B 1
dtype: int64
To get the same answer as waitingkuo (the "second question"), but slightly cleaner, is to groupby the level:
In [12]: df.groupby(['col5', 'col2']).size().groupby(level=1).max()
Out[12]:
col2
A 3
B 2
C 1
D 3
dtype: int64
Here is one more way to specify event.target
:
import { Component, EventEmitter, Output } from '@angular/core';_x000D_
_x000D_
@Component({_x000D_
selector: 'text-editor',_x000D_
template: `<textarea (keyup)="emitWordCount($event)"></textarea>`_x000D_
})_x000D_
export class TextEditorComponent {_x000D_
_x000D_
@Output() countUpdate = new EventEmitter<number>();_x000D_
_x000D_
emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there_x000D_
_x000D_
this.countUpdate.emit(_x000D_
// using it directly without `event`_x000D_
(target.value.match(/\S+/g) || []).length);_x000D_
}_x000D_
}
_x000D_
On the bottom right-hand corner of your Sublime Text window, you'll see an indentation indicator that looks a lot like this:
Clicking it will open a menu with options to adjust your indentation preferences, and more importantly, Convert Indentation to Tabs/Spaces
.
The same menu is listed under View -> Indentation
.
Using React Hooks
Import:
import { useHistory } from "react-router-dom";
In stateless component:
let history = useHistory();
On Event
history.goBack()
$ git rev-parse HEAD 273cf91b4057366a560b9ddcee8fe58d4c21e6cb
Update:
Alternatively (if you have tags):
(Good for naming a version, not very good for passing back to git.)
$ git describe v0.1.49-localhost-ag-1-g273cf91
Or (as Mark suggested, listing here for completeness):
$ git show --oneline -s c0235b7 Autorotate uploaded images based on EXIF orientation
What happens when the repository owner has not prepared a zip file, and you just want a download to use yourself? There is an answer and you don't need to go though that horrid process to download software, install and register keys and whatnot on GitHub, etc.!
To simply download a repository as a zip file: add the extra path '/zipball/master/' to the end of the repository URL and voila, it gives you a zip file of the whole lot.
For example,
becomes:
It then gives you a zip file to download.
With SQL Server you'd SELECT SCOPE_IDENTITY() to get the last identity value for the current process.
With SQlite, it looks like for an autoincrement you would do
SELECT last_insert_rowid()
immediately after your insert.
http://www.mail-archive.com/[email protected]/msg09429.html
In answer to your comment to get this value you would want to use SQL or OleDb code like:
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT last_insert_rowid()";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
int lastID = (Int32) cmd.ExecuteScalar();
}
Go to the Preferences tab (menu File → Settings), and then search as “word wrap”. The following animated image is helpful too.
If you are using jquery 1.7+, this works well:
$("donotscrollme").on("touchmove", false);
Answer for BigDecimal throws ArithmeticException
public static void main(String[] args) {
int age = 30;
BigDecimal retireMentFund = new BigDecimal("10000.00");
retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = " Dennis";
for ( int i = age; i <=65; i++){
recalculate(retireMentFund,new BigDecimal("0.10"));
}
BigDecimal monthlyPension = retireMentFund.divide(
yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));
System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
}
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
fundAmount.multiply(rate.add(new BigDecimal("1.00")));
}
Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem
The technique i used before discovering .Any()
:
var hasJohn = (from customer in list
where customer.FirstName == "John"
select customer).FirstOrDefault() != null;
I must be dense, but I still don't get it. Are there any actual examples of small app's written in a functional language like F# where you can look at the source code and see how and why it was better to use such an approach than, say, C#?
I wrote a set of attached properties to automatically sort a GridView
, you can check it out here. It doesn't handle the up/down arrow, but it could easily be added.
<ListView ItemsSource="{Binding Persons}"
IsSynchronizedWithCurrentItem="True"
util:GridViewSort.AutoSort="True">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}"
util:GridViewSort.PropertyName="Name"/>
<GridViewColumn Header="First name"
DisplayMemberBinding="{Binding FirstName}"
util:GridViewSort.PropertyName="FirstName"/>
<GridViewColumn Header="Date of birth"
DisplayMemberBinding="{Binding DateOfBirth}"
util:GridViewSort.PropertyName="DateOfBirth"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.
Let's take this warning as an example:
npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.
With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install
so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).
In a situation like this:
npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install
, or run npm install
for the specific version you need. Like this:
npm install @angular/[email protected] --save
You can leave out the --save
if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.
In this situation:
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
You are running Windows, and fsevent requires OSX. This warning can be ignored.
Hope this helps, and have fun learning Angular!
you could use ⊕ or ⊗
Adding the following lines to a new script will clear all variables each time you rerun the script:
from IPython import get_ipython
get_ipython().magic('reset -sf')
To make life easy, you can add them to your default template.
In Spyder: Tools>Preferences>Editor>Edit template
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.standingsButton) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
You can create multiple canvas
elements without appending them into document. These will be your layers:
Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage
on context
.
Example:
/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);
/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);
/* virtual canvase 2 - not appended to the DOM */
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)
/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);
And here is some codepen: https://codepen.io/anon/pen/mQWMMW
You could use cursor.lastrowid (see "Optional DB API Extensions"):
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('test','test'))
print(cursor.lastrowid)
# 1
If two people are inserting at the same time, as long as they are using different cursor
s, cursor.lastrowid
will return the id
for the last row that cursor
inserted:
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
print(cursor2.lastrowid)
# 3
print(cursor.lastrowid)
# 2
cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
(100,'blah','blah'))
print(cursor.lastrowid)
# 100
Note that lastrowid
returns None
when you insert more than one row at a time with executemany
:
cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
(('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None
Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
Control-C works, although depending on what the process is doing it might not take right away.
If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
$my_url outputs:
http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234
So now you can get this value using $_GET['id']
or $_REQUEST['id']
(decoded).
echo urldecode($_GET["id"]);
Output
http://google.com/?var=234&key=234
To get every GET parameter:
foreach ($_GET as $key=>$value) {
echo "$key = " . urldecode($value) . "<br />\n";
}
$key
is GET key and $value
is GET value for $key
.
Or you can use alternative solution to get array of GET params
$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
$pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($pairs as $pair) {
$part = explode('=', $pair);
$get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
}
}
$get_parameters
is same as url decoded $_GET
.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.
Judging from the example information above, I think this entire article is based on a bugged behavior in Tomcat 6.0.29 and earlier. See https://issues.apache.org/bugzilla/show_bug.cgi?id=50026. Upgrade to Tomcat 6.0.30 and the behavior between (Tomcat|Jetty) should merge.
If you pass the -v
flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will look in several places for the config file:
ansible.cfg
in the current directory where you ran ansible-playbook
~/.ansible.cfg
/etc/ansible/ansible.cfg
Recent versions of Mercurial include the evolve
extension which provides the hg amend
command. This allows amending a commit without losing the pre-amend history in your version control.
hg amend [OPTION]... [FILE]...
aliases: refresh
combine a changeset with updates and replace it with a new one
Commits a new changeset incorporating both the changes to the given files and all the changes from the current parent changeset into the repository. See 'hg commit' for details about committing changes. If you don't specify -m, the parent's message will be reused. Behind the scenes, Mercurial first commits the update as a regular child of the current parent. Then it creates a new commit on the parent's parents with the updated contents. Then it changes the working copy parent to this new combined changeset. Finally, the old changeset and its update are hidden from 'hg log' (unless you use --hidden with log).
See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve
extension.
Though best way is to get it done will be using a window function, it can also be done using a simple correlated sub-query.
Select id, someday, somevalue, (select sum(somevalue)
from testtable as t2
where t2.id = t1.id
and t2.someday <= t1.someday) as runningtotal
from testtable as t1
order by id,someday;
In some browsers:
flex:1;
does not equal flex:1 1 0;
flex:1;
= flex:1 1 0n;
(where n is a length unit).
The key point here is that flex-basis requires a length unit.
In Chrome for example flex:1
and flex:1 1 0
produce different results. In most circumstances it may appear that flex:1 1 0;
is working but let's examine what really happens:
Flex basis is ignored and only flex-grow and flex-shrink are applied.
flex:1 1 0;
= flex:1 1;
= flex:1;
This may at first glance appear ok however if the applied unit of the container is nested; expect the unexpected!
Try this example in CHROME
.Wrap{_x000D_
padding:10px;_x000D_
background: #333;_x000D_
}_x000D_
.Flex110x, .Flex1, .Flex110, .Wrap {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
flex-direction: column;_x000D_
}_x000D_
.Flex110 {_x000D_
-webkit-flex: 1 1 0;_x000D_
flex: 1 1 0;_x000D_
}_x000D_
.Flex1 {_x000D_
-webkit-flex: 1;_x000D_
flex: 1;_x000D_
}_x000D_
.Flex110x{_x000D_
-webkit-flex: 1 1 0%;_x000D_
flex: 1 1 0%;_x000D_
}
_x000D_
FLEX 1 1 0_x000D_
<div class="Wrap">_x000D_
<div class="Flex110">_x000D_
<input type="submit" name="test1" value="TEST 1">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1_x000D_
<div class="Wrap">_x000D_
<div class="Flex1">_x000D_
<input type="submit" name="test2" value="TEST 2">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1 1 0%_x000D_
<div class="Wrap">_x000D_
<div class="Flex110x">_x000D_
<input type="submit" name="test3" value="TEST 3">_x000D_
</div>_x000D_
</div>
_x000D_
It should be noted that this fails because some browsers have failed to adhere to the specification.
Browsers that use the full flex specification:
Latest versions of Chrome seem to have finally rectified this issue but other browsers still have not.
Tested and working in Chrome Ver 74.
Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):
netsh wlan set hostednetwork mode=allow ssid=tests key=tests123
netsh wlan start hostednetwork
Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)
Then right click on the lan connection (internet connection that you are using), properties.
Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"
This done, your connection is ready to use!
It's much simpler to do this:
DateTime dt = new DateTime(633896886277130000);
Which gives
dt.ToString() ==> "9/27/2009 10:50:27 PM"
You can format this any way you want by using dt.ToString(MyFormat)
. Refer to this reference for format strings. "MMMM dd, yyyy"
works for what you specified in the question.
Not sure where you get October 1.
public function index()
{
if(!$this->isLogin())
return Redirect::to('login');
if(Request::ajax()) // This is check ajax request
{
return $JSON;
}
$data = array();
$data['records'] = $this->table->fetchAll();
$this->setLayout(compact('data'));
}
If you want to grant to both tables and views try:
SELECT DISTINCT
|| OWNER
|| '.'
|| TABLE_NAME
|| ' to db_user;'
FROM
ALL_TAB_COLS
WHERE
TABLE_NAME LIKE 'TABLE_NAME_%';
For just views try:
SELECT
'grant select on '
|| OWNER
|| '.'
|| VIEW_NAME
|| ' to REPORT_DW;'
FROM
ALL_VIEWS
WHERE
VIEW_NAME LIKE 'VIEW_NAME_%';
Copy results and execute.
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe
showing the user's C:
drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.
In MySQL, use the JSON type.
Contra the answers above, the SQL standard has included array types for almost twenty years; they are useful, even if MySQL has not implemented them.
In your example, however, you'll likely want to create three tables: person and fruit, then person_fruit to join them.
DROP TABLE IF EXISTS person_fruit;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS fruit;
CREATE TABLE person (
person_id INT NOT NULL AUTO_INCREMENT,
person_name VARCHAR(1000) NOT NULL,
PRIMARY KEY (person_id)
);
CREATE TABLE fruit (
fruit_id INT NOT NULL AUTO_INCREMENT,
fruit_name VARCHAR(1000) NOT NULL,
fruit_color VARCHAR(1000) NOT NULL,
fruit_price INT NOT NULL,
PRIMARY KEY (fruit_id)
);
CREATE TABLE person_fruit (
pf_id INT NOT NULL AUTO_INCREMENT,
pf_person INT NOT NULL,
pf_fruit INT NOT NULL,
PRIMARY KEY (pf_id),
FOREIGN KEY (pf_person) REFERENCES person (person_id),
FOREIGN KEY (pf_fruit) REFERENCES fruit (fruit_id)
);
INSERT INTO person (person_name)
VALUES
('John'),
('Mary'),
('John'); -- again
INSERT INTO fruit (fruit_name, fruit_color, fruit_price)
VALUES
('apple', 'red', 1),
('orange', 'orange', 2),
('pineapple', 'yellow', 3);
INSERT INTO person_fruit (pf_person, pf_fruit)
VALUES
(1, 1),
(1, 2),
(2, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3);
If you wish to associate the person with an array of fruits, you can do so with a view:
DROP VIEW IF EXISTS person_fruit_summary;
CREATE VIEW person_fruit_summary AS
SELECT
person_id AS pfs_person_id,
max(person_name) AS pfs_person_name,
cast(concat('[', group_concat(json_quote(fruit_name) ORDER BY fruit_name SEPARATOR ','), ']') as json) AS pfs_fruit_name_array
FROM
person
INNER JOIN person_fruit
ON person.person_id = person_fruit.pf_person
INNER JOIN fruit
ON person_fruit.pf_fruit = fruit.fruit_id
GROUP BY
person_id;
The view shows the following data:
+---------------+-----------------+----------------------------------+
| pfs_person_id | pfs_person_name | pfs_fruit_name_array |
+---------------+-----------------+----------------------------------+
| 1 | John | ["apple", "orange"] |
| 2 | Mary | ["orange", "pineapple"] |
| 3 | John | ["apple", "orange", "pineapple"] |
+---------------+-----------------+----------------------------------+
In 5.7.22, you'll want to use JSON_ARRAYAGG, rather than hack the array together from a string.
I'm trying to use variables and settings from that file, not to invoke a separate process.
Well, simply importing the file with import filename
(minus .py, needs to be in the same directory or on your PYTHONPATH
) will run the file, making its variables, functions, classes, etc. available in the filename.variable
namespace.
So if you have cheddar.py
with the variable spam and the function eggs – you can import them with import cheddar
, access the variable with cheddar.spam
and run the function by calling cheddar.eggs()
If you have code in cheddar.py
that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
I think of Divide & Conquer
as an recursive approach and Dynamic Programming
as table filling.
For example, Merge Sort
is a Divide & Conquer
algorithm, as in each step, you split the array into two halves, recursively call Merge Sort
upon the two halves and then merge them.
Knapsack
is a Dynamic Programming
algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.
You can use something like this:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class testHashes {
public static void main(String args[]){
Map<String,String> myMap1 = new HashMap<String, String>();
List<Map<String , String>> myMap = new ArrayList<Map<String,String>>();
myMap1.put("URL", "Val0");
myMap1.put("CRC", "Vla1");
myMap1.put("SIZE", "Val2");
myMap1.put("PROGRESS", "Val3");
myMap.add(0,myMap1);
myMap.add(1,myMap1);
for (Map<String, String> map : myMap) {
System.out.println(map.get("URL"));
System.out.println(map.get("CRC"));
System.out.println(map.get("SIZE"));
System.out.println(map.get("PROGRESS"));
}
//System.out.println(myMap);
}
}
Try this:
a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
list(a).count(1)
For running without any browser, you can run it in headless mode.
I show you one example in Python that is working for me right now
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)
I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome
1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to
F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;
change your drive and folder depending on your requirement...
DAO is an act like as "Persistence Manager " in 3 tier architecture as well as DAO also design pattern as you can consult "Gang of Four" book. Your application service layer just need to call the method of DAO class without knowing hidden & internal details of DAO's method.
With only html and css, its not posible to change the src of image. If you do replace the img tag with div tag, then you might be able to change the image that is set as the background as like
div {
background: url('http://dummyimage.com/100x100/000/fff');
}
div:hover {
background: url('http://dummyimage.com/100x100/eb00eb/fff');
}
And if you think you can use some javascript code then you should be able to change the src of the img tag as below
function hover(element) {_x000D_
element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');_x000D_
}_x000D_
_x000D_
function unhover(element) {_x000D_
element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');_x000D_
}
_x000D_
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
_x000D_
Update:
Since git rm .
deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:
git reset HEAD . # This undoes the index changes
git checkout . # This checks out files in this and child directories from the HEAD
This should do what you want. It does not affect parent folders of your checked-out code or index.
Old answer that wasn't:
reset HEAD
will do the trick, and will not erase any uncommitted changes you have made to your files.
after that you need to repeat any git add
commands you had queued up.
Using a static const is like using any other const variables in your code. This means you can trace wherever the information comes from, as opposed to a #define that will simply be replaced in the code in the pre-compilation process.
You might want to take a look at the C++ FAQ Lite for this question: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
Assert does throw an AssertionError if you run your app with assertions turned on.
int a = 42;
assert a >= 0 && d <= 10;
If you run this with, say: java -ea -jar peiska.jar
It shall throw an java.lang.AssertionError
I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>
). It seems that when you inspect the element with Developer Tools, the element.style
has no style assigned. So instead of using ng-class
, I have tried using ng-style
, and in this case, the new CSS attribute does appear inside element.style
. This code works great for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar is what I am evaluating, and in each case I apply a style to each <td>
depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.
UPDATE
If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a
OR we are in route_b
, the active class will be applied.
This works just having a logic function on the right that returns true or false.
So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.
By the way, I forgot to give you the function isActive():
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div
, you can use the following code (very useful in ng-repeat
):
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons from Font Awesome
I attempted to find a more elegant solution, but the best I could do was basically the same thing that Dyno Fu said:
from copy import copy
def subtract_lists(a, b):
"""
>>> a = [0, 1, 2, 1, 0]
>>> b = [0, 1, 1]
>>> subtract_lists(a, b)
[2, 0]
>>> import random
>>> size = 10000
>>> a = [random.randrange(100) for _ in range(size)]
>>> b = [random.randrange(100) for _ in range(size)]
>>> c = subtract_lists(a, b)
>>> assert all((x in a) for x in c)
"""
a = copy(a)
for x in b:
if x in a:
a.remove(x)
return a
I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
public class Base64Example {
public static void main(String[] args) {
Base64Example tempObject = new Base64Example();
// convert file to regular byte array
byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");
// encoded file in Base64
byte[] encodedFile = Base64.encodeBase64(codedFile);
// print out the byte array
System.out.println(Arrays.toString(encodedFile));
// print the encoded String
System.out.println(encodedFile);
// decode file back to regular byte array
byte[] decodedByteArray = Base64.decodeBase64(encodedFile);
// save decoded byte array to a file
boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);
// print out success
System.out.println("success : " + success);
}
public byte[] convertFileToByteArray(String filePath) {
Path path = Paths.get(filePath);
byte[] codedFile = null;
try {
codedFile = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return codedFile;
}
public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {
boolean success = false;
Path path = Paths.get(filePath);
try {
Files.write(path, decodedByteArray);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
You can pass an object as argument to the Thread.Start
and use it as a shared data storage between the current thread and the initiating thread.
You can also just directly access (with the appropriate locking of course) your data members, if you started the thread using the instance form of the ThreadStart
delegate.
You can't use attributes to create shared data between threads. You can use the attribute instances attached to your class as a data storage, but I fail to see how that is better than using static or instance data members.
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));
I tried every answer on here and none of them worked. I ended up getting it working by upping the deployment target from 10.0 to 11.0. I have no idea why that fixed it, but I suspect it has to do with upgrading to Xcode 10.2.1.
RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).
Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.
Checkout And Run The Following Code. It will help you...
$( function() {_x000D_
$.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
_renderItem: function( ul, item ) {_x000D_
var li = $( "<li>" ),_x000D_
wrapper = $( "<div>", { text: item.label } );_x000D_
_x000D_
if ( item.disabled ) {_x000D_
li.addClass( "ui-state-disabled" );_x000D_
}_x000D_
_x000D_
$( "<span>", {_x000D_
style: item.element.attr( "data-style" ),_x000D_
"class": "ui-icon " + item.element.attr( "data-class" )_x000D_
})_x000D_
.appendTo( wrapper );_x000D_
_x000D_
return li.append( wrapper ).appendTo( ul );_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#filesA" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons" );_x000D_
_x000D_
$( "#filesB" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons customicons" );_x000D_
_x000D_
$( "#people" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget")_x000D_
.addClass( "ui-menu-icons avatar" );_x000D_
} );_x000D_
</script>_x000D_
<style>_x000D_
h2 {_x000D_
margin: 30px 0 0 0;_x000D_
}_x000D_
fieldset {_x000D_
border: 0;_x000D_
}_x000D_
label
_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* select with custom icons */_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
padding: 0.5em 0 0.5em 3em;_x000D_
}_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
height: 24px;_x000D_
width: 24px;_x000D_
top: 0.1em;_x000D_
}_x000D_
.ui-icon.video {_x000D_
background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.podcast {_x000D_
background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.rss {_x000D_
background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
}_x000D_
_x000D_
/* select with CSS avatar icons */_x000D_
option.avatar {_x000D_
background-repeat: no-repeat !important;_x000D_
padding-left: 20px;_x000D_
}_x000D_
.avatar .ui-icon {_x000D_
background-position: left top;_x000D_
}
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="demo">_x000D_
_x000D_
<form action="#">_x000D_
<h2>Selectmenu with framework icons</h2>_x000D_
<fieldset>_x000D_
<label for="filesA">Select a File:</label>_x000D_
<select name="filesA" id="filesA">_x000D_
<option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
<option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
<option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
<option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
<option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom icon images</h2>_x000D_
<fieldset>_x000D_
<label for="filesB">Select a podcast:</label>_x000D_
<select name="filesB" id="filesB">_x000D_
<option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
<option value="myvideo" data-class="video">Scott González Video</option>_x000D_
<option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
<fieldset>_x000D_
<label for="people">Select a Person:</label>_x000D_
<select name="people" id="people">_x000D_
<option value="1" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16');">John Resig</option>_x000D_
<option value="2" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&r=g&s=16');">Tauren Mills</option>_x000D_
<option value="3" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&r=g&s=16');">Jane Doe</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
There is text-decoration-thickness
, currently part of CSS Text Decoration Module Level 4. It's at "Editor's Draft" stage - so it's a work in progress and subject to change. As of January 2020, it is only supported in Firefox and Safari.
The text-decoration-thickness CSS property sets the thickness, or width, of the decoration line that is used on text in an element, such as a line-through, underline, or overline.
a {
text-decoration-thickness: 2px;
}
Codepen: https://codepen.io/mrotaru/pen/yLyLOgr (Firefox only)
There's also text-decoration-color
, which is part of CSS Text Decoration Module Level 3. This is more mature (Candidate Recommendation) and is supported in most major browsers (exceptions are Edge and IE). Of course it can't be used to alter the thickness of the line, but can be used to achieve a more "muted" underline (also shown in the codepen).