I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo
if you are not running as root):
a2enmod ssl
then restart Apache:
/etc/init.d/apache2 restart
More details of SSL in Apache for Ubuntu / Debian here.
Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in ExcelWriter
gives a clue that something like this might work out:
import pandas
from openpyxl import load_workbook
book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
writer.save()
In the above XML, set the android:layout_weight
of the linear layout as 2
:
android:layout_weight="2"
If you're on a Mac, here's how to fix it. This is after tons of trial and error. Hope this helps others..
Debugging:
$mysql --verbose --help | grep my.cnf
$ which mysql
/usr/local/bin/mysql
Resolution: nano /usr/local/etc/my.cnf
Add: default-authentication-plugin=mysql_native_password
-------
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
default-authentication-plugin=mysql_native_password
------
Finally Run: brew services restart mysql
What about r:Base? Way back in the day r:Base was a very robust DOS (then Windows) RDMBS and this is pre-Access / pre-Paradox days. Its closest competitor was dBase but that wasnt fully relational, at the time. I developed some very nice r:Base applications AND, like Access today, had a built in report generator, forms facility, queries and table manipulation.. To my surprise, its still alive! http://www.rbase.com/ Its got all that access offers, it seems. Might be something for you to consider.
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
From git checkout
's usage:
-2, --ours checkout our version for unmerged files
-3, --theirs checkout their version for unmerged files
-m, --merge perform a 3-way merge with the new branch
When resolving merge conflicts, you can do git checkout --theirs some_file
, and git checkout --ours some_file
to reset the file to the current version and the incoming versions respectively.
If you've done git checkout --ours some_file
or git checkout --theirs some_file
and would like to reset the file to the 3-way merge version of the file, you can do git checkout --merge some_file
.
Native DOM elements that are inputs also have a form
attribute that points to the form they belong to:
var form = element.form;
alert($(form).attr('name'));
According to w3schools, the .form
property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.
If this were a different type of element (not an <input>
), you could find the closest parent with closest
:
var $form = $(element).closest('form');
alert($form.attr('name'));
Also, see this MDN link on the form
property of HTMLInputElement
:
No, you can't. InputStream
is designed to work with remote resources, so you can't know if it's there until you actually read from it.
You may be able to use a java.io.PushbackInputStream
, however, which allows you to read from the stream to see if there's something there, and then "push it back" up the stream (that's not how it really works, but that's the way it behaves to client code).
Most examples are with one line of "html" that is rendered conditionally. This seems readable for me when I have multiple lines that needs to be rendered conditionally.
render: function() {
// This will be renered only if showContent prop is true
var content =
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>;
return (
<div>
<h1>Some title</h1>
{this.props.showContent ? content : null}
</div>
);
}
First example is good because instead of null
we can conditionally render some other content like {this.props.showContent ? content : otherContent}
But if you just need to show/hide content this is even better since Booleans, Null, and Undefined Are Ignored
render: function() {
return (
<div>
<h1>Some title</h1>
// This will be renered only if showContent prop is true
{this.props.showContent &&
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>
}
</div>
);
}
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
Inline tag is used to add another src of document to the current html element.
In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link
so add ?html=5 to the end of the link.. :)
You can use a little package called Mongoose Paginate that makes it easier.
$ npm install mongoose-paginate
After in your routes or controller, just add :
/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/
MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
if (error) {
console.error(error);
} else {
console.log('Pages:', pageCount);
console.log(paginatedResults);
}
}
I am trying the same thing. I have a RPG battle system in which my Death(self) function has to kill the own object of the Fighter class. But it appeared it`s not possible. Maybe my class Game in which I collect all participants in the combat should delete units form the "fictional" map???
def Death(self):
if self.stats["HP"] <= 0:
print("%s wounds were too much... Dead!"%(self.player["Name"]))
del self
else:
return True
def Damage(self, enemy):
todamage = self.stats["ATK"] + randint(1,6)
todamage -= enemy.stats["DEF"]
if todamage >=0:
enemy.stats["HP"] -= todamage
print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage))
enemy.Death()
return True
else:
print("Ineffective...")
return True
def Attack(self, enemy):
tohit = self.stats["DEX"] + randint(1,6)
if tohit > enemy.stats["EVA"]:
print("You landed a successful attack on %s "%(enemy.player["Name"]))
self.Damage(enemy)
return True
else:
print("Miss!")
return True
def Action(self, enemylist):
for i in range(0, len(enemylist)):
print("No.%d, %r"%(i, enemylist[i]))
print("It`s your turn, %s. Take action!"%(self.player["Name"]))
choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>")
if choice == 'a'or choice == 'A':
who = int(input("Who? "))
self.Attack(enemylist[who])
return True
else:
return self.Action()
This could be used for getting colors from computed style propeties:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
You can use CSS white-space Property
to achieve this.
white-space: nowrap
You can try this one
img{
max-height:500px;
max-width:500px;
height:auto;
width:auto;
}
This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px
You can check this post
Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw
for width: 100%
to get rid of the horizontal scrollbar.
For me, once there was a mistake in spelling of function
For e.g. instead of
$(document).ready(function(){
});
I wrote
$(document).ready(funciton(){
});
So keep that also in check
`n
is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n
(carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:
(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath
I suppose you could look at this link if I understood your question correctly http://www.javacodegeeks.com/2012/07/ultimate-jpa-queries-and-tips-list-part_09.html
For example they created a query like:
select id, name, age, a.id as ADDRESS_ID, houseNumber, streetName ' +
20' from person p join address a on a.id = p.address_id where p.id = 1'
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
If you are using terminal you will want to add the following to ./bash_profile
export PATH="/usr/local/mysql/bin:$PATH"
If you are using zsh, you will want to add the above line to your ~/.zshrc
If your on jQuery 1.3+ then use .live()
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
Example code (without exception-handling):
XMLGregorianCalendar xgc =
DatatypeFactory // Data-type converter.
.newInstance() // Instantiate a converter object.
.newXMLGregorianCalendar( // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
GregorianCalendar.from( // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
LocalDate // Modern class for representing a date-only, without time-of-day and without time zone.
.parse( "2014-01-07" ) // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern.
.atStartOfDay( ZoneOffset.UTC ) // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
) // Returns a `GregorianCalendar` object.
) // Returns a `XMLGregorianCalendar` object.
;
XMLGregorianCalendar
classAvoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar
, GregorianCalendar
, Calendar
, and Date
. Use only modern java.time classes.
When presented with a string such as "2014-01-07"
, parse as a LocalDate
.
LocalDate.parse( "2014-01-07" )
To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.
LocalDate.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
This returns a ZonedDateTime
object.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
;
zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]
But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC
constant as our ZoneId
argument.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneOffset.UTC )
;
zdt.toString() = 2014-01-07T00:00Z
The Z
on the end means UTC (an offset of zero), and is pronounced “Zulu”.
If you must work with legacy classes, convert to GregorianCalendar
, a subclass of Calendar
.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;
gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Apparently, you really need an object of the legacy class XMLGregorianCalendar
. If the calling code cannot be updated to use java.time, convert.
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc )
;
Actually, that code requires a try-catch.
try
{
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
xgc = 2014-01-07T00:00:00.000Z
Putting that all together, with appropriate exception-handling.
// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC.
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
Objects.requireNonNull( input );
if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
XMLGregorianCalendar xgc = null;
ZonedDateTime zdt = null;
try
{
zdt =
LocalDate
.parse( input )
.atStartOfDay( ZoneOffset.UTC );
}
catch ( DateTimeParseException e )
{
throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
}
GregorianCalendar gc = GregorianCalendar.from( zdt );
try
{
xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
Objects.requireNonNull( xgc );
return xgc ;
}
Usage.
String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );
Dump to console.
System.out.println( "xgc = " + xgc );
xgc = 2014-01-07T00:00:00.000Z
Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.
So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.
The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.
Your input string "2014-01-07"
is in standard ISO 8601 format.
The T
in the middle separates date portion from time portion.
The Z
on the end is short for Zulu and means UTC.
Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2014-01-07" ) ;
ld.toString(): 2014-01-07
ZonedDateTime
If you want to see the first moment of that day, specify a ZoneId
time zone to get a moment on the timeline, a ZonedDateTime
. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2014-01-07T00:00:00Z
For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
and then replace the T
in the middle with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2014-01-07 00:00:00
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Using Eclipse IDE:-
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
Try this,
HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");
I'm assuming you are talking about the event bubbling aspect of it. It would be helpful to see your HTML for the said span
elements as well. I can't see why you'd want to change the core behavior like this, I don't find it at all annoying. I suggest going with your second block of code:
$('span').click(function (){
doStuff2();
doStuff1();
});
Most importantly I think you'll find it more organized if you manage all the events for a given element in the same block like you've illustrated. Can you explain why you find this annoying?
x.each_with_index { |v, i| puts "current index...#{i}" }
You can use following class as service class to run your application in background
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private GPSTracker gpsTracker;
private Handler handler= new Handler();
private Timer timer = new Timer();
private Distance pastDistance = new Distance();
private Distance currentDistance = new Distance();
public static double DISTANCE;
boolean flag = true ;
private double totalDistance ;
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
if(flag){
pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = false;
}else{
currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = comapre_LatitudeLongitude();
}
Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
}
});
}
};
timer.schedule(timerTask,0, 5000);
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--------------------------------onDestroy -stop service ");
timer.cancel();
DISTANCE = totalDistance ;
}
public boolean comapre_LatitudeLongitude(){
if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
return false;
}else{
final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
System.out.println("Distance in mile :"+distance);
handler.post(new Runnable() {
@Override
public void run() {
float kilometer=1.609344f;
totalDistance = totalDistance + distance * kilometer;
DISTANCE = totalDistance;
//Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
}
});
return true;
}
}
}
Add One another class to get location
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
private Location m_Location;
public GPSTracker(Context context) {
this.mContext = context;
m_Location = getLocation();
System.out.println("location Latitude:"+m_Location.getLatitude());
System.out.println("location Longitude:"+m_Location.getLongitude());
System.out.println("getLocation():"+getLocation());
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
// --------------Distance.java
public class Distance {
private double latitude ;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
Is you want a plus (+) symbol in the body you have to encode it as 2B.
For example: Try this
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
You can use method getDate():
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)
https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search
Either use an Allias in the table like T and use T.ID, or use just the column name.
declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table
SELECT * FROM @TEMP
WHERE ID = 1
I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.
Function DoStuff(){
param(
[Parameter(Mandatory=$true)][string]$computername,
[Parameter(Mandatory=$false)][string]$arg2,
[Parameter(Mandatory=$false)][string]$domain
)
if(!($domain)){
$domain = 'domain1'
}
write-host $domain
if($arg2){
write-host "arg2 present... executing script block"
}
else{
write-host "arg2 missing... exiting or whatever"
}
}
With version 3 of PowerShell you can chain the replace calls together:
(Get-Content $sourceFile) | ForEach-Object {
$_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
} | Set-Content $destinationFile
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
It's usually describes as for optional add-on software packages
source, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local
.
I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.
I saved the login page as index.html
, edited all the href=
and action=
fields to have the full URL to the Agile server.
The key <form>
line needed to change from
<form autocomplete="off" name="MainForm" method="POST"
action="j_security_check"
onsubmit="return false;" target="_top">
to
<form autocomplete="off" name="MainForm" method="POST"
action="http://my.company.com:7001/Agile/default/j_security_check"
onsubmit="return false;" target="_top">
I also added this snippet to the end of the <body>
<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script>
I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm()
call was inspired by inspecting the keyPressEvent()
function.
If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:
public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
}
When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.
Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:
public void IncreaseCapacity(int increment)
{
var itemsList = (List<T>)Items;
var total = itemsList.Count + increment;
if (itemsList.Capacity < total)
{
itemsList.Capacity = total;
}
}
Use six
:
from six.moves.urllib.parse import quote
six
will simplify compatibility problems between Python 2 and Python 3, such as different import paths.
You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.
(It's the same as when you say int n = 10;
: There are no dynamic resources involved that you have to manage manually.)
Nano is 10-9 and milli 10-3. Hence, we can use the three first characters of nanoseconds to get the milliseconds:
date +%s%3N
From man date
:
%N nanoseconds (000000000..999999999)
%s seconds since 1970-01-01 00:00:00 UTC
Source: Server Fault's How do I get the current Unix time in milliseconds in Bash?.
My solution to hiding a DB-Password in Spring Boot App's application.properties does implemented here.
Scenario: some fake password already reading and saved from application.properties on start, in global Spring object ConfigurableEnvironment will be, in Run-Time replaced programmaticaly, by real DB-Password. The real password will be reading from another config file, saved in safe, project-outer place.
Don't forget: call the the Bean from main class with:
@Autowired
private SchedUtilility utl;
first import os module in your app than with use from getpid function get pid's app and save in a file.for example :
import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()
and create a bash file in /etc/init.d path: /etc/init.d/servername
PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in
start)
echo "starting"
$(python $PATHAPP)
;;
stop)
echo "stoping"
PID=$(cat $PIDAPP)
kill $PID
;;
esac
now , u can start and stop ur app with down command:
service servername stop service servername start
or
/etc/init.d/servername stop /etc/init.d/servername start
You can through option
Try this with some modifications
<div trbidi="on">
<script type="text/javascript">
function MostrarVideo(idYouTube)
{
var contenedor = document.getElementById('divInnerVideo');
if(idYouTube == '')
{contenedor.innerHTML = '';
} else{
var url = idYouTube;
contenedor.innerHTML = '<iframe width="560" height="315" src="https://www.youtube.com/embed/'+ url +'" frameborder="0" allowfullscreen></iframe>';
}
}
</script>
<select onchange="MostrarVideo(this.value);">
<option selected disabled>please selected </option>
<option value="qycqF1CWcXg">test1</option>
<option value="hniPHaBgvWk">test2</option>
<option value="bOQA33VNo7w">test3</option>
</select>
<div id="divInnerVideo">
</div>
If you want to put a default page placed inside id="divInnerVideo"
example:
<div id="divInnerVideo">
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/pES8SezkV8w?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
The problem is that PhpMyAdmin control user (usually: pma) password does not match the mysql user: pma (same user) password.
To fix it, 1. Set the password you want for user pma here:
"C:\xampp\phpMyAdmin\config.inc.php"
$cfg['Servers'][$i]['controlpass'] = 'your_new_phpmyadmin_pass';
(should be like on line 32)
Then go to mysql, login as root, go to: (I used phpmyadmin to go here)
Database: mysql »Table: user
Edit the user: pma
Select "Password" from the function list (left column) and set "your_new_phpmyadmin_pass" on the right column and hit go.
Restart mysql server.
Now the message should disappear.
I have seen this once. Are the users requesting different amounts of data? I found that even if you can configure a binding for data payloads (i.e. maxReceivedMessageSize
), the httpRuntime
maxRequestLength
trumps the WCF setting, so if IIS is trying to serve a request that exceeds that, it exhibits this behavior.
Think of it like this:
If maxReceivedMessageSize
is 12MB in your WCF behavior, and maxRequestLength
is 4MB (default), IIS wins.
VBA VERSION:
Note: Remember that if your polygon is an area within a map that Latitude/Longitude are Y/X values as opposed to X/Y (Latitude = Y, Longitude = X) due to from what I understand are historical implications from way back when Longitude was not a measurement.
CLASS MODULE: CPoint
Private pXValue As Double
Private pYValue As Double
'''''X Value Property'''''
Public Property Get X() As Double
X = pXValue
End Property
Public Property Let X(Value As Double)
pXValue = Value
End Property
'''''Y Value Property'''''
Public Property Get Y() As Double
Y = pYValue
End Property
Public Property Let Y(Value As Double)
pYValue = Value
End Property
MODULE:
Public Function isPointInPolygon(p As CPoint, polygon() As CPoint) As Boolean
Dim i As Integer
Dim j As Integer
Dim q As Object
Dim minX As Double
Dim maxX As Double
Dim minY As Double
Dim maxY As Double
minX = polygon(0).X
maxX = polygon(0).X
minY = polygon(0).Y
maxY = polygon(0).Y
For i = 1 To UBound(polygon)
Set q = polygon(i)
minX = vbMin(q.X, minX)
maxX = vbMax(q.X, maxX)
minY = vbMin(q.Y, minY)
maxY = vbMax(q.Y, maxY)
Next i
If p.X < minX Or p.X > maxX Or p.Y < minY Or p.Y > maxY Then
isPointInPolygon = False
Exit Function
End If
' SOURCE: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
isPointInPolygon = False
i = 0
j = UBound(polygon)
Do While i < UBound(polygon) + 1
If (polygon(i).Y > p.Y) Then
If (polygon(j).Y < p.Y) Then
If p.X < (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then
isPointInPolygon = True
Exit Function
End If
End If
ElseIf (polygon(i).Y < p.Y) Then
If (polygon(j).Y > p.Y) Then
If p.X < (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then
isPointInPolygon = True
Exit Function
End If
End If
End If
j = i
i = i + 1
Loop
End Function
Function vbMax(n1, n2) As Double
vbMax = IIf(n1 > n2, n1, n2)
End Function
Function vbMin(n1, n2) As Double
vbMin = IIf(n1 > n2, n2, n1)
End Function
Sub TestPointInPolygon()
Dim i As Integer
Dim InPolygon As Boolean
' MARKER Object
Dim p As CPoint
Set p = New CPoint
p.X = <ENTER X VALUE HERE>
p.Y = <ENTER Y VALUE HERE>
' POLYGON OBJECT
Dim polygon() As CPoint
ReDim polygon(<ENTER VALUE HERE>) 'Amount of vertices in polygon - 1
For i = 0 To <ENTER VALUE HERE> 'Same value as above
Set polygon(i) = New CPoint
polygon(i).X = <ASSIGN X VALUE HERE> 'Source a list of values that can be looped through
polgyon(i).Y = <ASSIGN Y VALUE HERE> 'Source a list of values that can be looped through
Next i
InPolygon = isPointInPolygon(p, polygon)
MsgBox InPolygon
End Sub
With java 8:
Arrays.stream(MyEnum.values()).map(Enum::name)
.collect(Collectors.toList()).toArray();
Since this question was closed, I'm posting here for how you do it using SQLAlchemy. Via recursion, it retries a bulk insert or update to combat race conditions and validation errors.
First the imports
import itertools as it
from functools import partial
from operator import itemgetter
from sqlalchemy.exc import IntegrityError
from app import session
from models import Posts
Now a couple helper functions
def chunk(content, chunksize=None):
"""Groups data into chunks each with (at most) `chunksize` items.
https://stackoverflow.com/a/22919323/408556
"""
if chunksize:
i = iter(content)
generator = (list(it.islice(i, chunksize)) for _ in it.count())
else:
generator = iter([content])
return it.takewhile(bool, generator)
def gen_resources(records):
"""Yields a dictionary if the record's id already exists, a row object
otherwise.
"""
ids = {item[0] for item in session.query(Posts.id)}
for record in records:
is_row = hasattr(record, 'to_dict')
if is_row and record.id in ids:
# It's a row but the id already exists, so we need to convert it
# to a dict that updates the existing record. Since it is duplicate,
# also yield True
yield record.to_dict(), True
elif is_row:
# It's a row and the id doesn't exist, so no conversion needed.
# Since it's not a duplicate, also yield False
yield record, False
elif record['id'] in ids:
# It's a dict and the id already exists, so no conversion needed.
# Since it is duplicate, also yield True
yield record, True
else:
# It's a dict and the id doesn't exist, so we need to convert it.
# Since it's not a duplicate, also yield False
yield Posts(**record), False
And finally the upsert function
def upsert(data, chunksize=None):
for records in chunk(data, chunksize):
resources = gen_resources(records)
sorted_resources = sorted(resources, key=itemgetter(1))
for dupe, group in it.groupby(sorted_resources, itemgetter(1)):
items = [g[0] for g in group]
if dupe:
_upsert = partial(session.bulk_update_mappings, Posts)
else:
_upsert = session.add_all
try:
_upsert(items)
session.commit()
except IntegrityError:
# A record was added or deleted after we checked, so retry
#
# modify accordingly by adding additional exceptions, e.g.,
# except (IntegrityError, ValidationError, ValueError)
db.session.rollback()
upsert(items)
except Exception as e:
# Some other error occurred so reduce chunksize to isolate the
# offending row(s)
db.session.rollback()
num_items = len(items)
if num_items > 1:
upsert(items, num_items // 2)
else:
print('Error adding record {}'.format(items[0]))
Here's how you use it
>>> data = [
... {'id': 1, 'text': 'updated post1'},
... {'id': 5, 'text': 'updated post5'},
... {'id': 1000, 'text': 'new post1000'}]
...
>>> upsert(data)
The advantage this has over bulk_save_objects
is that it can handle relationships, error checking, etc on insert (unlike bulk operations).
Check your array index to see if it's accessed out of bound.
Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.
JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.
See the article 50 Useful Design Tools For Beautiful Web Typography for alternative methods.
I have only used Cufon. I have found it reliable and very easy to use, so I've stuck with it.
I've used the following script with great success on numerous servers:
pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid
while [ -e /proc/$pid ]; do sleep 0.1; done
notes:
$INSTALLATION
contains enough of the process path that's it's totally unambiguousThis script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.
create table abc(emp_ID int, manager varchar(20) , manager_id int)
emp_ID manager manager_id
1 abc NULL
2 def 1
3 ghi 2
4 klm 3
5 def1 1
6 ghi1 2
7 klm1 3
select a.emp_ID , a.manager emp_name,b.manager manager_name
from abc a
left join abc b
on a.manager_id = b.emp_ID
Result:
emp_ID emp_name manager_name
1 abc NULL
2 def abc
3 ghi def
4 klm ghi
5 def1 abc
6 ghi1 def
7 klm1 ghi
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
I tried this with python3 and it worked, source
def output_reader(proc):
for line in iter(proc.stdout.readline, b''):
print('got line: {0}'.format(line.decode('utf-8')), end='')
def main():
proc = subprocess.Popen(['python', 'fake_utility.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
t = threading.Thread(target=output_reader, args=(proc,))
t.start()
try:
time.sleep(0.2)
import time
i = 0
while True:
print (hex(i)*512)
i += 1
time.sleep(0.5)
finally:
proc.terminate()
try:
proc.wait(timeout=0.2)
print('== subprocess exited with rc =', proc.returncode)
except subprocess.TimeoutExpired:
print('subprocess did not terminate in time')
t.join()
Of course, there is nothing that says the extension of a header file must be .h
and the extension of a C source file must be .c
. These are useful conventions.
E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif
E:\Temp> type my.source
#include <stdio.h>
#include "my.interface"
int main(void) {
char x[MYBUFFERSIZE] = {0};
x[0] = 'a';
puts(x);
return 0;
}
E:\Temp> gcc -x c my.source -o my.exe
E:\Temp> my
a
Try this:
HTML:
<input type="checkbox" value="FALSE" />
jQ:
$("input[type='checkbox']").on('change', function(){
$(this).val(this.checked ? "TRUE" : "FALSE");
})
Please bear in mind that unchecked checkbox will not be submitted in regular form, and you should use hidden filed in order to do it.
All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:
getDaysDiff = function (dateObject0, dateObject1) {
if (dateObject0 >= dateObject1) return 0;
var d = new Date(dateObject0.getTime());
var nd = 0;
while (d <= dateObject1) {
d.setDate(d.getDate() + 1);
nd++;
}
return nd-1;
};
I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.
In Swift 4 I tried all of this previously, but runs only:
@IBAction func myButton(sender: AnyObject) {
sender.setTitle("This is example text one", for:[])
sender.setTitle("This is example text two", for: .normal)
}
This is not an answer, just my experience:
On my Ubuntu 12.04 apache2, didn't find Indexes
in either apache2.conf or httpd.conf, luckily I found it in sites-available/default
. After removing it, now it doesn't see directory listing. May have to do it for sites-available/default-ssl
.
This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show()
when you are ready to display the plots:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.
I've run into this issue when trying to build a fixed positioned sidebar with both vertically scrollable content and nested absolute positioned children to be displayed outside sidebar boundaries.
My approach consisted of separately apply:
overflow: visible
property to the sidebar elementoverflow-y: auto
property to sidebar inner wrapperPlease check the example below or an online codepen.
html {_x000D_
min-height: 100%;_x000D_
}_x000D_
body {_x000D_
min-height: 100%;_x000D_
background: linear-gradient(to bottom, white, DarkGray 80%);_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.sidebar {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 200px;_x000D_
overflow: visible; /* Just apply overflow-x */_x000D_
background-color: DarkOrange;_x000D_
}_x000D_
_x000D_
.sidebarWrapper {_x000D_
padding: 10px;_x000D_
overflow-y: auto; /* Just apply overflow-y */_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.element {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 100%;_x000D_
background-color: CornflowerBlue;_x000D_
padding: 10px;_x000D_
width: 200px;_x000D_
}
_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
<div class="sidebar">_x000D_
<div class="sidebarWrapper">_x000D_
<div class="element">_x000D_
I'm a sidebar child element but I'm able to horizontally overflow its boundaries._x000D_
</div>_x000D_
<p>This is a 200px width container with optional vertical scroll.</p>_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
</div>_x000D_
</div>
_x000D_
You can use this:
df.dropna(subset=['EPS'], how='all', inplace=True)
I found a faster way of embedding:
They're hints to the compiler to generate the hint prefixes on branches. On x86/x64, they take up one byte, so you'll get at most a one-byte increase for each branch. As for performance, it entirely depends on the application -- in most cases, the branch predictor on the processor will ignore them, these days.
Edit: Forgot about one place they can actually really help with. It can allow the compiler to reorder the control-flow graph to reduce the number of branches taken for the 'likely' path. This can have a marked improvement in loops where you're checking multiple exit cases.
List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();
String query = "SELECT rlink_id, COUNT(*)"
+ "FROM dbo.Locate "
+ "GROUP BY rlink_id ";
Statement stmt = yourconnection.createStatement();
try {
ResultSet rs4 = stmt.executeQuery(query);
while (rs4.next()) {
sids.add(rs4.getString(1));
lids.add(rs4.getString(2));
}
} finally {
stmt.close();
}
String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());
While there are two excellent answers telling you how to do it, I feel that another answer is missing: In most cases you shouldn't do it at all.
Arrays are cumbersome, in most cases you are better off using the Collection API.
With Collections, you can add and remove elements and there are specialized Collections for different functionality (index-based lookup, sorting, uniqueness, FIFO-access, concurrency etc.).
While it's of course good and important to know about Arrays and their usage, in most cases using Collections makes APIs a lot more manageable (which is why new libraries like Google Guava hardly use Arrays at all).
So, for your scenario, I'd prefer a List of Lists, and I'd create it using Guava:
List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
Sharing data between activites example passing an email after login
"email" is the name that can be used to reference the value on the activity that's being requested
1 Code on the login page
Intent openLoginActivity = new Intent(getBaseContext(), Home.class);
openLoginActivity.putExtra("email", getEmail);
2 code on the home page
Bundle extras = getIntent().getExtras();
accountEmail = extras.getString("email");
I would recommend %20
.
Are you hard-coding them?
This is not very consistent across languages, though.
If I'm not mistaken, in PHP urlencode()
treats spaces as +
whereas Python's urlencode()
treats them as %20
.
EDIT:
It seems I'm mistaken. Python's urlencode()
(at least in 2.7.2) uses quote_plus()
instead of quote()
and thus encodes spaces as "+".
It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.
EDIT #2:
I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:
import urllib
print(urllib.urlencode({' ' : '+ '})
>>> '+=%2B+'
Get rid from your <Button>
wrap div using display:block
and float:left
in both <Button>
and <h1>
and specifying their width
with a position:relative
to your Section
. This approach has the advantage of not needing another div
only to position your <Button>
html
<section>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
<button>button</button>
</section>
? css
section {
position: relative;
width: 50%;
border: 1px solid;
float:left;
}
h1 {
display: block;
width:70%;
float:left;
}
button
{
position:relative;
top:0;
left:0;
float:left;
}
?
Some context up front as to where I am coming from. Code snippets are at the end.
When I can, I prefer to use an open source tool like H2O to do super high performance parallel CSV file reads, but this tool is limited in feature set. I end up writing a lot of code to create data science pipelines before feeding to H2O cluster for the supervised learning proper.
I have been reading files like 8GB HIGGS dataset from UCI repo and even 40GB CSV files for data science purposes significantly faster by adding lots of parallelism with the multiprocessing library's pool object and map function. For example clustering with nearest neighbor searches and also DBSCAN and Markov clustering algorithms requires some parallel programming finesse to bypass some seriously challenging memory and wall clock time problems.
I usually like to break the file row-wise into parts using gnu tools first and then glob-filemask them all to find and read them in parallel in the python program. I use something like 1000+ partial files commonly. Doing these tricks helps immensely with processing speed and memory limits.
The pandas dataframe.read_csv is single threaded so you can do these tricks to make pandas quite faster by running a map() for parallel execution. You can use htop to see that with plain old sequential pandas dataframe.read_csv, 100% cpu on just one core is the actual bottleneck in pd.read_csv, not the disk at all.
I should add I'm using an SSD on fast video card bus, not a spinning HD on SATA6 bus, plus 16 CPU cores.
Also, another technique that I discovered works great in some applications is parallel CSV file reads all within one giant file, starting each worker at different offset into the file, rather than pre-splitting one big file into many part files. Use python's file seek() and tell() in each parallel worker to read the big text file in strips, at different byte offset start-byte and end-byte locations in the big file, all at the same time concurrently. You can do a regex findall on the bytes, and return the count of linefeeds. This is a partial sum. Finally sum up the partial sums to get the global sum when the map function returns after the workers finished.
Following is some example benchmarks using the parallel byte offset trick:
I use 2 files: HIGGS.csv is 8 GB. It is from the UCI machine learning repository. all_bin .csv is 40.4 GB and is from my current project. I use 2 programs: GNU wc program which comes with Linux, and the pure python fastread.py program which I developed.
HP-Z820:/mnt/fastssd/fast_file_reader$ ls -l /mnt/fastssd/nzv/HIGGS.csv
-rw-rw-r-- 1 8035497980 Jan 24 16:00 /mnt/fastssd/nzv/HIGGS.csv
HP-Z820:/mnt/fastssd$ ls -l all_bin.csv
-rw-rw-r-- 1 40412077758 Feb 2 09:00 all_bin.csv
ga@ga-HP-Z820:/mnt/fastssd$ time python fastread.py --fileName="all_bin.csv" --numProcesses=32 --balanceFactor=2
2367496
real 0m8.920s
user 1m30.056s
sys 2m38.744s
In [1]: 40412077758. / 8.92
Out[1]: 4530501990.807175
That’s some 4.5 GB/s, or 45 Gb/s, file slurping speed. That ain’t no spinning hard disk, my friend. That’s actually a Samsung Pro 950 SSD.
Below is the speed benchmark for the same file being line-counted by gnu wc, a pure C compiled program.
What is cool is you can see my pure python program essentially matched the speed of the gnu wc compiled C program in this case. Python is interpreted but C is compiled, so this is a pretty interesting feat of speed, I think you would agree. Of course, wc really needs to be changed to a parallel program, and then it would really beat the socks off my python program. But as it stands today, gnu wc is just a sequential program. You do what you can, and python can do parallel today. Cython compiling might be able to help me (for some other time). Also memory mapped files was not explored yet.
HP-Z820:/mnt/fastssd$ time wc -l all_bin.csv
2367496 all_bin.csv
real 0m8.807s
user 0m1.168s
sys 0m7.636s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.257s
user 0m12.088s
sys 0m20.512s
HP-Z820:/mnt/fastssd/fast_file_reader$ time wc -l HIGGS.csv
11000000 HIGGS.csv
real 0m1.820s
user 0m0.364s
sys 0m1.456s
Conclusion: The speed is good for a pure python program compared to a C program. However, it’s not good enough to use the pure python program over the C program, at least for linecounting purpose. Generally the technique can be used for other file processing, so this python code is still good.
Question: Does compiling the regex just one time and passing it to all workers will improve speed? Answer: Regex pre-compiling does NOT help in this application. I suppose the reason is that the overhead of process serialization and creation for all the workers is dominating.
One more thing. Does parallel CSV file reading even help? Is the disk the bottleneck, or is it the CPU? Many so-called top-rated answers on stackoverflow contain the common dev wisdom that you only need one thread to read a file, best you can do, they say. Are they sure, though?
Let’s find out:
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.256s
user 0m10.696s
sys 0m19.952s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=1
11000000
real 0m17.380s
user 0m11.124s
sys 0m6.272s
Oh yes, yes it does. Parallel file reading works quite well. Well there you go!
Ps. In case some of you wanted to know, what if the balanceFactor was 2 when using a single worker process? Well, it’s horrible:
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=2
11000000
real 1m37.077s
user 0m12.432s
sys 1m24.700s
Key parts of the fastread.py python program:
fileBytes = stat(fileName).st_size # Read quickly from OS how many bytes are in a text file
startByte, endByte = PartitionDataToWorkers(workers=numProcesses, items=fileBytes, balanceFactor=balanceFactor)
p = Pool(numProcesses)
partialSum = p.starmap(ReadFileSegment, zip(startByte, endByte, repeat(fileName))) # startByte is already a list. fileName is made into a same-length list of duplicates values.
globalSum = sum(partialSum)
print(globalSum)
def ReadFileSegment(startByte, endByte, fileName, searchChar='\n'): # counts number of searchChar appearing in the byte range
with open(fileName, 'r') as f:
f.seek(startByte-1) # seek is initially at byte 0 and then moves forward the specified amount, so seek(5) points at the 6th byte.
bytes = f.read(endByte - startByte + 1)
cnt = len(re.findall(searchChar, bytes)) # findall with implicit compiling runs just as fast here as re.compile once + re.finditer many times.
return cnt
The def for PartitionDataToWorkers is just ordinary sequential code. I left it out in case someone else wants to get some practice on what parallel programming is like. I gave away for free the harder parts: the tested and working parallel code, for your learning benefit.
Thanks to: The open-source H2O project, by Arno and Cliff and the H2O staff for their great software and instructional videos, which have provided me the inspiration for this pure python high performance parallel byte offset reader as shown above. H2O does parallel file reading using java, is callable by python and R programs, and is crazy fast, faster than anything on the planet at reading big CSV files.
Using GetFiles search pattern for filtering the extension is not safe!! For instance you have two file Test1.xls and Test2.xlsx and you want to filter out xls file using search pattern *.xls, but GetFiles return both Test1.xls and Test2.xlsx I was not aware of this and got error in production environment when some temporary files suddenly was handled as right files. Search pattern was *.txt and temp files was named *.txt20181028_100753898 So search pattern can not be trusted, you have to add extra check on filenames as well.
Not possible.
You can only store, simple values in SharedPrefences SharePreferences.Editor
What particularly about the class do you need to save?
The rep.row function seems to sometimes make lists for columns, which leads to bad memory hijinks. I have written the following which seems to work well:
library(plyr)
rep.row <- function(r, n){
colwise(function(x) rep(x, n))(r)
}
Since you don't need to actually edit the file:
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = value
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
_x000D_
input{
padding: 10px;
font: 20px Arial;
width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
This is phpMyAdmin method.
$query = "INSERT INTO myTable
(mtb_i_idautoinc, mtb_s_string1, mtb_s_string2)
VALUES
(NULL, 'Jagodina', '35000')";
Use inline styles:
<div class="button" style="width:60px;height:100px;">This is a button</div>
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.
To fix this I added the following to manually trigger the jquery validation event that gets added by the library:
$(".chosen-select").each(function() {
$(this).chosen().on("change", function() {
$(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
});
});
jquery.validate will now add the .valid
class to the underlying select list.
Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group
, and each input has .form-control
.
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
Use ready event of document :
$(document).ready(function(){ /* the click code */ });
And it is better to use bind method for event handeling. because you don't want to call click action in every load of page
$(':submit').bind('click' , function () { /* ... */ });
An alternative to the many solutions already provided is making use of the glob **
. When you use bash
with the option globstar
(shopt -s globstar
) or you make use of zsh
, you can just use the glob **
for this.
**/bar
does a recursive directory search for files named bar
(potentially including the file bar
in the current directory). Remark that this cannot be combined with other forms of globbing within the same path segment; in that case, the *
operators revert to their usual effect.
Note that there is a subtle difference between zsh
and bash
here. While bash
will traverse soft-links to directories, zsh
will not. For this you have to use the glob ***/
in zsh
.
Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.
NuGet- > Install-Package Newtonsoft.Json
You should use html height attribute for the canvas element as:
<div class="chart">
<canvas id="myChart" height="100"></canvas>
</div>
I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity The following code starts this application:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);
Try this, it was created by James Padolsey(J-P here on SO) and does exactly what you want (I think)
http://james.padolsey.com/javascript/monitoring-dom-properties/
Also this happens when I was installing mysqlclient,
$ pip install mysqlclient
As user3429036 said,
$ brew install mysql
Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 100000; j++)
{
Calculate(j);
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
// TODO: Do something after all calculations
}
Tasks are currently the preferred way to implement what BackgroundWorker
does.
Tasks and
Progress
are explained in more detail here:
ApplicationContext (Root Application Context) : Every Spring MVC web application has an applicationContext.xml file which is configured as the root of context configuration. Spring loads this file and creates an applicationContext for the entire application. This file is loaded by the ContextLoaderListener which is configured as a context param in web.xml file. And there will be only one applicationContext per web application.
WebApplicationContext : WebApplicationContext is a web aware application context i.e. it has servlet context information. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.
The reason is quite obvious in the exception name itself i.e. the resolution of the resource is too large to render.
You can png to xml using online tools like https://svg2vector.com/ OR add your image to drawable-xxhdpi folder.
To understand how to use sqlite database in android with best practices see - Android with sqlite database
There are few classes about which you should know and those will help you model your tables and models i.e android.provider.BaseColumns
Below is an example of a table
public class ProductTable implements BaseColumns {
public static final String NAME = "name";
public static final String PRICE = "price";
public static final String TABLE_NAME = "products";
public static final String CREATE_QUERY = "create table " + TABLE_NAME + " (" +
_ID + " INTEGER, " +
NAME + " TEXT, " +
PRICE + " INTEGER)";
public static final String DROP_QUERY = "drop table " + TABLE_NAME;
public static final String SElECT_QUERY = "select * from " + TABLE_NAME;
}
I've written a very simple extension method on DateTime
and DateTimeOffset
to do this. I wanted it to work exactly like a TotalMonths
property on TimeSpan
would work: i.e. return the count of complete months between two dates, ignoring any partial months. Because it's based on DateTime.AddMonths()
it respects different month lengths and returns what a human would understand as a period of months.
(Unfortunately you can't implement it as an extension method on TimeSpan because that doesn't retain knowledge of the actual dates used, and for months they're important.)
The code and tests are both available on GitHub. The code is very simple:
public static int GetTotalMonthsFrom(this DateTime dt1, DateTime dt2)
{
DateTime earlyDate = (dt1 > dt2) ? dt2.Date : dt1.Date;
DateTime lateDate = (dt1 > dt2) ? dt1.Date : dt2.Date;
// Start with 1 month's difference and keep incrementing
// until we overshoot the late date
int monthsDiff = 1;
while (earlyDate.AddMonths(monthsDiff) <= lateDate)
{
monthsDiff++;
}
return monthsDiff - 1;
}
And it passes all these unit test cases:
// Simple comparison
Assert.AreEqual(1, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 2, 1)));
// Just under 1 month's diff
Assert.AreEqual(0, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 1, 31)));
// Just over 1 month's diff
Assert.AreEqual(1, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 2, 2)));
// 31 Jan to 28 Feb
Assert.AreEqual(1, new DateTime(2014, 1, 31).GetTotalMonthsFrom(new DateTime(2014, 2, 28)));
// Leap year 29 Feb to 29 Mar
Assert.AreEqual(1, new DateTime(2012, 2, 29).GetTotalMonthsFrom(new DateTime(2012, 3, 29)));
// Whole year minus a day
Assert.AreEqual(11, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2012, 12, 31)));
// Whole year
Assert.AreEqual(12, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2013, 1, 1)));
// 29 Feb (leap) to 28 Feb (non-leap)
Assert.AreEqual(12, new DateTime(2012, 2, 29).GetTotalMonthsFrom(new DateTime(2013, 2, 28)));
// 100 years
Assert.AreEqual(1200, new DateTime(2000, 1, 1).GetTotalMonthsFrom(new DateTime(2100, 1, 1)));
// Same date
Assert.AreEqual(0, new DateTime(2014, 8, 5).GetTotalMonthsFrom(new DateTime(2014, 8, 5)));
// Past date
Assert.AreEqual(6, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2011, 6, 10)));
IMHO it is considered as malformed header data.
You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.
The second way is true.
Typescript and Angular Implementation
directive
((): void=> {
"use strict";
angular.module("app").directive("busyindicator", busyIndicator);
function busyIndicator($http:ng.IHttpService): ng.IDirective {
var directive = <ng.IDirective>{
restrict: "A",
link(scope: Scope.IBusyIndicatorScope) {
scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
scope.$watch(scope.anyRequestInProgress, x => {
if (x) {
scope.canShow = true;
} else {
scope.canShow = false;
}
});
}
};
return directive;
}
})();
Scope
module App.Scope {
export interface IBusyIndicatorScope extends angular.IScope {
anyRequestInProgress: any;
canShow: boolean;
}
}
Template
<div id="activityspinner" ng-show="canShow" class="show" data-busyindicator>
</div>
CSS
#activityspinner
{
display : none;
}
#activityspinner.show {
display : block;
position : fixed;
z-index: 100;
background-image : url('data:image/gif;base64,R0lGODlhNgA3APMAAPz8/GZmZqysrHV1dW1tbeXl5ZeXl+fn59nZ2ZCQkLa2tgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAANgA3AAAEzBDISau9OOvNu/9gKI5kaZ4lkhBEgqCnws6EApMITb93uOqsRC8EpA1Bxdnx8wMKl51ckXcsGFiGAkamsy0LA9pAe1EFqRbBYCAYXXUGk4DWJhZN4dlAlMSLRW80cSVzM3UgB3ksAwcnamwkB28GjVCWl5iZmpucnZ4cj4eWoRqFLKJHpgSoFIoEe5ausBeyl7UYqqw9uaVrukOkn8LDxMXGx8ibwY6+JLxydCO3JdMg1dJ/Is+E0SPLcs3Jnt/F28XXw+jC5uXh4u89EQAh+QQJCgAAACwAAAAANgA3AAAEzhDISau9OOvNu/9gKI5kaZ5oqhYGQRiFWhaD6w6xLLa2a+iiXg8YEtqIIF7vh/QcarbB4YJIuBKIpuTAM0wtCqNiJBgMBCaE0ZUFCXpoknWdCEFvpfURdCcM8noEIW82cSNzRnWDZoYjamttWhphQmOSHFVXkZecnZ6foKFujJdlZxqELo1AqQSrFH1/TbEZtLM9shetrzK7qKSSpryixMXGx8jJyifCKc1kcMzRIrYl1Xy4J9cfvibdIs/MwMue4cffxtvE6qLoxubk8ScRACH5BAkKAAAALAAAAAA2ADcAAATOEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwyZKxhqhgJJeSQVdraBNFSsVUVPHsEAzJrEtnJNSELXRN2bKcwjw19f0QG7PjA7B2EGfn+FhoeIiYoSCAk1CQiLFQpoChlUQwhuBJEWcXkpjm4JF3w9P5tvFqZsLKkEF58/omiksXiZm52SlGKWkhONj7vAxcbHyMkTmCjMcDygRNAjrCfVaqcm11zTJrIjzt64yojhxd/G28XqwOjG5uTxJhEAIfkECQoAAAAsAAAAADYANwAABM0QyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/i8qmCoGQoacT8FZ4AXbFopfTwEBhhnQ4w2j0GRkgQYiEOLPI6ZUkgHZwd6EweLBqSlq6ytricICTUJCKwKkgojgiMIlwS1VEYlspcJIZAkvjXHlcnKIZokxJLG0KAlvZfAebeMuUi7FbGz2z/Rq8jozavn7Nev8CsRACH5BAkKAAAALAAAAAA2ADcAAATLEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwzJNCmPzheUyJuKijVrZ2cTlrg1LwjcO5HFyeoJeyM9U++mfE6v2+/4PD6O5F/YWiqAGWdIhRiHP4kWg0ONGH4/kXqUlZaXmJlMBQY1BgVuUicFZ6AhjyOdPAQGQF0mqzauYbCxBFdqJao8rVeiGQgJNQkIFwdnB0MKsQrGqgbJPwi2BMV5wrYJetQ129x62LHaedO21nnLq82VwcPnIhEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/g8Po7kX9haKoAZZ0iFGIc/iRaDQ40Yfj+RepSVlpeYAAgJNQkIlgo8NQqUCKI2nzNSIpynBAkzaiCuNl9BIbQ1tl0hraewbrIfpq6pbqsioaKkFwUGNQYFSJudxhUFZ9KUz6IGlbTfrpXcPN6UB2cHlgfcBuqZKBEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7yJEopZA4CsKPDUKfxIIgjZ+P3EWe4gECYtqFo82P2cXlTWXQReOiJE5bFqHj4qiUhmBgoSFho59rrKztLVMBQY1BgWzBWe8UUsiuYIGTpMglSaYIcpfnSHEPMYzyB8HZwdrqSMHxAbath2MsqO0zLLorua05OLvJxEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhfohELYHQuGBDgIJXU0Q5CKqtOXsdP0otITHjfTtiW2lnE37StXUwFNaSScXaGZvm4r0jU1RWV1hhTIWJiouMjVcFBjUGBY4WBWw1A5RDT3sTkVQGnGYYaUOYPaVip3MXoDyiP3k3GAeoAwdRnRoHoAa5lcHCw8TFxscduyjKIrOeRKRAbSe3I9Um1yHOJ9sjzCbfyInhwt3E2cPo5dHF5OLvJREAOwAAAAAAAAAAAA==')
-ms-opacity : 0.4;
opacity : 0.4;
background-repeat : no-repeat;
background-position : center;
left : 0;
bottom : 0;
right : 0;
top : 0;
}
Replace the watch battery in your computer. I have seen this error message when the coin looking battery on the motherboard was in need of replacement.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Do the following steps:
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/
Note - I am using CentOS7 as OS.
Try this to validate HTTP URLs (uriName
is the URI you want to test):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttp;
Or, if you want to accept both HTTP and HTTPS URLs as valid (per J0e3gan's comment):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
Use TextAreaFor
@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })
or use style for multi-line
class.
You could also write EditorTemplate for this.
If the data comes from an external library you might need to run the data upate statement within zone.run(...)
. Inject zone: NgZone
for this. If you can run the instantiation of the external library within zone.run()
already, then you might not need zone.run()
later.
pip install pyqt5
for python3 for ubuntu
I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute
.
First we need a validator:
public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
{
private readonly string _errorMessage;
private readonly int _length;
public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
: base(metadata, context, attribute)
{
_errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
_length = attribute.Length;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = _errorMessage,
ValidationType = "length"
};
rule.ValidationParameters["max"] = _length;
yield return rule;
}
}
Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules
we set a rule. ValidationType = "length"
is mapped to data-val-length
by the framework. rule.ValidationParameters["max"]
is for the data-val-length-max
attribute.
Now since you have a validator, you only need to register it in global.asax
:
protected void Application_Start()
{
//...
//Register Validator
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}
Et voila, it just works.
Using PostgreSQL 9.6.x with official Java driver 42.2.4
:
...myPreparedStatement.execute...
myPreparedStatement.toString()
Will show the SQL with the ?
already replaced, which is what I was looking for.
Just added this answer to cover the postgres case.
I would never have thought it could be so simple.
Done! Numbers only and maxlength work perfect.
<input maxlength="5" data-rule-maxlength="5" style="height:30px;width: 786px;" type="number" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
It is an old question, but I just ran into it.
Type.GetMethod(string name)
will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case
public static bool HasMethod(this object objectToCheck, string methodName)
{
try
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
catch(AmbiguousMatchException)
{
// ambiguous means there is more than one result,
// which means: a method with that name does exist
return true;
}
}
Check for already existing primary key with different column. If yes, drop the primary key using:
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO
and then write your query as it is.
After trying all the suggestions given here and other threads like this one I still couldn't get apt_get
to work on my Vagrant Ubuntu 16.04. In the end removing the file apt.conf
from /etc/apt
resolved the issue for me. My remaining files in that directory are:
vagrant@default:~$ ls -l /etc/apt/
total 68
drwxr-xr-x 2 root root 4096 Apr 15 12:20 apt.conf.d
drwxr-xr-x 2 root root 4096 May 21 2019 auth.conf.d
-rw-r--r-- 1 root root 53 Mar 19 19:50 preferences
drwxr-xr-x 2 root root 4096 Apr 14 2016 preferences.d
-rw-r--r-- 1 root root 3166 Sep 10 15:55 sources.list
drwxr-xr-x 2 root root 4096 Sep 10 16:04 sources.list.d
-rw-r--r-- 1 root root 17640 Mar 19 20:04 trusted.gpg
-rw-r--r-- 1 root root 17281 Mar 19 20:01 trusted.gpg~
drwxr-xr-x 2 root root 4096 Sep 10 13:45 trusted.gpg.d
I generally like to use my own extension for that:
string data = "THExxQUICKxxBROWNxxFOX";
var dataspt = data.Split("xx");
//>THE QUICK BROWN FOX
//the extension class must be declared as static
public static class StringExtension
{
public static string[] Split(this string str, string splitter)
{
return str.Split(new[] { splitter }, StringSplitOptions.None);
}
}
This will however lead to an Exception, if Microsoft decides to include this method-overload in later versions. It is also the likely reason why Microsoft has not included this method in the meantime: At least one company I worked for, used such an extension in all their C# projects.
It may also be possible to conditionally define the method at runtime if it doesn't exist.
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
The line's color is defined by EditText
's background property. To change it you should change the android:background
in the layout file.
I should note that this style is achieved by using a 9-patch drawable. If you look in the SDK, you can see that the background of the EditText
is this image:
To change it you could open it in an image manipulation program and color it in desired color. Save it as bg_edit_text.9.png
and then put it in you drawable folder. Now you can apply it as a background for your EditText
like so:
android:background="@drawable/bg_edit_text"
From the DevTools console, you can run:
document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';
Check the available jQuery version at https://code.jquery.com/jquery/.
To check whether it's loaded, see: Checking if jquery is loaded using Javascript.
Install Service:-
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe"
"C:\Services\myservice.exe"
UnInstall Sevice:-
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" -u "C:\Services\myservice.Service.exe"
This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.
Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
That's concerning. It's comparable to 2006's Internet Explorer 7.
To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:
var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";
var supported = new Func<string, bool>(url =>
{
try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
catch { return false; }
});
var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));
I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.
Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol
. See https://stackoverflow.com/a/26392698/284795
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
SUPER KEY:
Attribute or set of attributes used to uniquely identify tuples in the database.
CANDIDATE KEY:
PRIMARY KEY:
one of the candidate key which is used to identify records in DB uniquely
not null
If you're doing some performance tuning it's often recommended to set both -XX:PermSize
and -XX:MaxPermSize
to the same value to increase JVM
efficiency.
Here is some information:
You can also specify -XX:+CMSClassUnloadingEnabled
to enable class unloading
option if you are using CMS
GC
. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space
The voted up answer is missing a step.
Per aws s3 help:
Currently, there is no support for the use of UNIX style wildcards in a command's path arguments. However, most commands have
--exclude "<value>"
and--include "<value>"
parameters that can achieve the desired result......... When there are multiple filters, the rule is the filters that appear later in the command take precedence over filters that appear earlier in the command. For example, if the filter parameters passed to the command were--exclude "*"
--include "*.txt"
All files will be excluded from the command except for files ending with .txt
aws s3 rm --recursive s3://bucket/ --exclude="*" --include="/folder_path/*"
If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:
$ rm -f abc.log.* # Remove them all
$ rm -f abc.log.2012* # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012
Regular expressions are more powerful than wildcards; you can feed the output of grep
to rm -f
. For example, if some of the file names start with "abc.log"
and some with "ABC.log"
, grep
lets you do a case-insensitive match:
$ rm -f $(ls | grep -i '^abc\.log\.')
This will cause problems if any of the file names contain funny characters, including spaces. Be careful.
When I do this, I run the ls | grep ...
command first and check that it produces the output I want -- especially if I'm using rm -f
:
$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)
where !!
expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f
command.
This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...)
syntax. You can use the equivalent backtick syntax:
$ rm -f `ls | grep -i '^abc\.log\.'`
The $(...)
syntax is easier to read, and if you're really ambitious it can be nested.
Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:
$ ls > list
$ vi list # Use your favorite text editor
I can then edit the list
file manually, leaving only the files I want to remove, and then:
$ rm -f $(<list)
or
$ rm -f `cat list`
(Again, this assumes none of the file names contain funny characters, particularly spaces.)
Or, when editing the list
file, I can add rm -f
to the beginning of each line and then:
$ . ./list
or
$ source ./list
Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar
to rm -f 'foo bar'
.
restore the .git/ORIG_HEAD
and other root .git repo files
I got this error after restoring from backup, apparently the files contained in the .git directory root didn't make it to the target,but all the subfolders did so at first I thought the repo was intact.
I fixed it by restoring the root files.
I'm using Centos and the followings worked for me , I run this command
yum --enablerepo remi install php-xml
And restarted the Apache with this command
sudo service httpd restart
You can use an inflater with TableRow:
for (int i = 0; i < months; i++) {
View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
TextView textView = view.findViewById (R.id.title);
textView.setText ("Text");
tableLayout.addView (view);
}
Layout:
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:paddingTop="15dp"
android:paddingRight="15dp"
android:paddingLeft="15dp"
android:paddingBottom="10dp"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center"
/>
</TableRow>
You can give like this
public static function getAll()
{
return $posts = $this->all()->take(2)->get();
}
And when you call statically inside your controller function also..
Use the string's .replace
method with a regex of \D
, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:
foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
# Select all the Revision folders from the project folder.
$Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory
# The next revision number is just going to be one more than the highest number.
# You need to cast the string in the first pipeline to an int so Sort-Object works.
# If you sort it descending the first number will be the biggest so you select that one.
# Once you have the highest revision number you just add one to it.
$NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1
# Now in this we kill two birds with one stone.
# It will create the "Reports" folder but it also creates "Revision#" folder too.
New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory
# Move on to the next project folder.
# This untested example loop requires PowerShell version 3.0.
}
We can also use str_extract
from stringr
years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20 1
If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all
which unlike str_extract
returns all the macthes.
years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20" "1"
stringr::str_extract_all(years, "\\d+")
#[[1]]
#[1] "20" "21"
#[[2]]
#[1] "1"
What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.
// Getting 'Info' div in js hands_x000D_
var info = document.getElementById('info');_x000D_
_x000D_
// Creating function that will tell the position of cursor_x000D_
// PageX and PageY will getting position values and show them in P_x000D_
function tellPos(p){_x000D_
info.innerHTML = 'Position X : ' + p.pageX + '<br />Position Y : ' + p.pageY;_x000D_
}_x000D_
addEventListener('mousemove', tellPos, false);
_x000D_
* {_x000D_
padding: 0:_x000D_
margin: 0;_x000D_
/*transition: 0.2s all ease;*/_x000D_
}_x000D_
#info {_x000D_
position: absolute;_x000D_
top: 10px;_x000D_
right: 10px;_x000D_
background-color: black;_x000D_
color: white;_x000D_
padding: 25px 50px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<div id='info'></div>_x000D_
</body>_x000D_
</html>
_x000D_
Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works. The important bit being the wrapper around the object list.
$(document).ready(function () {
var employeeList = [
{ id: 1, name: 'Bob' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Tom' }
];
var Employees = {
EmployeeList: employeeList
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Employees/Process',
data: Employees,
success: function () {
$('#InfoPanel').html('It worked!');
},
failure: function (response) {
$('#InfoPanel').html(response);
}
});
});
public void Process(List<Employee> EmployeeList)
{
var emps = EmployeeList;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
Single liner works
df['Name'] = 'abc'
Creates a Name
column and sets all rows to abc
value
If we talk about SessionFactory.openSession()
And If we talk about SessionFactory.getCurrentSession()
In addition other guys answer, its Easy to get property value of any object by use Extension method like:
public static class Helper
{
public static object GetPropertyValue(this object T, string PropName)
{
return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
}
}
Usage is:
Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");
A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
apt-get install python2.7
will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.
If you search a value in a fixed list of values many times in a long list, HashSet<T> should be used. If the list is very short (< ~20 items), List could have better performance, based on this test HashSet vs. List performance
HashSet<int> nums = new HashSet<int> { 1, 2, 3, 4, 5 };
// ....
if (nums.Contains(value))
If you want to split/cut the array on an index i,
arr = arr.drop(i)
> arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
> arr.drop(2)
=> [3, 4, 5]
function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}
Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.
In my case namespaces
parameter was not matching the namespace of the controller.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Web.Areas.Admin.Controllers" }
);
}
You could use the .attr()
function:
$(this).attr('data-fullText')
or if you lowercase the attribute name:
data-fulltext="This is a span element"
then you could use the .data()
function:
$(this).data('fulltext')
The .data()
function expects and works only with lowercase attribute names.
One thing I don't see in examples is that when you cast BehaviorSubject to Observable via asObservable, it inherits behaviour of returning last value on subscription.
It's the tricky bit, as often libraries will expose fields as observable (i.e. params in ActivatedRoute in Angular2), but may use Subject or BehaviorSubject behind the scenes. What they use would affect behaviour of subscribing.
See here http://jsbin.com/ziquxapubo/edit?html,js,console
let A = new Rx.Subject();
let B = new Rx.BehaviorSubject(0);
A.next(1);
B.next(1);
A.asObservable().subscribe(n => console.log('A', n));
B.asObservable().subscribe(n => console.log('B', n));
A.next(2);
B.next(2);
Obsolete: This answer is correct only for an older version of Notepad++. Converting between tabs/spaces is now built into Notepad++ and the TextFX plugin is no longer available in the Plugin Manager dialog.
Preferences -> Language Menu/Tab Settings
.TextFX -> TextFX Edit -> Leading spaces to tabs or tabs to spaces
.Note: Make sure TextFX Characters plugin is installed (Plugins -> Plugin manager -> Show plugin manager
, Installed
tab). Otherwise, there will be no TextFX menu.
select right(convert(varchar(20),getdate(),100),7)
This worked for me.
Go to Project --> Properties --> Run/Debug Settings --> Click on the configuration & click "Edit", it will now open a "Edit Configuration".
Hit on "Search Project" , select the binary file from the "Binaries" and hit ok.
Note : Before doing all this, make sure you have done the below
--> Binary is generated once you execute "Build All" or (Ctrl+B)
If you are talking about actually compressing the text not just shortening then Deflate/gzip (wrapper around gzip), zip work well for smaller files and text. Other algorithms are highly efficient for larger files like bzip2 etc.
Wikipedia has a list of compression times. (look for comparison of efficiency)
Name | Text | Binaries | Raw images
-----------+--------------+---------------+-------------
7-zip | 19% in 18.8s | 27% in 59.6s | 50% in 36.4s
bzip2 | 20% in 4.7s | 37% in 32.8s | 51% in 20.0s
rar (2.01) | 23% in 30.0s | 36% in 275.4s | 58% in 52.7s
advzip | 24% in 21.1s | 37% in 70.6s | 57& in 41.6s
gzip | 25% in 4.2s | 39% in 23.1s | 60% in 5.4s
zip | 25% in 4.3s | 39% in 23.3s | 60% in 5.7s
Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.
import re
len(re.sub("[^0-9]", "", my_string))
Alphabetical:
import re
len(re.sub("[^a-zA-Z]", "", my_string))
More info - https://docs.python.org/3/library/re.html
+1 means 2 days ago. It's rounded.
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare @thing varchar(100)
select @thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(@thing)
--This converts just fine.
select convert(float,@thing)
select @thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(@thing)
--This convert throws.
select convert(float,@thing)
since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.
Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
InDate = Me.FromDateTxt
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
Use numpy.sum
. for your case, it is
sum = a.sum(axis=0)
In response to piemesons rant against jQuery, a Vanilla JavaScript(TM) solution (tested on FF and IE):
Put this in a script tag after your markup is loaded (right before the close of the body tag) and you'll get a similar effect to the jQuery example.
a = document.getElementsByTagName('a');
for (var i = 0; i < a.length;i++) {
a[i].getElementsByTagName('span')[1].onclick = function() { return false;};
}
This will disable the click on every 2nd span inside of an a tag. You could also check the innerHTML of each span for "description", or set an attribute or class and check that.
NULL can also be found in:
#include <string.h>
String.h will pull in the NULL from somewhere else.
(.*)
instead of (.)*
would be a start. The latter will only capture the last character on the line.
Also, no need to escape the :
.
I have several library projects with the same package name specified in the AndroidManifest (so no duplicate field names are generated by R.java). I had to remove any permissions and activities from the AndroidManifest.xml for all library projects to remove the error so Manifest.java wasn't created multiple times. Hopefully this can help someone.
Can you check your postgresql.conf file ??
On what port your postgres is running ??
I think it is not running on port 5432.If not change it to 5432
OR on terminal use
psql -U postgres -p YOUR_PORT_NUMBER database_name
I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.
If you're unable to change the structure, something like the below might work:
SELECT
*
FROM
Test
WHERE
Account_Location = (
CASE LocationType
WHEN 'location' THEN @locationID
ELSE Account_Location
END
)
AND
Account_Location_Area = (
CASE LocationType
WHEN 'area' THEN @locationID
ELSE Account_Location_Area
END
)
And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.
EDIT: The above suggestions are of course much better, just ignore mine.
If you're doing the check inside the View, put the value in the ViewBag
.
In your controller:
ViewBag["parameterName"] = Request["parameterName"];
It's worth noting that the Request
and Response
properties are exposed by the Controller
class. They have the same semantics as HttpRequest
and HttpResponse
.
This is known as a Shebang
:
http://en.wikipedia.org/wiki/Shebang_(Unix)
#!interpreter [optional-arg]
A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).
When a shell executes the script it will use the specified interpreter.
Example:
#!/bin/bash
# file: foo.sh
echo 1
$ chmod u+x foo.sh
$ ./foo.sh
1
This is a slight variation, but PJW's solution didn't quite work for me:
java -version 2>&1 | head -n 1 | cut -d'"' -f2
just cut the string on the delimiter "
(double quotes) and get the second field.
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
If you want something more reliable than Celery, try TaskHawk which is built on top of AWS SQS/SNS.
If you need something quick and dirty, you can just use PayPal's "Buy" buttons and drop them on your pages. These will take people off-site to PayPal where they can pay with a PayPal account or a credit card. This is free and super easy to implement.
If you want something a bit nicer where people pay on-site with their credit card, then you would want to look into one of those 3rd part payment providers. None of them (that I'm aware of) are completely free. All will have a per-transaction fee, and most will have a monthly fee as well.
Personally I've worked with Authorize.NET and PayPal Website Payments Pro. Both have great APIs and sample code that you can hook into via PHP easily enough.
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.
You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.
Or else the easiest you could do is use sessions.
<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>
<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">
<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>
$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});
This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/
This can be achieved natively using the jQueryUI hide/show methods. Eg.
// To slide something leftwards into view,
// with a delay of 1000 msec
$("div").click(function () {
$(this).show("slide", { direction: "left" }, 1000);
});
Reference: http://docs.jquery.com/UI/Effects/Slide
\usepackage[utf8]{inputenc}
will not work for a bibliographic entry such as this:
@ARTICLE{Hardy2007,
author = {Ibn Taymiyyah, A?mad ibn ?Abd al{-}Halim},
title = {Naq? al{-}man?iq},
shorttitle = {Naq? al-man?iq},
editor = {?amzah, A?mad},
publisher = {Maktabat a{l-}Sunnah},
address = {Cairo},
year = {1970},
sortname = {IbnTaymiyyaNaqdalmantiq},
keywords = { Logic, Medieval}}
For this entry use \usepackage[utf8x]{inputenc}
What about this simple code, works for me and on Windows 7
set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin
:end
tl;dr:
Sort array a_in
and store the result in a_out
(elements must not have embedded newlines[1]
):
Bash v4+:
readarray -t a_out < <(printf '%s\n' "${a_in[@]}" | sort)
Bash v3:
IFS=$'\n' read -d '' -r -a a_out < <(printf '%s\n' "${a_in[@]}" | sort)
Advantages over antak's solution:
You needn't worry about accidental globbing (accidental interpretation of the array elements as filename patterns), so no extra command is needed to disable globbing (set -f
, and set +f
to restore it later).
You needn't worry about resetting IFS
with unset IFS
.[2]
The above combines Bash code with external utility sort
for a solution that works with arbitrary single-line elements and either lexical or numerical sorting (optionally by field):
Performance: For around 20 elements or more, this will be faster than a pure Bash solution - significantly and increasingly so once you get beyond around 100 elements.
(The exact thresholds will depend on your specific input, machine, and platform.)
printf '%s\n' "${a_in[@]}" | sort
performs the sorting (lexically, by default - see sort
's POSIX spec):
"${a_in[@]}"
safely expands to the elements of array a_in
as individual arguments, whatever they contain (including whitespace).
printf '%s\n'
then prints each argument - i.e., each array element - on its own line, as-is.
Note the use of a process substitution (<(...)
) to provide the sorted output as input to read
/ readarray
(via redirection to stdin, <
), because read
/ readarray
must run in the current shell (must not run in a subshell) in order for output variable a_out
to be visible to the current shell (for the variable to remain defined in the remainder of the script).
Reading sort
's output into an array variable:
Bash v4+: readarray -t a_out
reads the individual lines output by sort
into the elements of array variable a_out
, without including the trailing \n
in each element (-t
).
Bash v3: readarray
doesn't exist, so read
must be used:
IFS=$'\n' read -d '' -r -a a_out
tells read
to read into array (-a
) variable a_out
, reading the entire input, across lines (-d ''
), but splitting it into array elements by newlines (IFS=$'\n'
. $'\n'
, which produces a literal newline (LF), is a so-called ANSI C-quoted string).
(-r
, an option that should virtually always be used with read
, disables unexpected handling of \
characters.)
Annotated sample code:
#!/usr/bin/env bash
# Define input array `a_in`:
# Note the element with embedded whitespace ('a c')and the element that looks like
# a glob ('*'), chosen to demonstrate that elements with line-internal whitespace
# and glob-like contents are correctly preserved.
a_in=( 'a c' b f 5 '*' 10 )
# Sort and store output in array `a_out`
# Saving back into `a_in` is also an option.
IFS=$'\n' read -d '' -r -a a_out < <(printf '%s\n' "${a_in[@]}" | sort)
# Bash 4.x: use the simpler `readarray -t`:
# readarray -t a_out < <(printf '%s\n' "${a_in[@]}" | sort)
# Print sorted output array, line by line:
printf '%s\n' "${a_out[@]}"
Due to use of sort
without options, this yields lexical sorting (digits sort before letters, and digit sequences are treated lexically, not as numbers):
*
10
5
a c
b
f
If you wanted numerical sorting by the 1st field, you'd use sort -k1,1n
instead of just sort
, which yields (non-numbers sort before numbers, and numbers sort correctly):
*
a c
b
f
5
10
[1] To handle elements with embedded newlines, use the following variant (Bash v4+, with GNU sort
):
readarray -d '' -t a_out < <(printf '%s\0' "${a_in[@]}" | sort -z)
.
Michal Górny's helpful answer has a Bash v3 solution.
[2] While IFS
is set in the Bash v3 variant, the change is scoped to the command.
By contrast, what follows IFS=$'\n'
in antak's answer is an assignment rather than a command, in which case the IFS
change is global.
EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6
. To install the required version of the library:
$ sudo apt-get install libxtst6:i386
Type:
$ sudo apt-get update
$ sudo apt-get install libxtst6
If this isn’t OK, type:
$ sudo updatedb
$ locate libXtst
it should return something like:
/usr/lib/x86_64-linux-gnu/libXtst.so.6 # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0
If you do not have libXtst.so.6
but do have libXtst.so.6.X.X
create a symbolic link:
$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X
Hope this helps.
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
Keep in mind that MySQL has a maximum row size limit
The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, not counting BLOB and TEXT types. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row. Read more about Limits on Table Column Count and Row Size.
Maximum size a single column can occupy, is different before and after MySQL 5.0.3
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
However, note that the limit is lower if you use a multi-byte character set like utf8 or utf8mb4.
Use TEXT
types inorder to overcome row size limit.
The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.
More details on BLOB and TEXT Types
Even more
Checkout more details on Data Type Storage Requirements which deals with storage requirements for all data types.
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
Use SHOW INDEX
like so:
SHOW INDEX FROM [tablename]
Docs: https://dev.mysql.com/doc/refman/5.0/en/show-index.html
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
The actual reason is that, in a new repo (git init), there is no branch (no master
, no branch at all, zero branches)
So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.
And:
matching
' (push all the branches of the same name, creating them if they don't exist), simple
' (push only the current branch, and only if it has a similarly named remote tracking branch on upstream, since git 1.7.11)In both cases, since the upstream empty repo has no branch:
That means your local first push has no idea:
So you need at least to do a:
git push origin master
But if you do only that, you:
master
branch on the upstream (now non-empty repo): good.master
' needs to be pushed to upstream (origin
) 'master
' (upstream branch): bad.That is why it is recommended, for the first push, to do a:
git push -u origin master
That will record origin/master
as a remote tracking branch, and will enable the next push to automatically push master
to origin/master
.
git checkout master
git push
And that will work too with push policies 'current
' or 'upstream
'.
In each case, after the initial git push -u origin master
, a simple git push will be enough to continue pushing master to the right upstream branch.
Why don't you style it out:
<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
Your browser does not support the canvas element.
</canvas>
I simply wrote an embedded SQL program to write a new record with date fields. It was by far best and shortest without any errors I was able to reach my requirement.
w_dob = %char(%date(*date));
exec sql insert into Tablename (ID_Number ,
AmendmentNo ,
OverrideDate ,
Operator ,
Text_ID ,
Policy_Company,
Policy_Number ,
Override ,
CREATE_USER )
values ( '801010',
1,
:w_dob,
'MYUSER',
' ',
'01',
'6535435023150',
'1',
'myuser');
_x000D_
You can use py2exe as already answered and use Cython to convert your key .py
files in .pyc
, C compiled files, like .dll
in Windows and .so
on Linux.
It is much harder to revert than common .pyo
and .pyc
files (and also gain in performance!).
Had to merge this nice answers. It revealed something like that;
Extension;
Array.prototype.where = function (filter) {
var collection = this;
switch (typeof filter) {
case 'function':
return $.grep(collection, filter);
case 'object':
for (var property in filter) {
if (!filter.hasOwnProperty(property))
continue; // ignore inherited properties
collection = $.grep(collection, function (item) {
return item[property] === filter[property];
});
}
return collection.slice(0); // copy the array
// (in case of empty object filter)
default:
throw new TypeError('func must be either a' +
'function or an object of properties and values to filter by');
}
};
Usage;
masterTableView.get_dataItems().where(function (t) {
if (t.findElement("_invoiceGridCheckbox").checked) {
invoiceIds.push(t.getDataKeyValue("Id"));
}
});
If the string is 1 character long, just take that character. If the string is not 1 character long, it cannot be parsed into a character.
Here are the difference between POST, PUT and PATCH methods of a HTTP protocol.
POST
A HTTP.POST method always creates a new resource on the server. Its a non-idempotent request i.e. if user hits same requests 2 times it would create another new resource if there is no constraint.
http post method is like a INSERT query in SQL which always creates a new record in database.
Example: Use POST method to save new user, order etc where backend server decides the resource id for new resource.
PUT
In HTTP.PUT method the resource is first identified from the URL and if it exists then it is updated otherwise a new resource is created. When the target resource exists it overwrites that resource with a complete new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.
http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.
PUT request is idempotent i.e. hitting the same requests twice would update the existing recording (No new record created). In PUT method the resource id is decided by the client and provided in the request url.
Example: Use PUT method to update existing user or order.
PATCH
A HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.
http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.
Example: You could use PATCH method to update order status.
PATCH /api/users/40450236/order/10234557
Request Body: {status: 'Delivered'}
this error happens when you are going to bind a bounded service. so, sol should be :-
in service connection add serviceBound as below:
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// your work here.
serviceBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
unbind service onDestroy
if (serviceBound) {
unbindService(serviceConnection);
}
You can use the jQuery plugin PositionCalculator
That plugin has also included collision handling (flip), so the toolbar-like menu can be placed at a visible position.
$(".placeholder").on('mouseover', function() {
var $menu = $("#menu").show();// result for hidden element would be incorrect
var pos = $.PositionCalculator( {
target: this,
targetAt: "top right",
item: $menu,
itemAt: "top left",
flip: "both"
}).calculate();
$menu.css({
top: parseInt($menu.css('top')) + pos.moveBy.y + "px",
left: parseInt($menu.css('left')) + pos.moveBy.x + "px"
});
});
for that markup:
<ul class="popup" id="menu">
<li>Menu item</li>
<li>Menu item</li>
<li>Menu item</li>
</ul>
<div class="placeholder">placeholder 1</div>
<div class="placeholder">placeholder 2</div>
Here is the fiddle: http://jsfiddle.net/QrrpB/1657/
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.
Use vh attributes. It means viewport height and is a percentage. So height: 90vh would mean 90% of the viewport height. This works in most modern browsers.
Eg.
div {
height: 90vh;
}
You can forego the rest of your silly 100% stuff on the body.
If you have a header you can also do some fun things like take it into account by using the calc function in CSS.
Eg.
div {
height: calc(100vh - 50px);
}
This will give you 100% of the viewport height, minus 50px for your header.
Yeah, why not?
double someDouble = 12323.2;
int someInt = (int)someDouble;
Using the Convert
class works well too.
int someOtherInt = Convert.ToInt32(someDouble);
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
On Linux we can have these as exceptions, too.
Normally, when your program performs a segmentation fault, it is sent a SIGSEGV
signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead.
Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this:
try
{
*(int*) 0 = 0;
}
catch (std::exception& e)
{
std::cerr << "Exception caught : " << e.what() << std::endl;
}
Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.
There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Single check box
HTML code:
<form action="checkbox-form.php" method="post">
Do you need wheelchair access?
<input type="checkbox" name="formWheelchair" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
PHP Code:
<?php
if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes')
{
echo "Need wheelchair access.";
}
else
{
echo "Do not Need wheelchair access.";
}
?>
Check box group
<form action="checkbox-form.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
<input type="submit" name="formSubmit" value="Submit" />
/form>
<?php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
}
?>