Okay, this worked for me. Open the old solution/project as an administrator in Visual Studio 2010 and open the new or copied solution/project. As an administrator, remove the copied pfk file in the new Visual Studio 2010 solution/project and go to project properties and unselect it.
With both projects open, copy paste to the new one. Go to project properties and select Build. I opened and closed Visual Studio and also after removing from the new project built it before copying it from the old project and selecting it. I received the error at the start of this post first up when I copied the project and tried to build it.
You have to import the font in your stylesheet like this:
@font-face{
font-family: "Thonburi-Bold";
src: url('Thonburi-Bold.ttf'),
url('Thonburi-Bold.eot'); /* IE */
}
(Similar to Doin idea) To show what is being matched, I use this code
$keys = array_keys($_GET);
foreach($keys as $i=>$key){
echo "$i => $key <br>";
}
Save it to r.php on the server root and then do some tests in .htaccess
For example, i want to match urls that do not start with a language prefix
RewriteRule ^(?!(en|de)/)(.*)$ /r.php?$1&$2 [L] #$1&$2&...
RewriteRule ^(.*)$ /r.php?nomatch [L] #report nomatch and exit
Using Brilliant's idea, here's a solution that only (vertically) scrolls if the element is NOT currently visible. The idea is to get the bounding box of the viewport and the element to be displayed in browser-window coordinate space. Check if it's visible and if not, scroll by the required distance so the element is shown at the top or bottom of the viewport.
function ensure_visible(element_id)
{
// adjust these two to match your HTML hierarchy
var element_to_show = document.getElementById(element_id);
var scrolling_parent = element_to_show.parentElement;
var top = parseInt(scrolling_parent.getBoundingClientRect().top);
var bot = parseInt(scrolling_parent.getBoundingClientRect().bottom);
var now_top = parseInt(element_to_show.getBoundingClientRect().top);
var now_bot = parseInt(element_to_show.getBoundingClientRect().bottom);
// console.log("Element: "+now_top+";"+(now_bot)+" Viewport:"+top+";"+(bot) );
var scroll_by = 0;
if(now_top < top)
scroll_by = -(top - now_top);
else if(now_bot > bot)
scroll_by = now_bot - bot;
if(scroll_by != 0)
{
scrolling_parent.scrollTop += scroll_by; // tr.offsetTop;
}
}
For Laravel 5.4 and if you are using mix helper, use
<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}"></script>
<form method="post" action="servletName">
<input type="submit" id="btn1" name="btn1"/>
<input type="submit" id="btn2" name="btn2"/>
</form>
on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method
In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:
git submodule update --recursive --remote --merge
You may add --init
to initialize any uninitialized submodules and use --rebase
if you want to rebase instead of merge.
You need to commit the changes afterwards:
git add . && git commit -m 'Update submodules to latest revisions'
jsonObj.profile-id
is a subtraction expression (i.e. jsonObj.profile - id
).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
You can simply use the imutils package to do the rotation. it has two methods
more info you can get on this blog: https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/
i was looking for same solution in vb.net and i found this one and it's great.
however as @JohnOdom suggested a better way to handle the blanks space if previous one is larger than current one..
i make a function in vb.net and thought someone could get helped ..
here is my code:
Private Sub sPrintStatus(strTextToPrint As String, Optional boolIsNewLine As Boolean = False)
REM intLastLength is declared as public variable on global scope like below
REM intLastLength As Integer
If boolIsNewLine = True Then
intLastLength = 0
End If
If intLastLength > strTextToPrint.Length Then
Console.Write(Convert.ToChar(13) & strTextToPrint.PadRight(strTextToPrint.Length + (intLastLength - strTextToPrint.Length), Convert.ToChar(" ")))
Else
Console.Write(Convert.ToChar(13) & strTextToPrint)
End If
intLastLength = strTextToPrint.Length
End Sub
You need to use a ServerSocket
. You can find an explanation here.
have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings
Update: this is a piece of code I use:
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}
I got this error when I had an invalid Type for an entity property.
public Type ObjectType {get;set;}
When I removed the property the error stopped occurring.
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
I faced the same issue and spent almost 15-16 tiring hours to clean, rebuild, invalidate-cache, upgrade Idea from 16.3 to 17.2, all in vain. We have a Maven managed project and the build used to be successful but just couldn't navigate between declaration/implementations as Idea couldn't see the files.
After endlessly trying to fix this, it finally dawned to me that it's the IDEA settings causing all the headache. This is what I did (Windows system):
.iml
files from project directory del /s /q "C:\Dev\trunk\*.iml".idea
folders<user_home>\.IntelliJIdea2017.2\system
VOILAAAAAAAAAAAA...!! I hope this helps a poor soul in pain
I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.
writer.writerow(("ColName1", "ColName2", "ColName"))
for i in range(len(first_col_list)):
writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))
Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.
An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:
RRRR RGGG GGGB BBBB
You could then use bit masking to retrieve the colour components as follows:
const unsigned short redMask = 0xF800;
const unsigned short greenMask = 0x07E0;
const unsigned short blueMask = 0x001F;
unsigned short lightGray = 0x7BEF;
unsigned short redComponent = (lightGray & redMask) >> 11;
unsigned short greenComponent = (lightGray & greenMask) >> 5;
unsigned short blueComponent = (lightGray & blueMask);
You can use anonymous types for this, i.e.:
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new { pg, op }).SingleOrDefault();
This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new
{
PermissionName = pg,
ObjectPermission = op
}).SingleOrDefault();
This will enable you to say:-
if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();
For example :-)
Select the platform to be iPhone Simulator then click Build and Go. If it builds correctly then it will launch the simulator and run. If it does not build ok then it will indicate errors at the bottom of the window on the right hand side.
If you only have the app file then you would need to manually install that into the simulator. The simulator was not designed to be used this way, but I'm sure it would be possible, even if it was incredibly difficult.
If you have the source code (.proj .m .h etc) files then it should be a simple case of build and go.
c(df$x, df$y)
# returns: 26 21 20 34 29 28
if the particular order is important then:
M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28
Or more generally:
m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
q = c(q, m[i,])
}
# returns 26 34 21 29 20 28
LocalDate.of( 2014 , 2 , 11 )
If you insist on using the terrible old java.util.Date
class, convert from the modern java.time classes.
java.util.Date // Terrible old legacy class, avoid using. Represents a moment in UTC.
.from( // New conversion method added to old classes for converting between legacy classes and modern classes.
LocalDate // Represents a date-only value, without time-of-day and without time zone.
.of( 2014 , 2 , 11 ) // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
.atStartOfDay( // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" ) // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`.
) // Returns a `ZonedDateTime`.
.toInstant() // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
) // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.
If you want "easy", you should be using the new java.time package in Java 8 rather than the notoriously troublesome java.util.Date & .Calendar classes bundled with Java.
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes.
A LocalDate
class is offered by java.time to represent a date-only value without any time-of-day or time zone. You do need a time zone to determine a date, as a new day dawns earlier in Paris than in Montréal for example. The ZoneId
class is for time zones.
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );
Dump to console:
System.out.println ( "today: " + today + " in zone: " + zoneId );
today: 2015-11-26 in zone: Asia/Singapore
Or use a factory method to specify the year, month, day.
LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );
localDate: 2014-02-11
Or pass a month number 1-12 rather than a DayOfWeek
enum object.
LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );
A LocalDate
has no real meaning until you adjust it into a time zone. In java.time, we apply a time zone to generate a ZonedDateTime
object. That also means a time-of-day, but what time? Usually makes sense to go with first moment of the day. You might think that means the time 00:00:00.000
, but not always true because of Daylight Saving Time (DST) and perhaps other anomalies. Instead of assuming that time, we ask java.time to determine the first moment of the day by calling atStartOfDay
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
zdt: 2014-02-11T00:00+08:00[Asia/Singapore]
For back-end work (business logic, database, data storage & exchange) we usually use UTC time zone. In java.time, the Instant
class represents a moment on the timeline in UTC. An Instant object can be extracted from a ZonedDateTime by calling toInstant
.
Instant instant = zdt.toInstant();
instant: 2014-02-10T16:00:00Z
You should avoid using java.util.Date
class entirely. But if you must interoperate with old code not yet updated for java.time, you can convert back-and-forth. Look to new conversion methods added to the old classes.
java.util.Date d = java.util.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda-Time library is now in maintenance mode, and advises migration to the java.time classes. I am leaving this section in place for history.
For one thing, Joda-Time uses sensible numbering so February is 2
not 1
. Another thing, a Joda-Time DateTime truly knows its assigned time zone unlike a java.util.Date which seems to have time zone but does not.
And don't forget the time zone. Otherwise you'll be getting the JVM’s default.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );
java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );
Dump to console…
System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
When run…
dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT
If you need to convert to a java.util.Date for use with other classes…
java.util.Date date = dateTimeSingapore.toDate();
You can use one of the many Arrays.binarySearch()
methods. Keep in mind that the array must be sorted first.
I solved because I have the same problem and I give you some clues:
1.- As @eggyal comments
mydatabase != mydatabasename
So, check your database name
2.- if in your file, you want create database, you can't set database that you not create yet:
mysql -uroot -pmypassword mydatabase<mydatabase.sql;
change it for:
mysql -uroot -pmypassword <mydatabase.sql;
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution
approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.
Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.
Not sure if you can open them invisibly in the current excel instance
You can open a new instance of excel though, hide it and then open the workbooks
Dim app as New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(fileName)
'
' Do what you have to do
'
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
As others have posted, make sure you clean up after you are finished with any opened workbooks
Also adding other Scenarios where you may see these Errors
First Check you compiler version, Download latest Typescript compiler to support ES6 syntaxes
typescript still produces output even with typing errors this doesn't actually block development,
When you see these errors Check for Syntaxes in initialization or when Calling these methods or variables,
Check whether the parameters of the functions are of wrong data Type,you initialized as 'string' and assigning a 'boolean' or 'number'
For Example
1.
private errors: string;
//somewhere in code you assign a boolean value to (string)'errors'
this.errors=true
or
this.error=5
2.
private values: Array<number>;
this.values.push(value); //Argument of type 'X' is not assignable to parameter of type 'X'
The Error message here is because the Square brackets for Array Initialization is missing, It works even without it, but VS Code red alerts.
private values: Array<number> = [];
this.values.push(value);
Note:
Remember that Javascript typecasts according to the value assigned, So typescript notifies them but the code executes even with these errors highlighted in VS Code
Ex:
var a=2;
typeof(a) // "number"
var a='Ignatius';
typeof(a) // "string"
Another Solution
if your txt file looks like this: mouse snake cat lizard wolf dog
you could reverse this file by simply using array indexing in python '''
contents=[]
def tail(contents,n):
with open('file.txt') as file:
for i in file.readlines():
contents.append(i)
for i in contents[:n:-1]:
print(i)
tail(contents,-5)
result: dog wolf lizard cat
And if you have this problem in slider or slideshow you must use jquery.easing.1.3
:
<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
I had a maven project giving me same thing. It showed that it couldnt find the jar with that version (dependency) and I knew its there and is correct -
So, for me the solution was to 1 delete the local repository. 2 Clean the project. 3 Disable the maven nature. 4 Generate eclipse artifacts and 5 re-configure as maven project.
(in order)
You can manually delete the registry key for your service, located at HKLM\SYSTEM\CurrentControlSet\Services
, after that you won't see the service in service control manager (need to refresh or reopen to see the change), and you can reinstall the service as usual.
Just style the border of the rows:
?table tr {
border-bottom: 1px solid black;
}?
table tr:last-child {
border-bottom: none;
}
Here is a fiddle.
Edited as mentioned by @pkyeck. The second style avoids the line under the last row. Maybe you are looking for this.
' VB.NET - Code
Function CheckLineSegmentCircleIntersection(x1 As Double, y1 As Double, x2 As Double, y2 As Double, xc As Double, yc As Double, r As Double) As Boolean
Static xd As Double = 0.0F
Static yd As Double = 0.0F
Static t As Double = 0.0F
Static d As Double = 0.0F
Static dx_2_1 As Double = 0.0F
Static dy_2_1 As Double = 0.0F
dx_2_1 = x2 - x1
dy_2_1 = y2 - y1
t = ((yc - y1) * dy_2_1 + (xc - x1) * dx_2_1) / (dy_2_1 * dy_2_1 + dx_2_1 * dx_2_1)
If 0 <= t And t <= 1 Then
xd = x1 + t * dx_2_1
yd = y1 + t * dy_2_1
d = Math.Sqrt((xd - xc) * (xd - xc) + (yd - yc) * (yd - yc))
Return d <= r
Else
d = Math.Sqrt((xc - x1) * (xc - x1) + (yc - y1) * (yc - y1))
If d <= r Then
Return True
Else
d = Math.Sqrt((xc - x2) * (xc - x2) + (yc - y2) * (yc - y2))
If d <= r Then
Return True
Else
Return False
End If
End If
End If
End Function
Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.
Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.
On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.
import sys
import os
def main():
print os.name
if __name__ == '__main__':
try:
if sys.argv[1] == 'deploy':
import paramiko
# Connect to remote host
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('remote_hostname_or_IP', username='john', password='secret')
# Setup sftp connection and transmit this script
sftp = client.open_sftp()
sftp.put(__file__, '/tmp/myscript.py')
sftp.close()
# Run the transmitted script remotely without args and show its output.
# SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
stdout = client.exec_command('python /tmp/myscript.py')[1]
for line in stdout:
# Process each line in the remote output
print line
client.close()
sys.exit(0)
except IndexError:
pass
# No cmd-line args provided, run script normally
main()
Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.
FYI, I put together a JSFiddle of this using the $cookieStore
, two controllers, a $rootScope
, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...
The gist of it is:
Javascript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
$scope.bump = function () {
var lastVal = $cookieStore.get('lastValue');
if (!lastVal) {
$rootScope.lastVal = 1;
} else {
$rootScope.lastVal = lastVal + 1;
}
$cookieStore.put('lastValue', $rootScope.lastVal);
}
});
myApp.controller('ShowerCtrl', function () {
});
HTML
<div ng-app="myApp">
<div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
<div id="button-holder" ng-controller="CookieCtrl">
<button ng-click="bump()">Bump!</button>
</div>
</div>
Real answers:
http://cutycapt.sourceforge.net/
http://iecapt.sourceforge.net/
http://www.websitescreenshots.com/
http://khtml2png.sourceforge.net/
https://htmlcsstoimage.com/ (Uses Google Chrome)
https://gofullpage.com/ - Full Page Screen Capture (Chrome extension) - see this superuser answer for more info
(Don't know of one to use Mozilla's renderer, though.)
To me the problem what that I had to check the box "Import maven projects automatically" under Setting> Maven>Importing
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
The easiest way is:
<h:outputText value=" " />
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
An alternative way to order a List is using the Collections framework;
in this case using the SortedSet (the bean in the list should implement Comparable, so Double is ok):
List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);
In general, to order by an attribute of a bean in the list,put all the elements of the list in a SortedMap, using as a key the attribute, then get the values() from the SortedMap (the attribute should implement Comparable):
List<Bean> testList;
...
SortedMap<AttributeType,Bean> sortedMap= new TreeMap<AttributeType, Bean>();
for(Bean bean : testList) {
sortedMap.put(bean.getAttribute(),bean);
}
orderedList=new ArrayList(sortedMap.values());
The correct result for me with SQL Server 2017:
USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO
RECONFIGURE
GO
EXEC sp_configure 'clr enabled' -- make sure it took
GO
USE <DATABASE>
GO
EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO
ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;
From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675
Applications -> XAMPP -> htdocs This is the place where you should put your files for the website you're building.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
Javascript solution for your case:
console.log(unique(standardsList));
function unique(obj){
var uniques=[];
var stringify={};
for(var i=0;i<obj.length;i++){
var keys=Object.keys(obj[i]);
keys.sort(function(a,b) {return a-b});
var str='';
for(var j=0;j<keys.length;j++){
str+= JSON.stringify(keys[j]);
str+= JSON.stringify(obj[i][keys[j]]);
}
if(!stringify.hasOwnProperty(str)){
uniques.push(obj[i]);
stringify[str]=true;
}
}
return uniques;
}
.complete
+ callback
This is a standards compliant method without extra dependencies, and waits no longer than necessary:
var img = document.querySelector('img')
function loaded() {
alert('loaded')
}
if (img.complete) {
loaded()
} else {
img.addEventListener('load', loaded)
img.addEventListener('error', function() {
alert('error')
})
}
Source: http://www.html5rocks.com/en/tutorials/es6/promises/
You could have two different versions of Python and pip.
Try to:
pip2 install --upgrade pip
and then pip2 install -r requirements.txt
Or pip3
if you are on newer Python version.
Last-Modified : The last modified date for the requested object
If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.
ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.
If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.
the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:
the server will return 304 when the if statement is False, and browser will use cache.
Toolbar -> Settings -> Compiler
Selected compiler
drop-down menu, make sure GNU GCC Compiler
is selectedcompiler settings
tab and then the compiler flags
tab underneathHave g++ follow the C++11 ISO C++ language standard [-std=c++11]
" is checkedOK
to saveIf you getting a blank screen, that may be because of 2 reasons:
Browser blocking the Frames from being displayed. In some browsers the frames are considered as unsafe. To overcome this you can launch the frameless version of phpPgAdmin by
http://-your-domain-name-/intro.php
You have enabled a security feature in Nginx for X-Frame-Options try disabling it.
// aspx.cs
// Load CheckBoxList selected items into ListBox
int status = 1;
foreach (ListItem s in chklstStates.Items )
{
if (s.Selected == true)
{
if (ListBox1.Items.Count == 0)
{
ListBox1.Items.Add(s.Text);
}
else
{
foreach (ListItem list in ListBox1.Items)
{
if (list.Text == s.Text)
{
status = status * 0;
}
else
{
status = status * 1;
}
}
if (status == 0)
{ }
else
{
ListBox1.Items.Add(s.Text);
}
status = 1;
}
}
}
}
Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.
What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.
As I am not master in js but I myself write code which check if user is at bottom. If user is at bottom then chat page will automatically scroll with new message. and if user scroll up then page will not auto scroll to bottom..
JS code -
var checkbottom;
jQuery(function($) {
$('.chat_screen').on('scroll', function() {
var check = $(this).scrollTop() + $(this).innerHeight() >= $(this)
[0].scrollHeight;
if(check) {
checkbottom = "bottom";
}
else {
checkbottom = "nobottom";
}
})
});
window.setInterval(function(){
if (checkbottom=="bottom") {
var objDiv = document.getElementById("chat_con");
objDiv.scrollTop = objDiv.scrollHeight;
}
}, 500);
html code -
<div id="chat_con" class="chat_screen">
</div>
The above error run the commend line\
please change the command $ node server it's working and server is started
CakePHP has two methods for getting the last inserted id: Model::getLastInsertID()
and Model::getInsertID()
.
Actually these methods are identical so it really doesn't matter which method you use.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
This methods can be found in cake/libs/model/model.php
on line 2768
I wanted the same answer and I didnt want to use goto
. So I used the following example (from learnpythonthehardway)
def sample():
print "This room is full of gold how much do you want?"
choice = raw_input("> ")
how_much = int(choice)
if "0" in choice or "1" in choice:
check(how_much)
else:
print "Enter a number with 0 or 1"
sample()
def check(n):
if n < 150:
print "You are not greedy, you win"
exit(0)
else:
print "You are nuts!"
exit(0)
select *
into #TempTable
from SomeTale
select *
from #TempTable
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
My issue was that I was on a machine with node version 0.12.2
, but that had an old 1.x.x
version of npm
. Be sure to update your version of npm: sudo npm install -g npm
Once that is done, remove any existing node-sass
and reinstall it via npm.
Here is a simpler solution:
inds = pd.isnull(df).any(1).nonzero()[0]
In [9]: df
Out[9]:
0 1
0 0.450319 0.062595
1 -0.673058 0.156073
2 -0.871179 -0.118575
3 0.594188 NaN
4 -1.017903 -0.484744
5 0.860375 0.239265
6 -0.640070 NaN
7 -0.535802 1.632932
8 0.876523 -0.153634
9 -0.686914 0.131185
In [10]: pd.isnull(df).any(1).nonzero()[0]
Out[10]: array([3, 6])
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
If you prefer PERL, there is a short PERL script (originally written by Larry Wall, the creator of PERL) that will do exactly what you want here: tips.webdesign10.com/files/rename.pl.txt.
For your example the following should do the trick:
rename.pl 's/html/txt/' *.html
long/int to the byte array looks like exact purpose of struct.pack
. For long integers that exceed 4(8) bytes, you can come up with something like the next:
>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
parts.append(i & limit)
i >>= 32
>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'
>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L
The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!
If you don't have one, you can get it for free on the Google Developers Website.
Here is what I typically do when a mysql slave gets out of sync. I have looked at mk-table-sync but thought the Risks section was scary looking.
On Master:
SHOW MASTER STATUS
The outputted columns (File, Position) will be of use to us in a bit.
On Slave:
STOP SLAVE
Then dump the master db and import it to the slave db.
Then run the following:
CHANGE MASTER TO
MASTER_LOG_FILE='[File]',
MASTER_LOG_POS=[Position];
START SLAVE;
Where [File] and [Position] are the values outputted from the "SHOW MASTER STATUS" ran above.
Hope this helps!
I was looking for an integer value in named column, so I did the below:
int index = dgv_myDataGridView.CurrentCell.RowIndex;
int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)
The good thing about this is that the column can be in any position in the grid view and you will still get the value.
Cheers
With Eclipse and Windows:
you have to copy 2 files - xxxPROJECTxxx.properties - log4j.properties here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib
This is for windows:
For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".
@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal
This script is located in "mygrapher". To run things, I would get into my command prompt, then do:
>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)
Just wanted to share this for web developers:
security-guide-for-developers
https://github.com/FallibleInc/security-guide-for-developers
class TableViewCell: UITableViewCell {
@IBOutlet weak var oneButton: UIButton!
@IBOutlet weak var twoButton: UIButton!
}
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)
return cell
}
func oneTapped(_ sender: Any?) {
print("Tapped")
}
func twoTapped(_ sender: Any?) {
print("Tapped")
}
}
If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.
e.g. run the shell command "env > /tmp/headers" from within your script
Then, look for the environment variables that start with HTTP_...
You will see lines like:
HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0
Each of those represents a request header.
Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.
Some of the other answers mention that Python 3 eliminated 2.x's range
and renamed 2.x's xrange
to range
. However, unless you're using 3.0 or 3.1 (which nobody should be), it's actually a somewhat different type.
As the 3.1 docs say:
Range objects have very little behavior: they only support indexing, iteration, and the
len
function.
However, in 3.2+, range
is a full sequence—it supports extended slices, and all of the methods of collections.abc.Sequence
with the same semantics as a list
.*
And, at least in CPython and PyPy (the only two 3.2+ implementations that currently exist), it also has constant-time implementations of the index
and count
methods and the in
operator (as long as you only pass it integers). This means writing 123456 in r
is reasonable in 3.2+, while in 2.7 or 3.1 it would be a horrible idea.
* The fact that issubclass(xrange, collections.Sequence)
returns True
in 2.6-2.7 and 3.0-3.1 is a bug that was fixed in 3.2 and not backported.
I had this problem tonight with android and after looking at the javadoc solutions I came up with this real working solution just for people like me that need a little more than a javadoc explanation.
Here's a working example with an actual interface using android java. It checks the activity that called implemented the AboutDialogListener interface before attempting to cast the AboutDialogListener field.
public class About extends DialogFragment implements OnClickListener,
OnCheckedChangeListener {
public static final String FIRST_RUN_ABOUT = "com.gosylvester.bestrides.firstrunabout";
public interface AboutDialogListener {
void onFinishEditDialog(Boolean _Checked);
}
private AboutDialogListener adl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Activity a = this.getActivity();
if (AboutDialogListener.class.isInstance(a)) {
adl = (AboutDialogListener) a;
}
}
... Later I check if the field adl is !null before calling the interface
@Override
public void onStop() {
super.onStop();
sharedPref.edit().putBoolean(About.FIRST_RUN_ABOUT, _Checked).commit();
// if there is an interface call it.
if (adl != null) {
adl.onFinishEditDialog(is_Checked());
}
}
Use chooseOkOnNextConfirmation() to dismiss the alert and getAlert() to verify that it has been shown (and optionally grab its text for verification).
selenium.chooseOkOnNextConfirmation(); // prepares Selenium to handle next alert
selenium.click(locator);
String alertText = selenium.getAlert(); // verifies that alert was shown
assertEquals("This is a popup window", alertText);
...
Based on this comment from the OP, "I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment", I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell's alignment property directly, only that cell is affected.
What if you just wrap your code into function?
So this:
cd ~/documents
mkdir test
echo "useless script" > about.txt
Becomes this:
CommentedOutBlock() {
cd ~/documents
mkdir test
echo "useless script" > about.txt
}
def _create_type(meta, name, attrs):
type_name = f'{name}Type'
type_attrs = {}
for k, v in attrs.items():
if type(v) is _ClassPropertyDescriptor:
type_attrs[k] = v
return type(type_name, (meta,), type_attrs)
class ClassPropertyType(type):
def __new__(meta, name, bases, attrs):
Type = _create_type(meta, name, attrs)
cls = super().__new__(meta, name, bases, attrs)
cls.__class__ = Type
return cls
class _ClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, owner):
if self in obj.__dict__.values():
return self.fget(obj)
return self.fget(owner)
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
return self.fset(obj, value)
def setter(self, func):
self.fset = func
return self
def classproperty(func):
return _ClassPropertyDescriptor(func)
class Bar(metaclass=ClassPropertyType):
__bar = 1
@classproperty
def bar(cls):
return cls.__bar
@bar.setter
def bar(cls, value):
cls.__bar = value
bar = Bar()
assert Bar.bar==1
Bar.bar=2
assert bar.bar==2
nbar = Bar()
assert nbar.bar==2
@Debasish Sahu, your answer is an answer to another question, namely: how to know which button (or any other control) was clicked when there is a common handler for a couple of controls? So I'm giving an answer to this question how I usually do it, almost the same as yours, but note that also works without type conversion when it handles the same type of Controls:
Private Sub btn_done_clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim selectedBtn As Button = sender
MsgBox("you have clicked button " & selectedBtn.Name)
End Sub
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
On windows 7, find
C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default
Find your color scheme file, open it, and find lineHighlight
.
Ex:
<key>lineHighlight</key>
<string>#ccc</string>
replace #ccc
with your preferred background color.
// logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
?>
You can use the UpdateProgress control:
Another way to look at this. Check out the details of the exception:
In [49]: try:
...: open('file.DNE.txt')
...: except Exception as e:
...: print(dir(e))
...:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']
There are lots of "things" to access using the 'as e' syntax.
This code was solely meant to show the details of this instance.
It's fine to manually select each number for a small set of numbers like in your example, but for larger collections you can do a regex search which will do the work for you.
Ctrl + F will open the search bar.
Regex searches are enabled by clicking the ".*" button on the far left.
Type in "\d+" to search for all occurrences of 1 or more digits. Clicking the "Find All" button will select each of these numbers separately.
Then you can use Ctrl + Shift + L to convert the selection into multiple cursors. From here you can do as you like.
If you only have one line of text and your div has a fixed height, you can do this:
div {
line-height: (2*height - font-size);
text-align: right;
}
See fiddle.
$full_path = WP_PLUGIN_URL . '/'. str_replace( basename( __FILE__ ), "", plugin_basename(__FILE__) );
This link may help: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories.
Using an open source program call Send Mail, you can send via wamp rather easily actually. I'm still setting it up, but here's a great tutorial by jo jordan. Takes less than 2 mins to setup.
Just tried it and it worked like a charm! Once I uncommented the error log and found out that it was stalling on the pop3 authentication, I just removed that and it sent nicely. Best of luck!
The best way is to close the session is: if there is no response for that session after particular interval of time. then close. Please see this post and I hope it will resolve the issue. "How to change the session timeout in PHP?"
Assuming doc
is your instance of org.w3c.dom.Document
:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
Unfortuantely, as div
elements can't be direct descendants of table
elements, the way I know to do this is to apply the CSS rules you want to each tr
element that you want to apply it to.
<table>
<tr><th>Test Table</th><tr>
<tr><td>123456789</td><tr>
<tr style="display: none; other-property: value;"><td>123456789</td><tr>
<tr style="display: none; other-property: value;"><td>123456789</td><tr>
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
</table>
If you have more than one CSS rule to apply to the rows in question, give the applicable rows a class
instead and offload the rules to external CSS.
<table>
<tr><th>Test Table</th><tr>
<tr><td>123456789</td><tr>
<tr class="something"><td>123456789</td><tr>
<tr class="something"><td>123456789</td><tr>
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
</table>
It seems to me that what you really want, is to customize the look of the captions. This is most easily done using the caption
package. For instructions how to use this package, see the manual (PDF). You would probably need to create your own custom caption format, as described in chapter 4 in the manual.
Edit: Tested with MikTex:
\documentclass{report}
\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}
% This concludes the preamble
\begin{document}
\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
goes().the().code()
}
\end{lstlisting}
\end{document}
Result:
You can use numpy.logical_not
to invert the boolean array returned by isin
:
In [63]: s = pd.Series(np.arange(10.0))
In [64]: x = range(4, 8)
In [65]: mask = np.logical_not(s.isin(x))
In [66]: s[mask]
Out[66]:
0 0
1 1
2 2
3 3
8 8
9 9
As given in the comment by Wes McKinney you can also use
s[~s.isin(x)]
I too had the same problem.
I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.
Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2
This worked for me:
1-
$ npm install -g n
$ n 9.11.2
2-
delete 'node_modules' from the route directory
3-
$ npm install
Still not sure how node/purgecss worked prior to updating.. but this did the trick.
You must do the following command:
sort -n -k1 filename
That should do it :)
['color', 'height'].reduce((a,b) => (a[b]=elmo[b],a), {})
let subset= (obj,keys)=> keys.reduce((a,b)=> (a[b]=obj[b],a),{});_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
let elmo = { _x000D_
color: 'red',_x000D_
annoying: true,_x000D_
height: 'unknown',_x000D_
meta: { one: '1', two: '2'}_x000D_
};_x000D_
_x000D_
console.log( subset(elmo, ['color', 'height']) );
_x000D_
Mockito cannot capture static methods, but since Mockito 2.14.0 you can simulate it by creating invocation instances of static methods.
Example (extracted from their tests):
public class StaticMockingExperimentTest extends TestBase {
Foo mock = Mockito.mock(Foo.class);
MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
Method staticMethod;
InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return null;
}
};
@Before
public void before() throws Throwable {
staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);
}
@Test
public void verify_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
handler.handle(invocation);
//verify staticMethod on mock
//Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
//1. Call standard 'verify' method. Internally, it will add verificationMode to the thread local state.
// Effectively, we indicate to Mockito that right now we are about to verify a method call on this mock.
verify(mock);
//2. Create the invocation instance using the new public API
// Mockito cannot capture static methods but we can create an invocation instance of that static invocation
Invocation verification = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
//3. Make Mockito handle the static method invocation
// Mockito will find verification mode in thread local state and will try verify the invocation
handler.handle(verification);
//verify zero times, method with different argument
verify(mock, times(0));
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
handler.handle(differentArg);
}
@Test
public void stubbing_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"foo");
handler.handle(invocation);
//register stubbing
when(null).thenReturn("hey");
//validate stubbed return value
assertEquals("hey", handler.handle(invocation));
assertEquals("hey", handler.handle(invocation));
//default null value is returned if invoked with different argument
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
assertEquals(null, handler.handle(differentArg));
}
static class Foo {
private final String arg;
public Foo(String arg) {
this.arg = arg;
}
public static String staticMethod(String arg) {
return "";
}
@Override
public String toString() {
return "foo:" + arg;
}
}
}
Their goal is not to directly support static mocking, but to improve its public APIs so that other libraries, like Powermockito, don't have to rely on internal APIs or directly have to duplicate some Mockito code. (source)
Disclaimer: Mockito team thinks that the road to hell is paved with static methods. However, Mockito's job is not to protect your code from static methods. If you don’t like your team doing static mocking, stop using Powermockito in your organization. Mockito needs to evolve as a toolkit with an opinionated vision on how Java tests should be written (e.g. don't mock statics!!!). However, Mockito is not dogmatic. We don't want to block unrecommended use cases like static mocking. It's just not our job.
const arrDiff = [
{
label: 'second',
value: 1000,
},
{
label: 'minute',
value: 1000 * 60,
},
{
label: 'hour',
value: 1000 * 60 * 60,
},
{
label: 'day',
value: 1000 * 60 * 60 * 24,
},
{
label: 'year',
value: 1000 * 60 * 60 * 24 * 365,
},
];
function diff(date) {
let result = { label: '', value: '' };
const value = Date.now() - date;
for (let obj of arrDiff) {
let temp = Math.round(value / obj.value);
if (temp === 0) {
break;
} else
result = {
value: temp,
label: obj.label,
};
}
return result;
}
const postDate = new Date('2020-12-17 23:50:00+0700');
console.log(diff(postDate));
$("#co").click(function(){
$(this).css({"backgroundColor" : "blue"});
});
Is there a difference between
==
andis
in Python?
Yes, they have a very important difference.
==
: check for equality - the semantics are that equivalent objects (that aren't necessarily the same object) will test as equal. As the documentation says:
The operators <, >, ==, >=, <=, and != compare the values of two objects.
is
: check for identity - the semantics are that the object (as held in memory) is the object. Again, the documentation says:
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object. Object identity is determined using theid()
function.x is not y
yields the inverse truth value.
Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,
a is b
is the same as:
id(a) == id(b)
where id
is the builtin function that returns an integer that "is guaranteed to be unique among simultaneously existing objects" (see help(id)
) and where a
and b
are any arbitrary objects.
You should use these comparisons for their semantics. Use is
to check identity and ==
to check equality.
So in general, we use is
to check for identity. This is usually useful when we are checking for an object that should only exist once in memory, referred to as a "singleton" in the documentation.
Use cases for is
include:
None
Usual use cases for ==
include:
The general use case, again, for ==
, is the object you want may not be the same object, instead it may be an equivalent one
PEP 8, the official Python style guide for the standard library also mentions two use-cases for is
:
Comparisons to singletons like
None
should always be done withis
oris not
, never the equality operators.Also, beware of writing
if x
when you really meanif x is not None
-- e.g. when testing whether a variable or argument that defaults toNone
was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
If is
is true, equality can usually be inferred - logically, if an object is itself, then it should test as equivalent to itself.
In most cases this logic is true, but it relies on the implementation of the __eq__
special method. As the docs say,
The default behavior for equality comparison (
==
and!=
) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).
and in the interests of consistency, recommends:
Equality comparison should be reflexive. In other words, identical objects should compare equal:
x is y
impliesx == y
We can see that this is the default behavior for custom objects:
>>> class Object(object): pass
>>> obj = Object()
>>> obj2 = Object()
>>> obj == obj, obj is obj
(True, True)
>>> obj == obj2, obj is obj2
(False, False)
The contrapositive is also usually true - if somethings test as not equal, you can usually infer that they are not the same object.
Since tests for equality can be customized, this inference does not always hold true for all types.
A notable exception is nan
- it always tests as not equal to itself:
>>> nan = float('nan')
>>> nan
nan
>>> nan is nan
True
>>> nan == nan # !!!!!
False
Checking for identity can be much a much quicker check than checking for equality (which might require recursively checking members).
But it cannot be substituted for equality where you may find more than one object as equivalent.
Note that comparing equality of lists and tuples will assume that identity of objects are equal (because this is a fast check). This can create contradictions if the logic is inconsistent - as it is for nan
:
>>> [nan] == [nan]
True
>>> (nan,) == (nan,)
True
The question is attempting to use is
to compare integers. You shouldn't assume that an instance of an integer is the same instance as one obtained by another reference. This story explains why.
A commenter had code that relied on the fact that small integers (-5 to 256 inclusive) are singletons in Python, instead of checking for equality.
Wow, this can lead to some insidious bugs. I had some code that checked if a is b, which worked as I wanted because a and b are typically small numbers. The bug only happened today, after six months in production, because a and b were finally large enough to not be cached. – gwg
It worked in development. It may have passed some unittests.
And it worked in production - until the code checked for an integer larger than 256, at which point it failed in production.
This is a production failure that could have been caught in code review or possibly with a style-checker.
Let me emphasize: do not use is
to compare integers.
You need to manually create the bundle for a debug build.
Bundle debug build:
#React-Native 0.59
react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/src/main/assets/index.android.bundle --assets-dest ./android/app/src/main/res
#React-Native 0.49.0+
react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug
#React-Native 0-0.49.0
react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug
Then to build the APK's after bundling:
$ cd android
#Create debug build:
$ ./gradlew assembleDebug
#Create release build:
$ ./gradlew assembleRelease #Generated `apk` will be located at `android/app/build/outputs/apk`
P.S. Another approach might be to modify gradle scripts.
Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,
You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s
to pattern: \[^\w\d\s]
In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.
To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.
>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']
To remove the repeated words, you can use a set {} instead of a list []
>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']
or apply list(set(all_words))
>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']
Most of the above solutions assume that the parent DateGridView
has .AutoSizeMode
not equal to Fill
. If you set the .AutoSizeMode
for the grid to be Fill
, you need to set the AutoSizeMode for each column to be None
if you want to fix a particular column width (and let the other columns Fill). I found a weird MS exception regarding a null object if you change a Column Width and the .AutoSizeMode
is not None
first.
This works
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
This throws a null exception regarding some internal object regarding setting border thickness.
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
// chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
I use package hyphenat
and then write compound words like Finnish word Internet-yhteys (Eng. Internet connection) as Internet\hyp yhteys
. Looks goofy but seems to be the most elegant way I've found.
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF
You can use this method to draw polyline on googleMap
// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.RED);
polyOptions.width(5);
polyOptions.addAll(list);
googleMap.clear();
googleMap.addPolyline(polyOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : list) {
builder.include(latLng);
}
final LatLngBounds bounds = builder.build();
//BOUND_PADDING is an int to specify padding of bound.. try 100.
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
googleMap.animateCamera(cu);
}
You need to add this line in your gradle in case you haven't.
compile 'com.google.android.gms:play-services-maps:8.4.0'
Try:
adb shell ip addr show rmnet0
It will return something like that:
3: rmnet0: <UP,LOWER_UP> mtu 1500 qdisc htb state UNKNOWN qlen 1000
link/[530]
inet 172.22.1.100/29 scope global rmnet0
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc/64 scope global dynamic
valid_lft forever preferred_lft forever
inet6 fe80::8099:af3f:2af2:8bc/64 scope link
valid_lft forever preferred_lft forever
This part is your IPV4 assigned by the operator
inet 172.22.1.100
This part is your IPV6 assigned by the operator
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
Well, if you like the developer way, Visual Studio Code allows you to specify the different file types for the tabSize
. Here is the example of my settings.json
with default four spaces and JavaScript/JSON two spaces:
{
// I want my default to be 4, but JavaScript/JSON to be 2
"editor.tabSize": 4,
"[javascript]": {
"editor.tabSize": 2
},
"[json]": {
"editor.tabSize": 2
},
// This one forces the tab to be **space**
"editor.insertSpaces": true
}
PS: Well, if you do not know how to open this file (specially in a new version of Visual Studio Code), you can:
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.
The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
Recently I got same problem with existing repository.when I try to fetch from upstream not able Fetched object and got problems eclipse: cannot open git-upload-pack.
for me following solution work after adding TLS version in eclipse.ini file
Dhttps.protocols=TLSv1.1,TLSv1.2
For java7 need to add TLSv1.1 and for java8 need to TLSv1.2
Note: Need to restart eclipse once above configuration added.
Something like this works:
input + label::after {_x000D_
content: 'click my input';_x000D_
color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
content: 'not valid yet';_x000D_
color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
content: 'looks good';_x000D_
color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
Then add some floats or positioning to order stuff.
With VSCode you can find the merge conflicts easily with the following UI.
(if you do not have the topbar, set "editor.codeLens": true
in User Preferences)
It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD
.
If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming
, etc.
Since you're using JPA, use the Lob
annotation (and optionally the Column
annotation). Here is what the JPA specification says about it:
9.1.19 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with theBasic
annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
So declare something like this:
@Lob
@Column(name="CONTENT", length=512)
private String content;
What system are you on? It looks like you have a system with X11, but the DISPLAY environment variable was not properly set. Try executing the following command and then rerunning your program:
export DISPLAY=localhost:0
Your SELECT
statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT
table with the given STUDENT_ID
and SECTION_ID
. You may want to try putting some DBMS_OUTPUT.PUT_LINE
statements before you run the query, printing the values of v_student_id
and v_section_id
. They may not be containing what you expect them to contain.
For System.Timers.Timer:
See Brian Gideon's answer below
MSDN Documentation on Timers states:
The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.
So indeed the timer elapses on a different thread.
You can execute your task in a different thread. threading.Timer
will let you execute a given callback once after some time has elapsed, if you want to execute your task, for example, as long as the callback returns True
(this is actually what glib.timeout_add
provides, but you might not have it installed in windows) or until you cancel it, you can use this code:
import logging, threading, functools
import time
logging.basicConfig(level=logging.NOTSET,
format='%(threadName)s %(message)s')
class PeriodicTimer(object):
def __init__(self, interval, callback):
self.interval = interval
@functools.wraps(callback)
def wrapper(*args, **kwargs):
result = callback(*args, **kwargs)
if result:
self.thread = threading.Timer(self.interval,
self.callback)
self.thread.start()
self.callback = wrapper
def start(self):
self.thread = threading.Timer(self.interval, self.callback)
self.thread.start()
def cancel(self):
self.thread.cancel()
def foo():
logging.info('Doing some work...')
return True
timer = PeriodicTimer(1, foo)
timer.start()
for i in range(2):
time.sleep(2)
logging.info('Doing some other work...')
timer.cancel()
Example output:
Thread-1 Doing some work...
Thread-2 Doing some work...
MainThread Doing some other work...
Thread-3 Doing some work...
Thread-4 Doing some work...
MainThread Doing some other work...
Note: The callback isn't executed every interval execution. Interval is the time the thread waits between the callback finished the last time and the next time is called.
I have used Open source Web Design in the past. They have quite a few css themes, don't know about ASP.Net
IF the array is associative and keyed correctly, it would probably be easier to turn it into xml first. Something like:
function array2xml ($array_item) {
$xml = '';
foreach($array_item as $element => $value)
{
if (is_array($value))
{
$xml .= "<$element>".array2xml($value)."</$element>";
}
elseif($value == '')
{
$xml .= "<$element />";
}
else
{
$xml .= "<$element>".htmlentities($value)."</$element>";
}
}
return $xml;
}
$simple_xml = simplexml_load_string(array2xml($assoc_array));
The other route would be to create your basic xml first, like
$simple_xml = simplexml_load_string("<array></array>");
and then for each part of your array, use something similar to my text creating loop and instead use the simplexml functions "addChild" for each node of the array.
I'll try that out later and update this post with both versions.
Use the length()
method in the File
class. From the javadocs:
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
UPDATED Nowadays we should use the Files.size()
method:
Paths path = Paths.get("/path/to/file");
long size = Files.size(path);
For the second part of the question, straight from File
's javadocs:
getUsableSpace()
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname
getTotalSpace()
Returns the size of the partition named by this abstract pathname
getFreeSpace()
Returns the number of unallocated bytes in the partition named by this abstract path name
I modified /etc/php.ini
[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone =('Asia/kolkata')
and now working fine.
Vipin Pal
parseFloat($(this).css('marginBottom'))
Even if marginBottom defined in em, the value inside of parseFloat above will be in px, as it's a calculated CSS property.
If you want to effect on the menu options for changing the locale immediately.You have to do like this.
//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//1.Here you can add your locale settings .
//2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
menu.clear();
onCreateOptionsMenu(menu);
return super.onMenuOpened(featureId, menu);
}
You can generate scriptof the stored proc's as depicted in other answers. Once the script have been generated, you can use sqlcmd
to execute them against target DB like
sqlcmd -S <server name> -U <user name> -d <DB name> -i <script file> -o <output log file>
Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.
But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.
There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.
First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty()
. That part is cross-platform.
For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin
. In Python 3, this just means sys.stdin.buffer.raw.read(1)
and sys.stdin.buffer.raw.readline()
. However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding)
on the results; you can wrap that all up in a function.
For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1)
, you do msvcrt.getwch()
.
For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1)
, etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw
function. If you want to return to line-discipline mode later, you'll need to use the termios
module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno())
before calling setraw
, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash)
, you don't have to learn what all those fiddly bits mean.
On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin
buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw
. You could always replace readline
by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.
If you instead had a data.frame (df) that had multiple columns and you want to vectorize you can do
as.matrix(df, ncol=1)
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, {Component} from 'react'
import {render} from 'react-dom'
class DivSize extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
componentDidMount() {
const height = this.divElement.clientHeight;
this.setState({ height });
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
)
}
}
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://codepen.io/bassgang/pen/povzjKw
Those files are created and used by Android Studio editor.
You don't need to check in those files to version control.
Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.
Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.
If layoutparams
is already defined (in XML or dynamically), Here's a one liner:
((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;
most of the problems cause by .NET Framework. So just go to project properties and change .Net version same as your reference dll.
Done!!!
Hope it's help :)
The main point is that as of December 2018 it's Scripts
not bin
.
Use one of these:
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda2/Scripts/:$PATH
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda3/Scripts/:$PATH
Use one of these:
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda2\Scripts\;%PATH%
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda3\Scripts\;%PATH%
Change /app
to your installation location. If you installed anaconda change Miniconda
to Anaconda
. Also, check for Script vs. bin,.
export PATH="/app/Miniconda/bin:$PATH"
You may need to run set -a
before setting the path, I think this is important if you're setting the path in a script. For example if you have your export command in a file called set_my_path.sh
, I think you'd need to do set -a; source("set_my_path.sh")
.
The set -a
will make your changes to the path persist for your session, but they are still not permanent.
For a more permanent solution add the command to ~/.bashrc
. The installers may offer to add something like this to your ~/.bashrc
file, but you can do it too (or comment it out to undo it).
Background: I installed the 64 bit versions of Anaconda 2 and 3 recently on my Windows 10 machine following the recommended installation steps in December of 2018.
ipython
, which works much better in the native Windows command line/bin
folder seems to have been replaced with Scripts
Arraylist narraylist=Arrays.asList(); // Returns immutable arraylist To make it mutable solution would be: Arraylist narraylist=new ArrayList(Arrays.asList());
Super key is the combination of fields by which the row is uniquely identified and the candidate key is the minimal super key.
The official reference is the class Formatter
.
You can use format strings to give the output string the format you like.
DateTime dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
Read more about Custom date and time format strings.
Data in XML format are rarely organized in a way that would allow the xmlToDataFrame
function to work. You're better off extracting everything in lists and then binding the lists together in a data frame:
require(XML)
data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
xml_data <- xmlToList(data)
In the case of your example data, getting location and start time is fairly straightforward:
location <- as.list(xml_data[["data"]][["location"]][["point"]])
start_time <- unlist(xml_data[["data"]][["time-layout"]][
names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])
Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label:
temps <- xml_data[["data"]][["parameters"]]
temps <- temps[names(temps) == "temperature"]
temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
temps <- unlist(temps[[1]][sapply(temps, names) == "value"])
out <- data.frame(
as.list(location),
"start_valid_time" = start_time,
"hourly_temperature" = temps)
head(out)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2013-06-19T16:00:00-04:00 91
2 29.81 -82.42 2013-06-19T17:00:00-04:00 90
3 29.81 -82.42 2013-06-19T18:00:00-04:00 89
4 29.81 -82.42 2013-06-19T19:00:00-04:00 85
5 29.81 -82.42 2013-06-19T20:00:00-04:00 83
6 29.81 -82.42 2013-06-19T21:00:00-04:00 80
You need the /g for global matching
replace(/\n/g, "<br />");
This works for me for \n
- see this answer if you might have \r\n
NOTE: The dupe is the most complete answer for any combination of \r\n
, \r
or \n
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
Line 1_x000D_
_x000D_
_x000D_
Line 2_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Line 3_x000D_
</textarea>
_x000D_
UPDATE
It seems some visitors of this question have text with the breaklines escaped as
some text\r\nover more than one line"
In that case you need to escape the slashes:
replace(/\\r\\n/g, "<br />");
NOTE: All browsers will ignore \r
in a string when rendering.
Hey i'm using Volley and was getting Server error 411, I added to the getHeaders method the following line :
params.put("Content-Length","0");
And it solved my issue
class Student{
//instance variable or data members.
Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
Scanner s1 = new Scanner(System.in);
String name = s1.nextLine();
int regno ;
int mark1;
int mark2;
int total;
List<Object> list = new ArrayList<Object>();
mapp.put(regno,list); //what wrong in this part?
list.add(mark1);
list.add(mark2);**
//String mark2=mapp.get(regno)[2];
}
If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a>
tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican
, which use Python-Markdown
. And I found an extension for Python-Markdown
Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab
seems not work in Python-Markdown 3.x.
Declare a variable in component.ts and initialize it to some value
buttonDisabled: boolean;
ngOnInit() {
this.buttonDisabled = false;
}
Now in .html or in the template, you can put following code:
<button disabled="{{buttonDisabled}}"> Click Me </button>
Now you can enable/disable button by changing value of buttonDisabled
variable.
The best practice is to check if the array key exists using the built-in array_key_exists
function.
I realize this has already been marked as answered, but we used to do it like this:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND OBJECT_ID = OBJECT_ID('dbo.MyProc'))
exec('CREATE PROCEDURE [dbo].[MyProc] AS BEGIN SET NOCOUNT ON; END')
GO
ALTER PROCEDURE [dbo].[MyProc]
AS
....
Just to avoid dropping the procedure.
Even if modern browsers support WebSockets now, I think there is no need to throw SocketIO away and it still has its place in any nowadays project. It's easy to understand, and personally, I learned how WebSockets work thanks to SocketIO.
As said in this topic, there's a plenty of integration libraries for Angular, React, etc. and definition types for TypeScript and other programming languages.
The other point I would add to the differences between Socket.io and WebSockets is that clustering with Socket.io is not a big deal. Socket.io offers Adapters that can be used to link it with Redis to enhance scalability. You have ioredis and socket.io-redis for example.
Yes I know, SocketCluster exists, but that's off-topic.
The better way is:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
LANGUAGE plpgsql
AS $_$
DECLARE
old_parent INTEGER;
new_parent INTEGER;
id_nom INTEGER;
txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
IF TG_OP = 'INSERT' THEN
EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT $1.id,$1.id,0 UNION ALL
SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
ELSE
-- EXECUTE does not support conditional statements inside
EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
EXECUTE '
-- prevent cycles in the tree
UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
|| ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
|| TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
-- first remove edges between all old parents of node and its descendants
DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
(SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
AND ancestor_id IN
(SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
-- then add edges for all new parents ...
INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT child_id,ancestor_id,d_c+d_a FROM
(SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
CROSS JOIN
(SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
|| TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
END IF;
END IF;
RETURN NULL;
END;
$_$;
Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');
For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'TRUNCATE ' || tbl_closure || ';
INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
WITH RECURSIVE tree AS
(
SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
UNION ALL
SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
JOIN tree ON child_id = ' || fld_parent || '
)
SELECT * FROM tree;';
END;
$$;
Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;
The exec
built-in command mirrors functions in the kernel, there are a family of them based on execve
, which is usually called from C.
exec
replaces the current program in the current process, without fork
ing a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;
We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile
, the last statement says something like:
exec appln-program
so now there is no shell to go back to. Even if appln-program
crashes, the end-user cannot get to a shell, because it is not there - the exec
replaced it.
We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh
, and everyone just put into their .login
(csh start-up file) a call to ksh
. While that worked, it left a stray csh
process running, and the logout was two stage which could get confusing. So we changed it to exec ksh
which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh
is not a login-shell).
Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4
etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.
You have obviously seen exec
used somewhere, perhaps if you showed the code that's bugging you we could justify its use.
Edit: I realised that my answer above is incomplete. There are two uses of exec
in shells like ksh
and bash
- used for opening file descriptors. Here are some examples:
exec 3< thisfile # open "thisfile" for reading on file descriptor 3
exec 4> thatfile # open "thatfile" for writing on file descriptor 4
exec 8<> tother # open "tother" for reading and writing on fd 8
exec 6>> other # open "other" for appending on file descriptor 6
exec 5<&0 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4 # copy write file descriptor 4 onto 7
exec 3<&- # close the read file descriptor 3
exec 6>&- # close the write file descriptor 6
Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec
reverts to the original meaning:
exec 3 < thisfile # oops, overwrite the current program with command "3"
There are several ways you can use these, on ksh use read -u
or print -u
, on bash
, for example:
read <&3
echo stuff >&4
You can use timespan
TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString()); // Displays "02:14:18".
[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.
grep -Fxq "String to be found" | ls -a
I'm having the same problem with Wampserver. It’s worked for me:
You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini" For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"
And change default port 3306 to 80. (Lines 20 & 27, in both)
port = 3306 To port = 80
I hope this is helpful.
It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.
Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking.
With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false)
.
After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,
while (!isDataEnough()) {
socketchannel.read(inputBuffer);
// do something else and then read again
}
With the asynchronous api in java 7, these controls can be made in more versatile ways.
One of the 2 ways is to use CompletionHandler
. Notice that both read
calls are non-blocking.
asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */,
new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {...}
public void failed(Throwable e, Object attachment) {...}
}
}
Like this:
>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]
Alternatively, you can use eval()
if you trust the string to be safe:
>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')
IE 8 actually uses the first button it encounters submit or button. Instead of easily indicating which is desired by making it a input type=submit the order on the page is actually significant.
Made a couple of refinements to BrianS's nearly perfect response above:
I've regexed the value set on show because I think it does actually make it slightly more readable in this case (although note I'm using a slightly different format)
My client wanted no calendar so I've added an on show / hide class addition to do that without affecting any other datepickers. The removal of the class is on a timer to avoid the table flashing back up as the datepicker fades out, which seems to be very noticeable in IE.
EDIT: One problem left to solve with this is that there is no way to empty the datepicker - clear the field and click away and it repopulates with the selected date.
EDIT2: I have not managed to solve this nicely (i.e. without adding a separate Clear button next to the input), so ended up just using this: https://github.com/thebrowser/jquery.ui.monthpicker - if anyone can get the standard UI one to do it that would be amazing.
$('.typeof__monthpicker').datepicker({
dateFormat: 'mm/yy',
showButtonPanel:true,
beforeShow:
function(input, dpicker)
{
if(/^(\d\d)\/(\d\d\d\d)$/.exec($(this).val()))
{
var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1);
$(this).datepicker('option', 'defaultDate', d);
$(this).datepicker('setDate', d);
}
$('#ui-datepicker-div').addClass('month_only');
},
onClose:
function(dt, dpicker)
{
setTimeout(function() { $('#ui-datepicker-div').removeClass('month_only') }, 250);
var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(y, m, 1));
}
});
You also need this style rule:
#ui-datepicker-div.month_only .ui-datepicker-calendar {
display:none
}
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];
I am not sure whether anyone faced issues with getting the whole string "test from adb". Using the escape character in front of the space worked for me.
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb" -n com.whereismywifeserver/.IntentReceiver
You can use react-native-easy-app that is easier to send http request and formulate interception request.
import { XHttp } from 'react-native-easy-app';
* Synchronous request
const params = {name:'rufeng',age:20}
const response = await XHttp().url(url).param(params).formEncoded().execute('GET');
const {success, json, message, status} = response;
* Asynchronous requests
XHttp().url(url).param(params).formEncoded().get((success, json, message, status)=>{
if (success){
this.setState({content: JSON.stringify(json)});
} else {
showToast(msg);
}
});
By default
Arrays of objects are passed by value (the array) but each object is passed by reference.
<?php
$obj=new stdClass();
$obj->field='world';
$original=array($obj);
function example($hello) {
$hello[0]->field='mundo'; // change will be applied in $original
$hello[1]=new stdClass(); // change will not be applied in $original
$
}
example($original);
var_dump($original);
// array(1) { [0]=> object(stdClass)#1 (1) { ["field"]=> string(5) "mundo" } }
Note: As an optimization, every single value is passed as reference until its modified inside the function. If it's modified and the value was passed by reference then, it's copied and the copy is modified.
In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.
This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)
How to copy some rows into the same table, with some fields having different values:
Your code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";
UPDATE temporary_table SET Event_ID="120";
UPDATE temporary_table SET ID=NULL
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
General scenario code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
UPDATE temporary_table SET <auto_inc_field>=NULL;
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
Simplified/condensed code:
CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
INSERT INTO original_table SELECT * FROM temporary_table;
As creation of the temporary table uses the TEMPORARY
keyword it will be dropped automatically when the session finishes (as @ar34z suggested).
input:focus {
outline:none;
}
This will do. Orange outline won't show up anymore.
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
BitConverter
class can be used to convert a byte[]
to string
.
var convertedString = BitConverter.ToString(byteAttay);
Documentation of BitConverter
class can be fount on MSDN
The standard approach is to give the centered element fixed dimensions, and place it absolutely:
<div class='fullscreenDiv'>
<div class="center">Hello World</div>
</div>?
.center {
position: absolute;
width: 100px;
height: 50px;
top: 50%;
left: 50%;
margin-left: -50px; /* margin is -0.5 * dimension */
margin-top: -25px;
}?
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>`
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)
RSA can be used both for encryption and digital signatures,
simply by reversing the order in which the exponents are used:
the secret exponent (d) to create the signature, the public exponent (e)
for anyone to verify the signature. Everything else is identical.
DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms.
It creates a 320 bit signature, but with 512-1024 bit security
again rests on difficulty of computing discrete logarithms
has been quite widely accepted.
DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)
DSA key generation is related to, but somewhat more complex than El Gamal.
Mostly because of the use of the secondary 160-bit modulus q used to help
speed up calculations and reduce the size of the resulting signature.
DSA Signature Creation and Verification
to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message
to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified
Signature creation is again similar to ElGamal with the use of a
per message temporary signature key k, but doing calc first mod p,
then mod q to reduce the size of the result. Note that the use of
the hash function SHA is explicit here. Verification also consists of
comparing two computations, again being a bit more complex than,
but related to El Gamal.
Note that nearly all the calculations are mod q, and
hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures
DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.
Yes, according to iTunes Connect Export Compliance Information screens, if you use built-in iOS or MacOS encryption (keychain, https), you are using encryption for purposes of US Government Export regulations. Whether you qualify for an export compliance exemption depends on what your app does and how it uses this encryption. Attached images show the iTunes Connect Export Compliance Screens to help you determine your export reporting obligations. In particular, it states:
If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government. Learn more
Specifying inheritance in the FileSystemAccessRule()
constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl"
and "Allow"
).
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
According to this topic
"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."
I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.
how about trying this?
void CheckKey(void) {
int key;
if (kbhit()) {
key=getch();
if (key == 224) {
do {
key=getch();
} while(key==224);
switch (key) {
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
}
}
printf("%d\n",key);
}
int main() {
while (1) {
if (kbhit()) {
CheckKey();
}
}
}
(if you can't understand why there is 224, then try running this code: )
#include <stdio.h>
#include <conio.h>
int main() {
while (1) {
if (kbhit()) {
printf("%d\n",getch());
}
}
}
but I don't know why it's 224. can you write down a comment if you know why?
echo "blahblah"> txt.txt
will erase the txt and put blahblah in it's place
echo "blahblah">> txt.txt
will write blahblah on a new line in the txt
I think that both will create a new txt if none exists (I know that the first one does)
Where "txt.txt
" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop
, which will put it on their desktop.
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
You can, the question in my mind is more should you. Right from the beginning, I'll say that there is no hard and fast answer. Do the right thing for your current situation.
To me inheritance implies an 'is-a' relationship. Imagine a dog class, which can be extended by more specialized sub types (Alsatian, Poodle, etc). In this case making the dog class abstract may be the right thing to do since sub-types are dogs. Now let's imagine that dogs need a collar. In this case inheritance doesn't make sense: it's nonsense to have a 'is-a' relationship between dogs and collars. This is definitely a 'has-a' relationship, collar is a collaborating object. Making collar abstract just so that dogs can have one doesn't make sense.
I often find that abstract classes with no abstract methods are really expressing a 'has-a' relationship. In these cases I usually find that the code can be better factored without using inheritance. I also find that abstract classes with no abstract method are often a code smell and at the very least should lead to questions being raised in a code review.
Again, this is entirely subjective. There may well be situations when an abstract class with no abstract methods makes sense, it's entirely up to interpretation and justification. Make the best decision for whatever you're working on.
You could json encode a generic object.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);
Use window.location.pathname
to get the path of the current page's URL.
What we have in our table:-
Primary Key
Event type (e.g. "UPDATED", "APPROVED")
Description ("Frisbar was added to blong")
User Id
User Id of second authoriser
Amount
Date/time
Generic Id
Table Name
The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.
Thanks to Chris for his awesome answer, I took it one step further and automated the process of running those statements (my table had over 8,000 permissions)
if object_id('dbo.tempPermissions') is not null
Drop table dbo.tempPermissions
Create table tempPermissions(ID int identity , Queries Varchar(255))
Insert into tempPermissions(Queries)
select 'GRANT ' + dp.permission_name collate latin1_general_cs_as
+ ' ON ' + s.name + '.' + o.name + ' TO ' + dpr.name
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
declare @count int, @max int, @query Varchar(255)
set @count =1
set @max = (Select max(ID) from tempPermissions)
set @query = (Select Queries from tempPermissions where ID = @count)
while(@count < @max)
begin
exec(@query)
set @count += 1
set @query = (Select Queries from tempPermissions where ID = @count)
end
select * from tempPermissions
drop table tempPermissions
additionally to restrict it to a single table add:
and o.name = 'tablename'
after the WHERE dpr.name NOT IN ('public','guest') and remember to edit the select statement so that it generates statements for the table you want to grant permissions 'TO' Not the table the permissions are coming 'FROM' (which is what the script does).
Paint DOES have set color function.
/**
* Set the paint's color. Note that the color is an int containing alpha
* as well as r,g,b. This 32bit value is not premultiplied, meaning that
* its alpha can be any value, regardless of the values of r,g,b.
* See the Color class for more details.
*
* @param color The new color (including alpha) to set in the paint.
*/
public native void setColor(@ColorInt int color);
As an Android developer, I set paint color like this...
paint.setColor(getResources().getColor(R.color.xxx));
I define the color value on color.xml something like...
<color name="xxx">#008fd2</color>
By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm
I hope this helps ! Enjoy coding!
1) 51,983 is a string type number does not accept comma
so u should set it as text
<input type="text" name="commanumber" id="commanumber" value="1,99" step='0.01' min='0' />
replace , with .
and change type attribute to number
$(document).ready(function() {
var s = $('#commanumber').val().replace(/\,/g, '.');
$('#commanumber').attr('type','number');
$('#commanumber').val(s);
});
Check out http://jsfiddle.net/ydf3kxgu/
Hope this solves your Problem
Try like this format and use "width" attribute to manage the image size, it is simple. JavaScript can be implemented in element too.
<button><img src=""></button>
_x000D_
Use these CSS properties:
page-break-after
page-break-before
For instance:
<html>
<head>
<style>
@media print
{
table {page-break-after:always}
}
</style>
</head>
<body>
....
</body>
</html>
If you aren't inclined to momentjs, you can use this:
let x = new Date()
x.toISOString(x.setDate(x.getDate())).slice(0, 10)
Basically it gets the current date (numeric value of date of current month) and then sets the value. Then it converts into ISO format from which I slice down the pure numeric date (i.e. 2019-09-23)
Hope it helps someone.
The long running most typical approach to this question is: Isolated Storage.
Serialize your control state to XML or some other format (especially easily if you're saving Dependency Properties with WPF), then save the file to the user's isolated storage.
If you do want to go the app setting route, I tried something similar at one point myself...though the below approach could easily be adapted to use Isolated Storage:
class SettingsManager
{
public static void LoadSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
EnsureProperties(sender, savedElements);
foreach (FrameworkElement element in savedElements.Keys)
{
try
{
element.SetValue(savedElements[element], Properties.Settings.Default[sender.Name + "." + element.Name]);
}
catch (Exception ex) { }
}
}
public static void SaveSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
EnsureProperties(sender, savedElements);
foreach (FrameworkElement element in savedElements.Keys)
{
Properties.Settings.Default[sender.Name + "." + element.Name] = element.GetValue(savedElements[element]);
}
Properties.Settings.Default.Save();
}
public static void EnsureProperties(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
foreach (FrameworkElement element in savedElements.Keys)
{
bool hasProperty =
Properties.Settings.Default.Properties[sender.Name + "." + element.Name] != null;
if (!hasProperty)
{
SettingsAttributeDictionary attributes = new SettingsAttributeDictionary();
UserScopedSettingAttribute attribute = new UserScopedSettingAttribute();
attributes.Add(attribute.GetType(), attribute);
SettingsProperty property = new SettingsProperty(sender.Name + "." + element.Name,
savedElements[element].DefaultMetadata.DefaultValue.GetType(), Properties.Settings.Default.Providers["LocalFileSettingsProvider"], false, null, SettingsSerializeAs.String, attributes, true, true);
Properties.Settings.Default.Properties.Add(property);
}
}
Properties.Settings.Default.Reload();
}
}
.....and....
Dictionary<FrameworkElement, DependencyProperty> savedElements = new Dictionary<FrameworkElement, DependencyProperty>();
public Window_Load(object sender, EventArgs e) {
savedElements.Add(firstNameText, TextBox.TextProperty);
savedElements.Add(lastNameText, TextBox.TextProperty);
SettingsManager.LoadSettings(this, savedElements);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
SettingsManager.SaveSettings(this, savedElements);
}
just use style attribute with height and width option
<input type="submit" id="search" value="Search" style="height:50px; width:50px" />
Turns out that npm was installed in the wrong directory so I had to change the “npm config prefix” by running this code:
npm config set prefix /usr/local
Then I reinstalled gulp globally (with the -g param) and it worked properly.
This article is where I found the solution: http://webbb.be/blog/command-not-found-node-npm
The []
syntax for getting item by key or index is just syntax sugar.
When you evaluate a[i]
Python calls a.__getitem__(i)
(or type(a).__getitem__(a, i)
, but this distinction is about inheritance models and is not important here). Even if the class of a
may not explicitly define this method, it is usually inherited from an ancestor class.
All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names
You can try this way:-
Give a class say header
to the header rows, use nextUntil to get all rows beneath the clicked header until the next header.
$('.header').click(function(){
$(this).nextUntil('tr.header').slideToggle(1000);
});
<table border="0">
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
Another Example:
$('.header').click(function(){
$(this).find('span').text(function(_, value){return value=='-'?'+':'-'});
$(this).nextUntil('tr.header').slideToggle(100); // or just use "toggle()"
});
You can also use promise to toggle the span icon/text after the toggle is complete in-case of animated toggle.
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
$this.find('span').text(function (_, value) {
return value == '-' ? '+' : '-'
});
});
});
Or just with a css pseudo element to represent the sign of expansion/collapse, and just toggle a class on the header.
CSS:-
.header .sign:after{
content:"+";
display:inline-block;
}
.header.expand .sign:after{
content:"-";
}
JS:-
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
The SET
clause should come after the table specification.
UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
This worked perfectly with grouped calls: Implement a custom subclass of UITableViewCell
This will respect corners and such...
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
if(selected)
[self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
else
[self setBackgroundColor:[UIColor whiteColor]];
}