You can combine filter with the text.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<title>SVG colored patterns via mask</title>_x000D_
</head>_x000D_
<body>_x000D_
<svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">_x000D_
<defs>_x000D_
<filter x="0" y="0" width="1" height="1" id="bg-text">_x000D_
<feFlood flood-color="white"/>_x000D_
<feComposite in="SourceGraphic" operator="xor" />_x000D_
</filter>_x000D_
</defs>_x000D_
<!-- something has already existed -->_x000D_
<rect fill="red" x="150" y="20" width="100" height="50" />_x000D_
<circle cx="50" cy="50" r="50" fill="blue"/>_x000D_
_x000D_
<!-- Text render here -->_x000D_
<text filter="url(#bg-text)" fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
<text fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
</svg>_x000D_
</body>_x000D_
</html>
_x000D_
When you're going to work with such time series in Python, pandas
is indispensable. And here's the good news: it comes with a historical data downloader for Yahoo: pandas.io.data.DataReader
.
from pandas.io.data import DataReader
from datetime import datetime
ibm = DataReader('IBM', 'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
print(ibm['Adj Close'])
Here's an example from the pandas
documentation.
Update for pandas >= 0.19:
The pandas.io.data
module has been removed from pandas>=0.19
onwards. Instead, you should use the separate pandas-datareader
package. Install with:
pip install pandas-datareader
And then you can do this in Python:
import pandas_datareader as pdr
from datetime import datetime
ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
print(ibm['Adj Close'])
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
Try the load() function.
$('#content').load("http://vnexpress.net");
Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:
Access-Control-Allow-Origin:*
to allow requests from everywhere.
You should use Joda Time library because Java Util Date returns wrong values sometimes.
Joda vs Java Util Date
For example days between yesterday (dd-mm-yyyy, 12-07-2016) and first day of year in 1957 (dd-mm-yyyy, 01-01-1957):
public class Main {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try {
date = format.parse("12-07-2016");
} catch (ParseException e) {
e.printStackTrace();
}
//Try with Joda - prints 21742
System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
//Try with Java util - prints 21741
System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));
}
private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
DateTime jodaDateTime = new DateTime(date);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
DateTime y1957 = formatter.parseDateTime("01-01-1957");
return Days.daysBetween(y1957 , jodaDateTime).getDays();
}
private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date y1957 = null;
try {
y1957 = format.parse("01-01-1957");
} catch (ParseException e) {
e.printStackTrace();
}
return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
}
So I really advice you to use Joda Time library.
It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor
for the various constructors.
this Works for me perfectly:
.modal {
text-align: center;
padding: 0!important;
}
.modal:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
complete Demo URL : https://codepen.io/dimbslmh/full/mKfCc
Assuming your code above is the actual code, you have two problems:
1) your if statements need to be '==', not '='. You want to do comparison, not assignment.
2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe
if (a == false) {
a = true;
} else if (a == true) {
a = false;
}
Another thing that would make it even simpler is the '!' operator:
a = !a;
will switch the value of a.
I'm going to assume compiling the QuickFix package does not produce a setup.py
file, but rather only compiles the Python bindings and relies on make install
to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so
extension), and add that directory to your PYTHONPATH
environmental variable e.g., add
export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH
or similar line in your shell configuration file.
A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local
. Assuming QuickFix knows to put the Python files in the appropriate site-packages
, when you do make install
, it should install the files to ~/.local/lib/pythonX.Y/site-packages
, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.
If, on the other hand, it did provide a setup.py
file, simply run
python setup.py install --user
for Python 2.6+.
Some short background:
Unfortunately the Unix API doesn't provide a running program with the full path to the executable. In fact, the program executing yours can provide whatever it wants in the field that normally tells your program what it is. There are, as all the answers point out, various heuristics for finding likely candidates. But nothing short of searching the entire filesystem will always work, and even that will fail if the executable is moved or removed.
But you don't want the Perl executable, which is what's actually running, but the script it is executing. And Perl needs to know where the script is to find it. It stores this in __FILE__
, while $0
is from the Unix API. This can still be a relative path, so take Mark's suggestion and canonize it with File::Spec->rel2abs( __FILE__ );
Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.
Update:
You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.
function truncate(input) {
if (input.length > 5) {
return input.substring(0, 5) + '...';
}
return input;
};
or in ES6
const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
I faced the same issue because I didn't have permission to query the database I was trying to.
In the case you don't have permission to query the table/database, besides the Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask
error, you will see that in Cloudera Manager is not even registering your query.
When you test with device you want to add your PC ip address.
in pc run in cmd Ipconfig
in ubuntu run terminal ifconfig
Then use "http://your_pc_ip_address:8080/register"
insted of using "http://10.0.2.2:8080/register"
in my pc = 192.168.1.3
and also add internet permission to Manifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
This error generally comes if the code is not deployed properly.
In my case, I have two services ServiceA and ServiceB. I found the problem that ServiceB files were not deployed properly. Because of which when ServiceA was calling ServiceB internally it was giving below error.
Please make sure the files and references are deployed properly.
I actual ran into the same requirement. I simply used CSS override like this
.navbar .btn-toolbar { margin-top: 0; margin-bottom: 0 }
You can read it by chunks (byte buffer[] = new byte[2048]
) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml
has been adjusted:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>
Change this file to comment the Valve
:
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
After that, refresh your browser (not need to restart Tomcat), you can see the manager page.
A "rollback" only works if you used transactions. That way you can group queries together and undo all queries if only one of them fails.
But if you already committed the transaction (or used a regular DELETE-query), the only way of getting your data back is to recover it from a previously made backup.
I'm not sure about HQL, but in JPA you just call the query's setParameter
with the parameter and collection.
Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);
where names
is the collection of names you're searching for
Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");
You probably updated your Ubuntu installation and one of the updates included the upgrade of Apache to version 2.4.x
In Apache 2.4.x the vhost configuration files, located in the /etc/apache2/sites-available directory, must have the .conf extension.
Using terminal (mv command), rename all your existing configuration files and add the .conf extension to all of them.
mv /etc/apache2/sites-available/cmsplus.dev /etc/apache2/sites-available/cmsplus.dev.conf
If you get a "Permission denied" error, then add "sudo " in front of your terminal commands.
You do not need to make any other changes to the configuration files.
Enable the vhost(s):
a2ensite cmsplus.dev.conf
And then reload Apache:
service apache2 reload
Your sites should be up and running now.
UPDATE: As mentioned here, a Linux distribution that you installed changed the configuration to Include *.conf only. Therefore it has nothing to do with Apache 2.2 or 2.4
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use &
and |
it will always evaluate both sides of the expression.
Use logging.exception
from within the except:
handler/block to log the current exception along with the trace information, prepended with a message.
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise
Now looking at the log file, /tmp/logging_example.out
:
DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
Could be SELinux. Check the appropriate log file (/var/log/messages? - been a while since I've used a RedHat derivative) to see if that's blocking the access.
Yes, delete this;
has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;
, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete
's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete
(§[expr.delete]) doesn't mention delete this;
specifically at all. The section on destrucors does mention delete this
in one place (§[class.dtor]/13):
At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).
That tends to support the idea that the standard considers delete this;
to be valid--if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this;
at all, as far as I know.
Anyway, some consider delete this
a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.
The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When start to you make a phone call, something takes note of that and creates a phone_call
object. From that point onward, the phone_call
object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call
object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call
object is based on when the first person starts the call and when the last people leave the call--from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.
For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.
Pass in the straight XML instead of a dictionary.
This is an old question, and this is somewhat subtly mentioned in the other posts, but the explanation that made this click for me is that non fast forward merges will require a separate commit.
No, there is no straightforward way because Python dictionaries do not have a set ordering.
From the documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
In other words, the 'index' of b
depends entirely on what was inserted into and deleted from the mapping before:
>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}
As of Python 2.7, you could use the collections.OrderedDict()
type instead, if insertion order is important to your application.
There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.
It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!
On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):
#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif
When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.
edit:
I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.
The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.
edit:
The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.
I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.
If anyone is interested in my version of the code, send me a message and I'll send it to you.
According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.
(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)
There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.
<?php echo APP_TITLE?> - <?php echo $page_title;?>
this should work fine for you
Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string. I found solution of this problem.
base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");
and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
From DateTime on msdn:
Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt"
instead.
Mixing some of the suggestions above, and was able to get a good solution:
Custom ScrollView:
package com.scrollable.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;
public class VScroll extends ScrollView {
public VScroll(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VScroll(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VScroll(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return false;
}
}
Custom HorizontalScrollView:
package com.scrollable.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
public class HScroll extends HorizontalScrollView {
public HScroll(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public HScroll(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HScroll(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return false;
}
}
the ScrollableImageActivity:
package com.scrollable.view;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
public class ScrollableImageActivity extends Activity {
private float mx, my;
private float curX, curY;
private ScrollView vScroll;
private HorizontalScrollView hScroll;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vScroll = (ScrollView) findViewById(R.id.vScroll);
hScroll = (HorizontalScrollView) findViewById(R.id.hScroll);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float curX, curY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mx = event.getX();
my = event.getY();
break;
case MotionEvent.ACTION_MOVE:
curX = event.getX();
curY = event.getY();
vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
mx = curX;
my = curY;
break;
case MotionEvent.ACTION_UP:
curX = event.getX();
curY = event.getY();
vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
break;
}
return true;
}
}
the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.scrollable.view.VScroll android:layout_height="fill_parent"
android:layout_width="fill_parent" android:id="@+id/vScroll">
<com.scrollable.view.HScroll android:id="@+id/hScroll"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/bg"></ImageView>
</com.scrollable.view.HScroll>
</com.scrollable.view.VScroll>
</LinearLayout>
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
A simple function that jumps (instantly scrolls) to the bottom of the whole page. It uses the built-in .scrollTop()
. I haven’t tried to adapt this to work with individual page elements.
function jumpToPageBottom() {
$('html, body').scrollTop( $(document).height() - $(window).height() );
}
Seems like a permissions issue. This is what worked for me
sudo chown -R $(whoami) /Library/Ruby/Gems/*
or in your case
sudo chown -R $(whoami) /usr/local/lib/ruby/gems/2.0.0/gems/
What does this do:
This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.
<div class="form-group col-12">_x000D_
<hr>_x000D_
</div>
_x000D_
You need a gcc
, g++
compiler toolchain (on your windows machine) for the eclipse which you have manually downloaded,
One of the options can be done implicit via cygwin
installation(by selecting proper development packages for gcc
, g++
) and then add the location of the compiled gcc
,g++
package like C:\cygwin\etc\alternatives
to the PATH
variable for windows environment.
After this open eclipse and go to Project->properties->C/C++ Tool Chain Editor
and add replace default GNU C++ compiler
and GNU C Compiler
with Cygwin C++ compiler
and Cygwin C compiler
and rebuild the project. The errors related to gcc, g++ PATH not found
will now be gone.
Kotlin solution using extension function, to set and unset the tinting :
fun ImageView.setTint(@ColorInt color: Int?) {
if (color == null) {
ImageViewCompat.setImageTintList(this, null)
return
}
ImageViewCompat.setImageTintMode(this, PorterDuff.Mode.SRC_ATOP)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(color))
}
Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute
Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.
For any sub domain request, use this:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+)
RewriteRule ^(.*)$ /%1/$1 [L]
Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.
We can summarize by using summarize_at
, summarize_all
and summarize_if
on dplyr 0.7.4
. We can set the multiple columns and functions by using vars
and funs
argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4
, summarise_each
(and mutate_each
) is already deprecated, so we cannot use these functions.
options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)
library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’
set.seed(123)
df <- data_frame(
a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)
df %>% group_by(grp) %>%
summarise_each(.vars = letters[1:4],
.funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean
You should change to the following code. The following codes all have the same result.
# summarise_at
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = names(.)[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = vars(a,b,c,d),
.funs = c(mean="mean"))
# summarise_all
df %>% group_by(grp) %>%
summarise_all(.funs = c(mean="mean"))
# summarise_if
df %>% group_by(grp) %>%
summarise_if(.predicate = function(x) is.numeric(x),
.funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 3.6 3.00
# 2 2 4.25 2.75 4.0 3.75
# 3 3 3.00 5.00 1.0 2.00
You can also have multiple functions.
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:2],
.funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean a_Sd b_Sd
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 1.4832397 1.870829
# 2 2 4.25 2.75 0.9574271 1.258306
# 3 3 3.00 5.00 NA NA
Incase their is local uncommitted changes and avoid merge conflict while pulling.
git stash save
git pull
git stash pop
public static bool IsNegative<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) < 0;
}
In query, CONCAT_WS()
function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
you have to add the missing local lang helper: for me the missing ones where de_LU de_LU.UTF-8 . Mongo 2.6.4 worked wihtout mongo 2.6.5 throw an error on this
A little late, but I use a _is_running
variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.
def stop(self):
self._is_running = False
And in run()
just loop on while(self._is_running)
To temporarily disable the draggable behavior use:
$('#item-id').draggable( "disable" )
To remove the draggable behavior permanently use:
$('#item-id').draggable( "destroy" )
From what I understand of your question, it appears that you want to apply a permutation that you specify on a list
. This is done by specifying another list
(lets call it p
) that holds the indices of the elements of the original list
that should appear in the permuted list
. You then use p
to make a new list
by simply substituting the element at each position by that whose index is in that position in p
.
def apply_permutation(lst, p):
return [lst[x] for x in p]
arr=list("abcde")
new_order=[3,2,0,1,4]
print apply_permutation(arr,new_order)
This prints ['d', 'c', 'a', 'b', 'e']
.
This actually creates a new list
, but it can be trivially modified to permute the original "in place".
If you only want to import a certificate in PEM format into a keystore, keytool will do the job:
keytool -import -alias *alias* -keystore cacerts -file *cert.pem*
I was able to connect Robomongo to a remote instance of MongoDB running on Mongo Labs using the connection string as follows:
Download the latest version of Robomongo. I downloaded 0.9 RC6 from here.
From the connection string, populate the server address and port numbers as follows.
Populate DB name and username and password as follows under the authentication tab.
Test the connection.
// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);
// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
// ...
return *this;
}
This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.
Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.
More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.
To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true
For character Character.isLetter(str.charAt(0)) --return true
If you are using C# 7 or above, you can use tuple types instead of anonymous types.
var myList = new List<(int IntProp, string StrProp)>();
myList.Add((IntProp: 123, StrProp: "XYZ"));
Without knowing all the information... You could bind a reset trigger to your model or controller:
this.bind("reset", this.updateView);
and when you want to reset the views, trigger a reset.
For your callback, do something like:
updateView: function() {
view.remove();
view.render();
};
Send Mail using phpMailer library through Gmail Please donwload library files from Github
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "[email protected]";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery) use ($stakeholderId){
$subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
$subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
});
$result = $query->get();
return $result;
// OUTPUT @input $stakeholderId = 1
//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss
.rights
from dms_stakeholder_permissions
where dms_stakeholder_permissions
.stakeholder_id
= 4 or (dms_stakeholder_permissions
.stakeholder_id
= 1 and dms_stakeholder_permissions
.rights
in (1, 2, 3))
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
for the first question
$key = 'Home';
echo $key." is at ".$page[$key];
There does not seem to be any answer which addresses the very common beginner problem of failing to install the required library in the first place.
On Debianish platforms, if libfoo
is missing, you can frequently install it with something like
apt-get install libfoo-dev
The -dev
version of the package is required for development work, even trivial development work such as compiling source code to link to the library.
The package name will sometimes require some decorations (libfoo0-dev
? foo-dev
without the lib
prefix? etc), or you can simply use your distro's package search to find out precisely which packages provide a particular file.
(If there is more than one, you will need to find out what their differences are. Picking the coolest or the most popular is a common shortcut, but not an acceptable procedure for any serious development work.)
For other architectures (most notably RPM) similar procedures apply, though the details will be different.
You mean something like this?
long key = -1L;
PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
Can do it without using ExcelWriter, using tools in openpyxl
This can make adding fonts to the new sheet much easier using openpyxl.styles
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
#Location of original excel sheet
fileLocation =r'C:\workspace\data.xlsx'
#Location of new file which can be the same as original file
writeLocation=r'C:\workspace\dataNew.xlsx'
data = {'Name':['Tom','Paul','Jeremy'],'Age':[32,43,34],'Salary':[20000,34000,32000]}
#The dataframe you want to add
df = pd.DataFrame(data)
#Load existing sheet as it is
book = load_workbook(fileLocation)
#create a new sheet
sheet = book.create_sheet("Sheet Name")
#Load dataframe into new sheet
for row in dataframe_to_rows(df, index=False, header=True):
sheet.append(row)
#Save the modified excel at desired location
book.save(writeLocation)
Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:
branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2
For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.
To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:
git co A
git co SHA-of-A2
git co -b AA
Then we created a branch BB from commit B3:
git co B
git co SHA-of-B3
git co -b BB
At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.
It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.
You have two typing errors in your code:
struct timeval,
should be
struct timeval
and after the printf()
parenthesis you need a semicolon.
Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.
Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec
and subtract "before" tv_usec
. You gain nothing by casting an integer number of seconds to a float.
I'd suggest checking out the man page for struct timeval
.
This is the code:
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char** argv) {
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 10000) {
i ++;
}
gettimeofday (&tvalAfter, NULL);
// Changed format to long int (%ld), changed time calculation
printf("Time in microseconds: %ld microseconds\n",
((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
+tvalAfter.tv_usec) - tvalBefore.tv_usec
); // Added semicolon
return 0;
}
Other approach for Vanilla JavaScript:
for(var o of document.querySelectorAll('#models > option')) {
o.remove()
}
As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.
However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:
Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).
Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.
Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
Because in the first one , you're trying to convert a collection to an ArrayList. In the 2nd one , you just use the built in constructor of ArrayList
It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)
This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.
In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.
Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
I had this problem (colons in the target name) because I had -n
in my GREP_OPTIONS
environment variable. Apparently, this caused configure
to generate the Makefile
incorrectly.
In SQL, the way to do this is to double the apostrophe:
'he doesn''t work for me'
If you are doing this programmatically, you should use an API that accepts parameters and escapes them for you, like prepared statements or similar, rather that escaping and using string concatenation to assemble a query.
Use:
sb.AppendLine();
sb.Append("\t");
for better portability. Environment.NewLine
may not necessarily be \n
; Windows uses \r\n
, for example.
In my case I was missing 'www.' from the url I was pushing. It must be exact match, if you're working on www.test.com
, you must push to www.test.com
and not test.com
I recently needed to do this and I came up with this
-- GROUP_CONCAT turns all the rows into 1
-- @q:= stores all the kill commands to a variable
select @q:=GROUP_CONCAT(CONCAT('KILL ',ID) SEPARATOR ';')
FROM information_schema.processlist
-- If you don't need it, you can remove the WHERE command altogether
WHERE user = 'user';
-- Creates statement and execute it
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
That way, you don't need to store to file and run all queries with a single command.
JQUERY FORMATCURRENCY PLUGIN
http://code.google.com/p/jquery-formatcurrency/
It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:
#include <iostream>
using namespace std;
int main()
{
int pause;
struct Customer
{
int uid;
string name;
};
Customer customerRecords[2];
customerRecords[0] = {25, "Bob Jones"};
customerRecords[1] = {26, "Jim Smith"};
cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
cin >> pause;
return 0;
}
things that speed up the inserts:
I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.
You could write a function that converts a scientific notation to regular, something like
def sc2std(x):
s = str(x)
if 'e' in s:
num,ex = s.split('e')
if '-' in num:
negprefix = '-'
else:
negprefix = ''
num = num.replace('-','')
if '.' in num:
dotlocation = num.index('.')
else:
dotlocation = len(num)
newdotlocation = dotlocation + int(ex)
num = num.replace('.','')
if (newdotlocation < 1):
return negprefix+'0.'+'0'*(-newdotlocation)+num
if (newdotlocation > len(num)):
return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
else:
return s
Similar to the above solutions I used @Input()
in a directive and able to pass multiple arrays of values in the directive.
selector: '[selectorHere]',
@Input() options: any = {};
Input.html
<input selectorHere [options]="selectorArray" />
Array from TS file
selectorArray= {
align: 'left',
prefix: '$',
thousands: ',',
decimal: '.',
precision: 2
};
I had the same error by in SQL Server Management Studio.
I found that to look at the more specific error, look at the log file created by the SQL Server. When I opened the log file, I found this error
Could not connect because the maximum number of ’2' user connections has already been reached. The system administrator can use sp_configure to increase the maximum value. The connection has been closed
I spend quite some time figuring this out. Finally running the following code fixed my problem.
sp_configure 'show advanced options', 1;
go
reconfigure
go
sp_configure 'user connections', 0
go
reconfigure
go
To view logs search for "logs" on windows startup button, click "view events logs". From there go to Applications under "Windows Logs". You can also choose "System" logs to see system wise errors. You can use filter on current logs by clicking "Filter Current Logs" on right side and then select "Error checkbox".
Minimal runnable example
glOrtho
: 2D games, objects close and far appear the same size:
glFrustrum
: more real-life like 3D, identical objects further away appear smaller:
main.c
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
static int ortho = 0;
static void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (ortho) {
} else {
/* This only rotates and translates the world around to look like the camera moved. */
gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
glColor3f(1.0f, 1.0f, 1.0f);
glutWireCube(2);
glFlush();
}
static void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (ortho) {
glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
} else {
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
}
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
if (argc > 1) {
ortho = 1;
}
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return EXIT_SUCCESS;
}
Compile:
gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut
Run with glOrtho
:
./main 1
Run with glFrustrum
:
./main
Tested on Ubuntu 18.10.
Schema
Ortho: camera is a plane, visible volume a rectangle:
Frustrum: camera is a point,visible volume a slice of a pyramid:
Parameters
We are always looking from +z to -z with +y upwards:
glOrtho(left, right, bottom, top, near, far)
left
: minimum x
we seeright
: maximum x
we seebottom
: minimum y
we seetop
: maximum y
we see-near
: minimum z
we see. Yes, this is -1
times near
. So a negative input means positive z
.-far
: maximum z
we see. Also negative.Schema:
How it works under the hood
In the end, OpenGL always "uses":
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
If we use neither glOrtho
nor glFrustrum
, that is what we get.
glOrtho
and glFrustrum
are just linear transformations (AKA matrix multiplication) such that:
glOrtho
: takes a given 3D rectangle into the default cubeglFrustrum
: takes a given pyramid section into the default cubeThis transformation is then applied to all vertexes. This is what I mean in 2D:
The final step after transformation is simple:
x
, y
and z
are in [-1, +1]
z
component and take only x
and y
, which now can be put into a 2D screenWith glOrtho
, z
is ignored, so you might as well always use 0
.
One reason you might want to use z != 0
is to make sprites hide the background with the depth buffer.
Deprecation
glOrtho
is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.
So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.
Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.
Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.
Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245
With an explicit GLfloat transform[]
it would look something like this:
glfw_transform.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec3 color;\n"
"out vec3 ourColor;\n"
"uniform mat4 transform;\n"
"void main() {\n"
" gl_Position = transform * vec4(position, 1.0f);\n"
" ourColor = color;\n"
"}\n";
static const GLchar* fragment_shader_source =
"#version 330 core\n"
"in vec3 ourColor;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(ourColor, 1.0f);\n"
"}\n";
static GLfloat vertices[] = {
/* Positions Colors */
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
const char *vertex_shader_source,
const char *fragment_shader_source
) {
GLchar *log = NULL;
GLint log_length, success;
GLuint fragment_shader, program, vertex_shader;
/* Vertex shader */
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
log = malloc(log_length);
if (log_length > 0) {
glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
printf("vertex shader log:\n\n%s\n", log);
}
if (!success) {
printf("vertex shader compile error\n");
exit(EXIT_FAILURE);
}
/* Fragment shader */
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
printf("fragment shader log:\n\n%s\n", log);
}
if (!success) {
printf("fragment shader compile error\n");
exit(EXIT_FAILURE);
}
/* Link shaders */
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetProgramInfoLog(program, log_length, NULL, log);
printf("shader link log:\n\n%s\n", log);
}
if (!success) {
printf("shader link error");
exit(EXIT_FAILURE);
}
/* Cleanup. */
free(log);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
int main(void) {
GLint shader_program;
GLint transform_location;
GLuint vbo;
GLuint vao;
GLFWwindow* window;
double time;
glfwInit();
window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, WIDTH, HEIGHT);
shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
/* Position attribute */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
/* Color attribute */
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader_program);
transform_location = glGetUniformLocation(shader_program, "transform");
/* THIS is just a dummy transform. */
GLfloat transform[] = {
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
time = glfwGetTime();
transform[0] = 2.0f * sin(time);
transform[5] = 2.0f * cos(time);
glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glfwTerminate();
return EXIT_SUCCESS;
}
Compile and run:
gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out
Output:
The matrix for glOrtho
is really simple, composed only of scaling and translation:
scalex, 0, 0, translatex,
0, scaley, 0, translatey,
0, 0, scalez, translatez,
0, 0, 0, 1
as mentioned in the OpenGL 2 docs.
The glFrustum
matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho
, more info at: https://gamedev.stackexchange.com/a/118848/25171
The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho
and frustum
operations.
It turns out that my understanding of the error message was wrong. I'd say it features very poor choice of words. Googling around shown me someone else misunderstood the message exactly like I did - see PHP bug #66763.
After totally unhelpful "This is the way the RMs wanted it to be." response to that bug by Mike, Tyrael explains that setting it to "-1" doesn't make just the warning to go away. It does the right thing, i.e. it completely disables populating the culprit variable. Turns out that having it set to 0 STILL populates data under some circumstances. Talk about bad design! To cite PHP RFC:
Change always_populate_raw_post_data INI setting to accept three values instead of two.
- -1: The behavior of master; don't ever populate $GLOBALS[HTTP_RAW_POST_DATA]
- 0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST)
- 1/on/yes/true: BC behavior (always populate $GLOBALS[HTTP_RAW_POST_DATA])
So yeah, setting it to -1 not only avoids the warning, like the message said, but it also finally disables populating this variable, which is what I wanted.
Here's my solution:
# /initializers/string.rb
class String
IntegerRegex = /^(\d)+$/
def integer?
!!self.match(IntegerRegex)
end
end
# any_model_or_controller.rb
'12345'.integer? # true
'asd34'.integer? # false
And here's how it works:
/^(\d)+$/
is regex expression for finding digits in any string. You can test your regex expressions and results at http://rubular.com/.IntegerRegex
to avoid unnecessary memory allocation everytime we use it in the method.integer?
is an interrogative method which should return true
or false
.match
is a method on string which matches the occurrences as per the given regex expression in argument and return the matched values or nil
.!!
converts the result of match
method into equivalent boolean.String
class is monkey patching, which doesn't change anything in existing String functionalities, but just adds another method named integer?
on any String object. My error was also related to not finding the required .so
file by a service.
I used LD_LIBRARY_PATH
variable to priorities the path picked up by the linker to search the required lib.
I copied both service and .so
file in a folder and fed it to LD_LIBRARY_PATH
variable as
LD_LIBRARY_PATH=. ./service
being in the same folder I have given the above command and it worked.
It's always worth grouping elements into sections that are relevant. In your case, a parent element that contains two columns;
HTML:
<div class='container2'>
<img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails' />
<div class="text">
<h4>Facebook</h4>
<p>
fine location, GPS, coarse location
<span>0 mins ago</span>
</p>
</div>
</div>
CSS:
* {
padding:0;
margin:0;
}
.iconDetails {
margin:0 2%;
float:left;
height:40px;
width:40px;
}
.container2 {
width:100%;
height:auto;
padding:1%;
}
.text {
float:left;
}
.text h4, .text p {
width:100%;
float:left;
font-size:0.6em;
}
.text p span {
color:#666;
}
Eliminating the arrows should be avoided. A solution that preserves the dropdown arrows is to first remove styles from the dropdown:
.myDropdown {
background-color: #yourbg;
border-style: none;
}
Then create div directly before the dropdown in your HTML:
<div class="myDiv"></div>
<select class="myDropdown...">...</select>
And style the div like this:
.myDiv {
background-color: #yourbg;
border-style: none;
position: absolute;
display: inline;
border: 1px solid #acolor;
}
Display inline will keep the div from going to a new line, position absolute removes it from the flow of the page. The end result is a nice clean underline you can style as you'd like, and your dropdown still behaves as the user would expect.
Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?
Solution 1
Run the app on a physical device instead of the emulator. I encountered this issue and my app didnt have a content provider defined.
Solution 2
In the other instance, i had an instrumented test app installed matching the same applicationId.
To fix the issue i had to run ./gradlew uA
- uA short for uninstallAll
task.
You can alternatively use the Gradle panel and choose navigate to app\install\uninstallAll task
If you using an emulator, you can wipe out the data
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
This would be slower, but will take care of the addition of space before and after the an Also, you'll have to change the value of position ( to 2, it's more intuitive now)
you can update all of the dependencies to their latest version by
npm update
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
Best solution from nginx: http://sysoev.ru/nginx/docs/http/ngx_http_ssi_module.html
Another option would be to use case_when
require(dplyr)
mutate(df, est = case_when(
b == 0 ~ (a - 5)/2.53,
TRUE ~ est
))
This solution becomes even more handy if more than 2 cases need to be distinguished, as it allows to avoid nested if_else
constructs.
Your Application.java
class should extend the SpringBootServletInitializer
class
ex:
public class Application extends SpringBootServletInitializer {}
There are several issues here.
DataContext="{Binding Employee}"
because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext>
syntax.{Binding Employee}
is invalid here, you just have to specify an object.<Window.DataContext> <local:Employee/> </Window.DataContext>
know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.
private void my_button_Click(object sender, RoutedEventArgs e)
{
Employee e = (Employee) DataContext;
}
A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.
public partial class MainWindow : Window
{
Employee employee = new Employee();
public MainWindow()
{
InitializeComponent();
DataContext = employee;
}
}
I put together something that does exactly what I was looking for and looks great. Using the scrollHeight of an element gets you the height of when it was loaded in the DOM.
var clickers = document.querySelectorAll('.clicker');_x000D_
clickers.forEach(clicker => {_x000D_
clicker.addEventListener('click', function (e) {_x000D_
var node = e.target.parentNode.childNodes[5];_x000D_
if (node.style.height == "0px" || node.style.height == "") {_x000D_
$(node).animate({ height: node.scrollHeight });_x000D_
}_x000D_
else {_x000D_
$(node).animate({ height: 0 });_x000D_
}_x000D_
});_x000D_
});
_x000D_
.answer{_x000D_
font-size:15px;_x000D_
color:blue;_x000D_
height:0px;_x000D_
overflow:hidden;_x000D_
_x000D_
}
_x000D_
<div class="row" style="padding-top:20px;">_x000D_
<div class="row" style="border-color:black;border-style:solid;border-radius:4px;border-width:4px;">_x000D_
<h1>This is an animation tester?</h1>_x000D_
<span class="clicker">click me</span>_x000D_
<p class="answer">_x000D_
I will be using this to display FAQ's on a website and figure you would like this. The javascript will allow this to work on all of the FAQ divs made by my razor code. the Scrollheight is the height of the answer element on the DOM load. Happy Coding :)_x000D_
Lorem ipsum dolor sit amet, mea an quis vidit autem. No mea vide inani efficiantur, mollis admodum accusata id has, eam dolore nemore eu. Mutat partiendo ea usu, pri duis vulputate eu. Vis mazim noluisse oportere id. Cum porro labore in, est accumsan euripidis scripserit ei. Albucius scaevola elaboraret usu eu. Ad sed vivendo persecuti, harum movet instructior eam ei._x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.
write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
cmd /c Pause | Out-Null
Read-Host -Prompt "Press Enter to continue"
This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.
Function Pause ($Message = "Press any key to continue . . . ") {
if ((Test-Path variable:psISE) -and $psISE) {
$Shell = New-Object -ComObject "WScript.Shell"
$Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
}
else {
Write-Host -NoNewline $Message
[void][System.Console]::ReadKey($true)
Write-Host
}
}
Using array_column to re-index will save time if you need to find multiple times:
$lookup = array_column($arr, NULL, 'id'); // re-index by 'id'
Then you can simply $lookup[$id]
at will.
For me, the mysql server was not running. So, i started the mysql server through
mysql.server start
then
mysql_secure_installation
to secure the server and now I can visit the MySQL server through
mysql -u root -p
or
sudo mysql -u root -p
depending on your installation.
Here's a one liner:
val => ['Bytes','Kb','Mb','Gb','Tb'][Math.floor(Math.log2(val)/10)]
Or even:
val => 'BKMGT'[~~(Math.log2(val)/10)]
My solution:
def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a
pass
Just a note to add on here: it's now 3 years later, yet this post is top in Google when you type in "How to search an S3 Bucket."
Perhaps you're looking for something more complex, but if you landed here trying to figure out how to simply find an object (file) by it's title, it's crazy simple:
open the bucket, select "none" on the right hand side, and start typing in the file name.
http://docs.aws.amazon.com/AmazonS3/latest/UG/ListingObjectsinaBucket.html
Like this:
int main()
{
int arr[2][5] =
{
{1,8,12,20,25},
{5,9,13,24,26}
};
}
This should be covered by your C++ textbook: which one are you using?
Anyway, better, consider using std::vector
or some ready-made matrix class e.g. from Boost.
Just use the location.host property
switch (location.host) {
case "xxx.local":
settings = ...
break;
case "xxx.dev.yyy.com":
settings = ...
break;
}
Since I've visited this page several times, I've decided to post an example (loose) comparison test.
Results:
"" -> false
"0" -> false
"1" -> true
"01" -> true
"abc" -> true
"true" -> true
"false" -> true
0 -> false
0.1 -> true
1 -> true
1.1 -> true
-42 -> true
"NAN" -> true
0 -> false
-> true
null -> false
true -> true
false -> false
[] -> false
["a"] -> true
{} -> true
{} -> true
{"s":"f"} -> true
Code:
class Vegetable {}
class Fruit {
public $s = "f";
}
$cases = [
"",
"0",
"1",
"01",
"abc",
"true",
"false",
0,
0.1,
1,
1.1,
-42,
"NAN",
(float) "NAN",
NAN,
null,
true,
false,
[],
["a"],
new stdClass(),
new Vegetable(),
new Fruit(),
];
echo "<pre>" . PHP_EOL;
foreach ($cases as $case) {
printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 9, " ", STR_PAD_RIGHT), json_encode( $case == true ));
}
When a strict (===
) comparison is done, everything except true
returns false
.
You can do it easily with regex:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
check what is using your GPU memory with
sudo fuser -v /dev/nvidia*
Your output will look something like this:
USER PID ACCESS COMMAND
/dev/nvidia0: root 1256 F...m Xorg
username 2057 F...m compiz
username 2759 F...m chrome
username 2777 F...m chrome
username 20450 F...m python
username 20699 F...m python
Then kill the PID that you no longer need on htop
or with
sudo kill -9 PID.
In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.
I had the exact same problem while trying to setup a Gitlab pipeline executed by a Docker runner installed on a Raspberry Pi 4
Using nload
to follow bandwidth usage within Docker runner container while pipeline was cloning the repo i saw the network usage dropped down to a few bytes per seconds..
After a some deeper investigations i figured out that the Raspberry temperature was too high and the network card start to dysfunction above 50° Celsius.
Adding a fan to my Raspberry solved the issue.
I've always done it with sed
var=`hg st -R "$path" | sed -e 's/ *$//'`
If there is a more elegant solution, I hope somebody posts it.
I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.
I have come up with a solution based on your comment for the output you are looking for:
Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces
var str = "<p> </p><div> </div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p> </p><div> </div>";_x000D_
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
You can use a headless firefox with an extension. It's pretty annoying to get running but it does produce good results.
Check out this answer for more info.
just add onclick handler for anchor tag
onclick="this.parentNode.style.display = 'none'"
or change onclick handler for img tag
onclick="this.parentNode.parentNode.style.display = 'none'"
Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.
Check for correct IP address in the cassandra.yaml file. Majority of times the error is due to incorrect IP address of your system also the username and password too.
After doing so initiate cqlsh by the command :-
cqlsh 10.31.79.1 -u cassandra -p cassandra
Both means "every item in a set of two things". The two things being "left" and "right"
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
Just put an override method named getItemId Get it by right click>generate>override methods>getItemId Put this method in the Adapter class
It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:
http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/
In that tutorial you have a complete example how to use the progressbar in a webview app.
Adrian.
If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:
import { Product } from '../models/product';
products: Array<Product>; // Initialize the array.
[...]
let i = 0;
this.service.products( i , (result) => {
if ( i == 0 ) {
// Create the first element of the array.
this.products = Array(result);
} else {
// Add to the array of maps.
this.products.push(result);
}
});
Where product.ts look like...
export class Product {
id: number;
[...]
}
This post will go through the following topics:
merge
has shortcomings here)Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge
calls:
df1.merge(df2, ...).merge(df3, ...)
However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.
Here I introduce pd.concat
for multi-way joins on unique keys, and DataFrame.join
for multi-way joins on non-unique keys. First, the setup.
# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C]
# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')
dfs2 = [A2, B2, C2]
If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat
. Note that pd.concat
joins DataFrames on the index.
# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')
valueA valueB valueC
key
D 2.240893 -0.977278 1.0
Omit join='inner'
for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join
, described below).
concat
is fast, but has its shortcomings. It cannot handle duplicates.
A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)
In this situation, we can use join
since it can handle non-unique keys (note that join
joins DataFrames on their index; it calls merge
under the hood and does a LEFT OUTER JOIN unless otherwise specified).
# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
[df.set_index('key') for df in (B, C)], how='inner').reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')
valueA valueB valueC
key
D 1.454274 -0.977278 1.0
D 0.761038 -0.977278 1.0
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
find . -name "*.ear" | xargs ls -sh
You can access the function itself using arguments.callee
[MDN]:
if (counter>0) {
arguments.callee(counter-1);
}
This will break in strict mode, however.
The following will round positive or negative numbers to a given decimal position:
sub round ()
{
my ($x, $pow10) = @_;
my $a = 10 ** $pow10;
return (int($x / $a + (($x < 0) ? -0.5 : 0.5)) * $a);
}
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
you should browse to where java installed, then go to bin directory which contains the java.exe file.
example - C:\Program Files\Java\jdk1.6.0_03\bin\java.exe
but you should run your SQL Developer as Administrator
There's one caveat if you're importing Swift code into your Objective-C files within the same framework. You have to do it with specifying the framework name and angle brackets:
#import <MyFramework/MyFramework-Swift.h>
MyFramework
here is the "Product Module Name" build setting (PRODUCT_NAME = MyFramework
).
Simply adding #import "MyFramework-Swift.h"
won't work. If you check the built products directory (before such an #import
is added, so you've had at least one successful build with some Swift code in the target), then you should still see the file MyFramework-Swift.h
in the Headers
directory.
All the above answers assumes the earth is a sphere. However, a more accurate approximation would be that of an oblate spheroid.
a= 6378.137#equitorial radius in km
b= 6356.752#polar radius in km
def Distance(lat1, lons1, lat2, lons2):
lat1=math.radians(lat1)
lons1=math.radians(lons1)
R1=(((((a**2)*math.cos(lat1))**2)+(((b**2)*math.sin(lat1))**2))/((a*math.cos(lat1))**2+(b*math.sin(lat1))**2))**0.5 #radius of earth at lat1
x1=R*math.cos(lat1)*math.cos(lons1)
y1=R*math.cos(lat1)*math.sin(lons1)
z1=R*math.sin(lat1)
lat2=math.radians(lat2)
lons2=math.radians(lons2)
R1=(((((a**2)*math.cos(lat2))**2)+(((b**2)*math.sin(lat2))**2))/((a*math.cos(lat2))**2+(b*math.sin(lat2))**2))**0.5 #radius of earth at lat2
x2=R*math.cos(lat2)*math.cos(lons2)
y2=R*math.cos(lat2)*math.sin(lons2)
z2=R*math.sin(lat2)
return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5
it depends where is your Data folder
To get the directory where the .exe file is:
AppDomain.CurrentDomain.BaseDirectory
To get the current directory:
Environment.CurrentDirectory
Then you can concatenate your directory path (@"\Data\Names.txt"
)
I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.
I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.
ORACLE_HOME needs to be at the top level of the Oracle directory structure for the database installation. From that point, Oracle knows how to find all the other files it needs. For example, the error message you get is because Oracle can't locate the message files to report errors with (should be in the various mesg directories below the oracle home. Instead of the above value you give, I would try
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0
I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
I got an error. But if I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
everything was OK.
A Maven SNAPSHOT is an artifact created by a Maven build and pretends to help developers in the software development cycle. A SNAPSHOT is an artifact (or project build result ) that is not pretended to be used anywhere, it's only a temporarily .jar, ear, ... created to test the build process or to test new requirements that are not yet ready to go to a production environment. After you are happy with the SNAPSHOT artifact quality, you can create a RELEASE artifact that can be used by other projects or can be deployed itself.
In your project, you can define a SNAPSHOT using the version element in the pom.xml file of Maven:
<groupId>example.project.maven</groupId>
<artifactId>MavenEclipseExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Maven pom example</description>
If you want to understand better Maven you can look into these articles too:
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
Don't forget. if you are trying to hover around an image, you have to put it around a container. css:
.brand:hover + .brand-sales {
display: block;
}
.brand-sales {
display: none;
}
If you hover on this:
<span className="brand">
<img src="https://murmure.me/wp-content/uploads/2017/10/nike-square-1900x1900.jpg"
alt"some image class="product-card-place-logo"/>
</span>
This will show:
<div class="product-card-sales-container brand-sales">
<div class="product-card-">Message from the business goes here. They can talk alot or not</div>
</div>
This may be possible by using the refs attribute.
In the example of wanting to to reach a <div>
what you would want to do is use is <div ref="myExample">
. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample)
.
From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children
(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.
Here's the official react documentation on refs for more info.
Visual studio command prompt is nothing but the regular command prompt where few environment variables are set by default. This variables are set in the batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat . So basically to get a visual studio command prompt for a particular version, just open regular command prompt and run this batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat (Change the visual studio version based on your installed version). Voila you have got the visual studio command prompt. You can write a script to run the batch file and open cmd.exe.
From Python 2.5 onwards, you can use
from ..Modules import LDAPManager
The leading period takes you "up" a level in your heirarchy.
See the Python docs on intra-package references for imports.
I found a library called ObjectPrinter which allows to easily dump objects and collections to strings (and more). It does exactly what I needed.
I'd wonder why someone would try to "override" the container width, since its purpose is to keep its content with some padding, but I had a similar situation (that's why I wanted to share my solution, even though there're answers).
In my situation, I wanted to have all content (of all pages) rendered inside a container, so this was the piece of code from my _Layout.cshtml:
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
<div class="container">
@RenderBody()
</div>
</section>
</div>
In my Home Index page, I had a background header image I'd like to fill the whole screen width, so the solution was to make the Index.cshtml like this:
@section featured {
<!-- This content will be rendered outside the "container div" -->
<div class="intro-header">
<div class="container">SOME CONTENT WITH A NICE BACKGROUND</div>
</div>
}
<!-- The content below will be rendered INSIDE the "container div" -->
<div class="content-section-b">
<div class="container">
<div class="row">
MORE CONTENT
</div>
</div>
</div>
I think this is better than trying to make workarounds, since sections are made with the purpose of allowing (or forcing) views to dynamically replace some content in the layout.
You can't use shorthand notation to set configuration values outside of PHP.ini. I assume it's falling back to 2MB as the compiled default when confronted with a bad value.
On the other hand, I don't think upload_max_filesize
could be set using ini_set()
. The "official" list states that it is PHP_INI_PERDIR
.
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
For others like me who had a different but similar issue where the animation was not occurring at all:
From what I could find it may be something in my browser setting which preferred less motion for accessibility purposes. I could not find any setting in my browser, but I was able to get the animation working by downloading a local copy of bootstrap and commenting out this section of the CSS file:
@media (prefers-reduced-motion: reduce) {
.collapsing {
-webkit-transition: none;
transition: none;
}
}
In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)
In order to see the changes that have been staged already, you can pass the -–staged
option to git diff
(in pre-1.6 versions of Git, use –-cached
).
git diff --staged
git diff --cached
A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method. probably not the most efficient, but easy to understand and use.
Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String
' reset the stream or we'll get an empty string returned
' remember the position so we can restore it later
Dim Pos = memStream.Position
memStream.Position = startPos
Dim reader As New StreamReader(memStream)
Dim str = reader.ReadToEnd()
' reset the position so that subsequent writes are correct
memStream.Position = Pos
Return str
End Function
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.
function myFunction() {_x000D_
var selchbox = [];_x000D_
var inputfields = document.getElementsByName("myCheck");_x000D_
var ar_inputflds = inputfields.length;_x000D_
_x000D_
for (var i = 0; i < ar_inputflds; i++) {_x000D_
if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
selchbox.push(inputfields[i].value);_x000D_
}_x000D_
return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
var selchb = myFunction();_x000D_
console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
Use jQuery.attr()
in your click handler:
$("#myform").attr('action', 'page1.php');
I just put the test in the class itself by making it an inner class: https://rogerkeays.com/how-to-unit-test-private-methods
For Windows I found this working:
Set http = CreateObject("Microsoft.XmlHttp")
http.open "GET", "http://www.mywebservice.com/webmethod.asmx?WSDL", FALSE
http.send ""
WScript.Echo http.responseText
Reference: CodeProject
The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.
Here is an example:
public static void testCode(){
List[] b = new List[1];
test(b);
}
@SafeVarargs
public static void test(List<A>... a){
}
As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.
The simple solution
SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field
You can use:
npx <command>
npx
looks for command in .bin
directory of your node_modules
Store the following in a file called npm-exec.bat
and add it to your %PATH%
@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*
Then you can use it like
npm-exec <command> <arg0> <arg1> ...
For example
To execute wdio
installed in local node_modules directory, do:
npm-exec wdio wdio.conf.js
i.e. it will run .\node_modules\.bin\wdio wdio.conf.js
Another approach would be to deserialize into a java.util.Map
, and then just modify the Java Map
as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
Since I have encoding ISO-8859-1 operating system the date format "dd.MM.yyyy HH:mm:sss" was not recognised what did work was to use InvariantCulture string.
string url = "GetData?DagsPr=" + DagsProfs.ToString(CultureInfo.InvariantCulture)
This can be achieved using HTML.
<a href="myfile.pdf">Download Brochure</a>
Add download attribute to it: Here the file name will be myfile.pdf
<a href="myfile.pdf" download>Download Brochure</a>
Specify a value for the download attribute:
<a href="myfile.pdf" download="Brochure">Download Brochure</a>
Here the file name will be Brochure.pdf
all: program
program.o: program.h headers.h
is enough. the rest is implicit
it might help you..
Button download_image = (Button)bigimagedialog.findViewById(R.id.btn_downloadimage);
download_image.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
boolean success = (new File("/sdcard/dirname")).mkdir();
if (!success)
{
Log.w("directory not created", "directory not created");
}
try
{
URL url = new URL("YOUR_URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
String data1 = String.valueOf(String.format("/sdcard/dirname/%d.jpg",System.currentTimeMillis()));
FileOutputStream stream = new FileOutputStream(data1);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
Toast.makeText(getApplicationContext(), "Downloading Completed", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotation Test</title>
<link type="text/css" href="css/style.css" rel="stylesheet"></style>
<script src="js/jquery-1.5.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#mode").text("LANDSCAPE");
} else {
// Portrait
$("#mode").text("PORTRAIT");
}
}, false);
</script>
</head>
<body onorientationchange="updateOrientation();">
<div id="mode">LANDSCAPE</div>
</body>
</html>
just install npm install -g @angular/cli@latest
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
Are your sure this is a css issue ? There are some posts on google around this issue: http://productforums.google.com/forum/#!category-topic/chrome/discuss-chrome/eMlLBcKqd2s
It may be related to the print process. On safari, which is webkit also, there is a checkbox to print background images and colors in the printer dialog.
In the config file there is a colon instead of an equal sign after the sonar.web.host.
Is:
sonar.web.host:sonarqube
Should be
sonar.web.host=sonarqube
Try something like:-
ALTER TABLE table_name ADD CONSTRAINT [DF_table_name_Created]
DEFAULT (getdate()) FOR [created_at];
replacing table_name
with the name of your table.
You can create your own JSONObject
then toString()
.
Remember run it in the background thread like doInBackground
in AsyncTask
.
OkHttp version > 4:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.
select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
natural join (select distinct LastName from
ValTbl v where a.LastName = v.LastName)
try that.
Visual Studio Community 2015 is free. But I got the 30 day trial expired message. After some googling figured out that I have to sign in with a Microsoft account. So I signed up with my Hotmail account and after that I was able to continue using the VS community 2015.
Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
Form2:
public partial class Form2 : Form
{
Form opener;
public Form2(Form parentForm)
{
InitializeComponent();
opener = parentForm;
}
private void button1_Click(object sender, EventArgs e)
{
opener.Close();
this.Close();
}
}
If you don't need multi-column, chosen is another good choice. MIT Licensed
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.
Try mydatagrid.Items.Refresh()
Very good answer from DevWL about using the native HTML5 template element.
To contribute to this good question from the OP I would like to add on how to use this template
element using jQuery, for example:
$($('template').html()).insertAfter( $('#somewhere_else') );
The content of the template
is not html, but just treated as data, so you need to wrap the content into a jQuery object to then access jQuery's methods.
Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.
With iOS 7+, static Launch Images are now deprecated.
You should create a custom view that composes slices of images, which sizes to all screens like a normal UIViewController view.
Its a good to remember that config files can be split across secondary files to make config changes easier on different servers (dev/demo/production etc), without having to recompile code/app etc. For example we use them to allow onsite engineers to make endpoint changes without actually touching the 'real' files.
First step is to move the bindings section out of the WPF App.Config into it's own separate file.
The behaviours section is set to allow both http and https (doesn't seem to have an affect on the app if both are allowed)
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
And we move the bindings section out to its own file;
<bindings configSource="Bindings.config" />
In the bindings.config file we switch the security based on protocol
<!-- None = http:// -->
<!-- Transport = https:// -->
<security mode="None" >
Now the on site engineers only need to change the Bindings.Config file and the Client.Config where we store the actual URL for each endpoint.
This way we can change the endpoint from http to https and back again to test the app without having to change any code.
Hope this helps.
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.
A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
Summary:
First you enable attribute routing
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Then you can use attributes to define parameters and optionally data types
public class BooksController : Controller
{
// eg: /books
// eg: /books/1430210079
[Route("books/{isbn?}")]
public ActionResult View(string isbn)
<a href="home.php?click=1" class="btn">Click me</a>
<?php
if($_GET['click']){
doSomething();
}
?>
But is better to use JS and with ajax to call function!
Both will have a key of 0
, and that method of combining the arrays will collapse duplicates. Try using array_merge()
instead.
$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')
// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);
If the elements in your array used different keys, the +
operator would be more appropriate.
$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');
// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;
Edit: Added a code snippet to clarify
Easiest way to do this is close the project. Using file explorer head to the location of that project and delete.
Alot of processes, even simply deleting can be annoying to figure out in studio. Most deleting options a good work around is to delete using file explorer. This is a part of the process tht works for deleting modules as well. Which u will prob find is painful as well
I'd recommend using a class instead of setting css properties. So instead of this:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
Define a css class:
.border
{
border-color: #C1E0FF;
border-width:1px;
border-style:solid;
}
And then change your javascript to:
$(this).addClass("border");
This works nicely
def running():
n=0# number of instances of the program running
prog=[line.split() for line in subprocess.check_output("tasklist").splitlines()]
[prog.pop(e) for e in [0,1,2]] #useless
for task in prog:
if task[0]=="itunes.exe":
n=n+1
if n>0:
return True
else:
return False