Just use this:
$array = explode("\n", file_get_contents('file.txt'));
Because gets
doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:
char array1[] = "12345";
char array2[] = "67890";
gets(array1);
Now, first of all you are allowed to input how many characters you want, gets
won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1
) will overwrite whatever they find in memory because gets
will write them. In the previous example this means that if you input "abcdefghijklmnopqrts"
maybe, unpredictably, it will overwrite also array2
or whatever.
The function is unsafe because it assumes consistent input. NEVER USE IT!
Assuming that you only want to read a single line, then use LINE_MAX
, which is defined in <limits.h>
:
#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...
The elegant way:
Name[strcspn(Name, "\n")] = 0;
The slightly ugly way:
char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
*pos = '\0';
else
/* input too long for buffer, flag error */
The slightly strange way:
strtok(Name, "\n");
Note that the strtok
function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the \n
character intact.
There are others as well, of course.
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).
I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/
The solution:
Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)
For development:
<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">
For production (where caching is mostly a good thing):
<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)
Or combination of these two:
<?php
define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">
EDIT:
Or prettier combination of those two:
<?php
// Init
define( "DEBUGGING", true ); // or false in production enviroment
// Functions
function get_cache_prevent_string( $always = false ) {
return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
}
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">
All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:
NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long
int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;
Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
Lots of good answers here - just chipping in my own.
I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:
[
{
"property1": "foo",
"property2": "bar",
"timeOfDay": "2019-09-30T00:00:00",
"numberOfHits": 98,
"isSpecial": false,
"comment": "just to be awkward, this contains a comma"
},
{
"property1": "fool",
"property2": "barrel",
"timeOfDay": "2019-10-31T00:00:00",
"numberOfHits": 11,
"isSpecial": false,
"comment": null
},
...
]
There are a few things to note about this:
null
).The ParseListOfObjects
function in the code below takes the JSON string as input, and returns a Collection
representing the items in the list. Each item is represented as a Dictionary
, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String
, Date
, Double
, Boolean
- or Empty
if the value is null
).
Your VBA project will need a reference to the Microsoft Scripting Runtime
library to use the Dictionary
object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.
Here's my JSON.bas
:
Option Explicit
' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.
Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"
Private Const strLIST_DELIMITER As String = ","
Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"
Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"
Private Const strQUOTE As String = """"
Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"
Public Function ParseListOfObjects(ByVal strJson As String) As Collection
' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
' values of the JSON object properties.
Set ParseListOfObjects = New Collection
Dim strList As String: strList = Trim(strJson)
' Check we have a list
If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
End If
' Get the list item text (between the [ and ])
Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))
If strBody = "" Then
Exit Function
End If
' Check we have a list of objects
If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
End If
' We now have something like:
' {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)
Dim ixItem As Long
For ixItem = LBound(astrItems) To UBound(astrItems)
Dim strItem As String: strItem = Trim(astrItems(ixItem))
If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
End If
' Only the last item will have a closing brace (see comment above)
Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)
If bIsLastItem Then
If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
End If
End If
Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))
ParseListOfObjects.Add ParseObjectContent(strContent)
Next ixItem
End Function
Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary
Set ParseObjectContent = New Scripting.Dictionary
ParseObjectContent.CompareMode = TextCompare
' The object content will look something like:
' "property":"value", "property":"value", ...
' ... although the value may not be in quotes, since numbers are not quoted.
' We can't assume that the property value won't contain a comma, so we can't just split the
' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
' (and we're already assuming no sub-structure).
' We'll need to scan for commas while taking quoted strings into account.
Dim ixPos As Long: ixPos = 1
Do While ixPos <= Len(strContent)
Dim strRemainder As String
' Find the opening quote for the name (names should always be quoted)
Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)
If ixOpeningQuote <= 0 Then
' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
strRemainder = Trim(Mid(strContent, ixPos))
If Len(strRemainder) = 0 Then
Exit Do
End If
Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
End If
' Now find the closing quote for the name, which we assume is the very next quote
Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
If ixClosingQuote <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
End If
If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
End If
Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
' The next thing after the quote should be the colon
Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)
If ixNameValueSeparator <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
End If
' Check that there was nothing between the closing quote and the colon
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
End If
' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
' closing quote while ignoring any commas inside the quoted value.
' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
' for the next comma.
' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
' have the last - unquoted - value).
ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)
If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
' Only use whichever came first
If ixOpeningQuote < ixPropertySeparator Then
ixPropertySeparator = 0
Else
ixOpeningQuote = 0
End If
End If
Dim strValue As String
Dim vValue As Variant
If ixOpeningQuote <= 0 Then ' it's not a quoted value
If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
ixPos = Len(strContent) + 1
Else ' this is not the last value
strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
End If
vValue = ParseUnquotedValue(strValue)
Else ' It is a quoted value
' Find the corresponding closing quote, which should be the very next one
ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)
If ixClosingQuote <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
End If
strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
vValue = ParseQuotedValue(strValue)
' Re-scan for the property separator, in case we hit one that was part of the quoted value
ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)
If ixPropertySeparator <= 0 Then ' this was the last value
' Check that there's nothing between the closing quote and the end of the text
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
End If
ixPos = Len(strContent) + 1
Else ' this is not the last value
' Check that there's nothing between the closing quote and the property separator
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
End If
ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
End If
End If
ParseObjectContent.Add strName, vValue
Loop
End Function
Private Function ParseUnquotedValue(ByVal strValue As String) As Variant
If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = Empty
ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = True
ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = False
ElseIf IsNumeric(strValue) Then
ParseUnquotedValue = CDbl(strValue)
Else
Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
End If
End Function
Private Function ParseQuotedValue(ByVal strValue As String) As Variant
' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
' Dates are in the form:
' 2019-09-30T00:00:00
If strValue Like "####-##-##T##:00:00" Then
' NOTE: we just want the date part
ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
Else
ParseQuotedValue = strValue
End If
End Function
A simple test:
Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)
MsgBox oObjects(1)("property1") ' shows "foo"
It means what it says. The operation took too long to complete.
BTW, look at WebRequest.Timeout and you'll see that you've set your timeout for 1/5 second.
With collections.Counter
you could do
>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]
If appropriate, you could simply start with an empty collections.Counter
and add to it
>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc.
Add a line to your app.config in the configSections element
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
<log4net configSource="Config\Log4Net.config" />
In your application code, when you create the log, write
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.
JavaScript
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forE??ach(function(link) {
link.className += ' current-link')
});
</script>
One Liner Version of Above
document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});
CSS
.current-link {
color:#baada7;
}
Other Notes
Taraman's jQuery answer above only searches on [href]
which will return link
tags and tags other than a
which rely on the href
attribute. Searching on a[href='*https://urlofcurrentpage.com*']
captures only those links which meets the criteria and therefore runs faster.
In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.
This is the html redirect approach it works but not the best.
<meta http-equiv="Refresh" content="0;URL=https://www.example.com" />
PHP approach
<?php
function redirectTohttps() {
if ($_SERVER['HTTPS']!="on") {
$redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location:$redirect");
}
}
?>
.htaccess approch
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
copied from: www.letuslook.org
This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):
warning C4101: 'i': unreferenced local variable
After I commented this unused i
, and compiled it, the other error went away.
Use:
File.ReadAllLines("My textfile.txt");
Reference: https://msdn.microsoft.com/pt-br/library/s2tte0y1(v=vs.110).aspx
With newer versions of client tools, there are multiple options to format the query output. The rest is to spool it to a file or save the output as a file depending on the client tool. Here are few of the ways:
Using the SQL*Plus commands you could format to get your desired output. Use SPOOL to spool the output to a file.
For example,
SQL> SET colsep ,
SQL> SET pagesize 20
SQL> SET trimspool ON
SQL> SET linesize 200
SQL> SELECT * FROM scott.emp;
EMPNO,ENAME ,JOB , MGR,HIREDATE , SAL, COMM, DEPTNO
----------,----------,---------,----------,---------,----------,----------,----------
7369,SMITH ,CLERK , 7902,17-DEC-80, 800, , 20
7499,ALLEN ,SALESMAN , 7698,20-FEB-81, 1600, 300, 30
7521,WARD ,SALESMAN , 7698,22-FEB-81, 1250, 500, 30
7566,JONES ,MANAGER , 7839,02-APR-81, 2975, , 20
7654,MARTIN ,SALESMAN , 7698,28-SEP-81, 1250, 1400, 30
7698,BLAKE ,MANAGER , 7839,01-MAY-81, 2850, , 30
7782,CLARK ,MANAGER , 7839,09-JUN-81, 2450, , 10
7788,SCOTT ,ANALYST , 7566,09-DEC-82, 3000, , 20
7839,KING ,PRESIDENT, ,17-NOV-81, 5000, , 10
7844,TURNER ,SALESMAN , 7698,08-SEP-81, 1500, , 30
7876,ADAMS ,CLERK , 7788,12-JAN-83, 1100, , 20
7900,JAMES ,CLERK , 7698,03-DEC-81, 950, , 30
7902,FORD ,ANALYST , 7566,03-DEC-81, 3000, , 20
7934,MILLER ,CLERK , 7782,23-JAN-82, 1300, , 10
14 rows selected.
SQL>
Alternatively, you could use the new /*csv*/
hint in SQL Developer.
/*csv*/
For example, in my SQL Developer Version 3.2.20.10:
Now you could save the output into a file.
New in SQL Developer version 4.1, use the following just like sqlplus command and run as script. No need of the hint in the query.
SET SQLFORMAT csv
Now you could save the output into a file.
Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY
tells the OS to recreate the service after it has enough memory and call onStartCommand()
again with a null intent. START_NOT_STICKY
tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT
that tells the OS to recreate the service and redeliver the same intent to onStartCommand()
.
This article by Dianne Hackborn explained the background of this a lot better than the official documentation.
Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html
The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:
START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.
axios.get(
'/app/export'
).then(response => {
const url = window.URL.createObjectURL(new Blob([response]));
const link = document.createElement('a');
link.href = url;
const fileName = `${+ new Date()}.csv`// whatever your file name .
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
link.remove();// you need to remove that elelment which is created before.
})
You may want to disable browser caching for all pages rendered by controllers (i.e. HTML pages), but keep caching in place for resources such as scripts, style sheets, and images. If you're using MVC4+ bundling and minification, you'll want to keep the default cache durations for scripts and stylesheets (very long durations, since the cache gets invalidated based on a change to a unique URL, not based on time).
In MVC4+, to disable browser caching across all controllers, but retain it for anything not served by a controller, add this to FilterConfig.RegisterGlobalFilters
:
filters.Add(new DisableCache());
Define DisableCache
as follows:
class DisableCache : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
I was able to get it to work by following these instructions.
Download the sample code
Unzip it to a new location
Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)
Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to)
Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs:
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Run (hit F5)
SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";
will give you what you need
I did this many years back on 2003 or possibly 97, yikes!
If I recall you need to use one of the subcommands above tied to a timer. You cannot operate on the db with any connections or forms open.
So you do something about closing all forms, and kick off the timer as the last running method. (which will in turn call the compact operation once everything closes)
If you haven't figured this out I could dig through my archives and pull it up.
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
As GTalk
is gone from the SDK, it might be a good idea to make a 'standard' push messaging system. That way, only one service has to run, only one extra tcp connection needs to be open. Applications should talk to this service using Intents
and should first request permission to send and receive notification from the service. The service should then notify the user a new application wants to send and receive messages. The user will then grant or deny permission, so he stays in control. The application will then register an action + category to the service, so the service knows how to deliver the pushed message.
Would the a good idea or not?
For Translating the command to python refer below:-
1)Alternative of cat command is open refer this. Below is the sample
>>> f = open('workfile', 'r')
>>> print f
2)Alternative of grep command refer this
3)Alternative of Cut command refer this
This is an old thread, but I stumbled across it when trying to solve a similar problem.
For me, I got this particular error relating to the php_wincache.dll
. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.
So, if you get an error similar to this, make sure all the extensions are in place and updated.
It might be that
hsql://localhost
can't be resolved to a file. Look at the sample program here:
See if you can get that working first, and then see if you can take that configuration information and use it in the Spring bean configuration.
Good luck!
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok.
if you use docker-compose.yml
file:
services:
varnish:
ports:
- 80
- 6081
You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT
varnish:
ports:
- 81:80
- 6081:6081
The code commented works as well, just choose which do you prefer
import numpy as np
from PIL import Image
def convert_from_cv2_to_image(img: np.ndarray) -> Image:
# return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.fromarray(img)
def convert_from_image_to_cv2(img: Image) -> np.ndarray:
# return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
return np.asarray(img)
Why not set ON CASCADE DELETE on Foreign Key patron_info
.pid?
I am parsing .il files generated by ildasm to build a database of assemnblies, classes, methods, and stored procedures for use doing a conversion. I came across the following, which broke my parsing.
.method private hidebysig instance uint32[0...,0...]
GenerateWorkingKey(uint8[] key,
bool forEncryption) cil managed
The book Expert .NET 2.0 IL Assembler, by Serge Lidin, Apress, published 2006, Chapter 8, Primitive Types and Signatures, pp. 149-150 explains.
<type>[]
is termed a Vector of <type>
,
<type>[<bounds> [<bounds>**] ]
is termed an array of <type>
**
means may be repeated, [ ]
means optional.
Examples: Let <type> = int32
.
1) int32[...,...]
is a two-dimensional array of undefined lower bounds and sizes
2) int32[2...5]
is a one-dimensional array of lower bound 2 and size 4.
3) int32[0...,0...]
is a two-dimensional array of lower bounds 0 and undefined size.
Tom
In addition to above : Trailing closure can be used .
downloadFileFromURL(NSURL(string: "url_str")!) { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
}
Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:
span.stars, span.stars span {
display: block;
background: url(stars.png) 0 -16px repeat-x;
width: 80px;
height: 16px;
}
span.stars span {
background-position: 0 0;
}
(source: ulmanen.fi)
Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.
$.fn.stars = function() {
return $(this).each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars holder
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
}
If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size
row:
val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */
<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>
$(function() {
$('span.stars').stars();
});
(source: ulmanen.fi)
This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.
A small explanation on how the stars are presented might be in order.
The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:
<span class="stars">
<span></span>
</span>
The outer span gets a background-position
of 0 -16px
. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x
, it will only show 5 gray stars.
The inner span on the other hand has a background-position
of 0 0
which makes only the yellow stars visible.
This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.
Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.
But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.
Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px
, so that people with CSS turned off would at least see the floating point number instead of the stars.
Hopefully that made some sense.
Now even more compact and harder to understand! Can also be squeezed down to a one liner:
$.fn.stars = function() {
return $(this).each(function() {
$(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
});
}
This worked for me and also worked with bootstrap tables
<style>
.table td, .table th {
font-size: 10px;
}
</style>
You can't access Session
directly in JavaScript.
You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById
Python 3.7 works for me, I uninstalled python 3.8.1 and reinstalled 3.7.6. After that, I executed:
pip3 install --user --upgrade tensorflow
and it works
Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?
It can very much be an ssh-agent issue.
Check whether there is an ssh-agent PID currently running with eval "$(ssh-agent -s)"
Check whether your identity is added with ssh-add -l
and if not, add it with ssh-add <pathToYourRSAKey>
.
Then try again your ssh command (or any other command that spawns ssh daemons, like autossh for example) that returned 255.
platform.architecture()
is problematic (and expensive).
Conveniently test for sys.maxsize > 2**32
since Py2.6 .
This is a reliable test for the actual (default) pointer size and compatible at least since Py2.3: struct.calcsize('P') == 8
. Also: ctypes.sizeof(ctypes.c_void_p) == 8
.
Notes: There can be builds with gcc option -mx32
or so, which are 64bit architecture applications, but use 32bit pointers as default (saving memory and speed). 'sys.maxsize = ssize_t' may not strictly represent the C pointer size (its usually 2**31 - 1
anyway). And there were/are systems which have different pointer sizes for code and data and it needs to be clarified what exactly is the purpose of discerning "32bit or 64bit mode?"
echo one,two,three | sed 's/,/\
/g'
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
This happens when classes belonging to the same package are loaded from different JAR files, and those JAR files have signatures signed with different certificates - or, perhaps more often, at least one is signed and one or more others are not (which includes classes loaded from directories since those AFAIK cannot be signed).
So either make sure all JARs (or at least those which contain classes from the same packages) are signed using the same certificate, or remove the signatures from the manifest of JAR files with overlapping packages.
Try this
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-30)
As noted by @Neel, this method returns in Javascript Timestamp format. To convert it back to date object, you need to pass the above to a new Date object; new Date(priorDate)
.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Button btn;
EditText et;
PackageInfo info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
info = getPackageManager().getPackageInfo("com.example.id", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
et.setText("" + something);
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
});
}
}
When I have added/modified/deleted many files (since the last commit), I like to look at those modifications in chronological order.
For that I use:
To list all non-staged files:
git ls-files --other --modified --exclude-standard
To get the last modified date for each file:
while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done
Although ruvim suggests in the comments:
xargs -0 stat -c '%y %n' --
To sort them from oldest to more recent:
sort
An alias makes it easier to use:
alias gstlast='git ls-files --other --modified --exclude-standard|while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done|sort'
Or (shorter and more efficient, thanks to ruvim)
alias gstlast='git ls-files --other --modified --exclude-standard|xargs -0 stat -c '%y %n' --|sort'
For example:
username@hostname:~> gstlast
2015-01-20 11:40:05.000000000 +0000 .cpl/params/libelf
2015-01-21 09:02:58.435823000 +0000 .cpl/params/glib
2015-01-21 09:07:32.744336000 +0000 .cpl/params/libsecret
2015-01-21 09:10:01.294778000 +0000 .cpl/_deps
2015-01-21 09:17:42.846372000 +0000 .cpl/params/npth
2015-01-21 12:12:19.002718000 +0000 sbin/git-rcd
I now can review my modifications, from oldest to more recent.
As an alternate streaming approach:
Both steps should handle steaming just fine.
Pitfalls:
Even though the answer for this question has been selected already, however, I believe the simplest query will be
SELECT *
FROM table
WHERE
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();
Use dotPeek by JetBrains.
https://www.jetbrains.com/decompiler/
dotPeek is a free tool based on ReSharper. It can reliably decompile any .NET assembly into C# or IL code.
In following 97 ascii value of small "a".
public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (97 + r.nextInt(3));
return random_3_Char;
}
in above 3 number for a , b , c or d and if u want all character like a to z then you replace 3 number to 25.
<input type="button" value="Clear" onclick="javascript: functionName();" >
you just need to set the onclick event, call your desired function on this onclick event.
function functionName()
{
$("#output").val("");
}
Above function will set the value of text area to empty string.
For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.
It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).
Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
Over a year later... if what you need is get the auto generated id of a table, you can just
SELECT @ReportOptionId = SCOPE_IDENTITY()
Otherwise, it seems like you are stuck with using a table.
Unfortunately, JSR 308
will not add more values than this project local Not Null suggestion here
Java 8
will not come with a single default annotation or its own Checker
framework.
Similar to Find-bugs or JSR 305
, this JSR is poorly maintained by a small bunch of mostly academic teams.
No commercial power behind it, thus JSR 308
launches EDR 3
(Early Draft Review at JCP
) NOW, while Java 8
is supposed to ship in less than 6 months:-O
Similar to 310
btw. but unlike 308 Oracle
has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform.
Every project, vendor and academic class like the ones behind the Checker Framework
and JSR 308
will create its own proprietary checker annotation.
Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to Java 9
or 10
, or via frameworks like Apache Commons
or Google Guava
;-)
You've got 2 options:
OPTION A) Marks as "active" in your calendar, only when you click in the input.
Js:
$('input.datepicker').datepicker(
{
changeMonth: false,
changeYear: false,
beforeShow: function(input, instance) {
$(input).datepicker('setDate', new Date());
}
}
);
Css:
div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active {
background: #1ABC9C;
border-radius: 50%;
color: #fff;
cursor: pointer;
display: inline-block;
width: 24px; height: 24px;
}?
OPTION B) Input by default with today. You've to populate first the datepicker .
$("input.datepicker").datepicker().datepicker("setDate", new Date());
First you need to access the navigation drawer in your MainActivity(or the calling activity) like this:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Then you need to remove the header layout from the activity_main.xml because the layout will be inflated programatically in the MainActivity. Your activity_main.xml should look like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Then in your MainActivity, we inflate the nav_header_main layout and get access to its views, in this case the ImageView and TextView
//inflate header layout
View navView = navigationView.inflateHeaderView(R.layout.nav_header_main);
//reference to views
ImageView imgvw = (ImageView)navView.findViewById(R.id.imageView);
TextView tv = (TextView)navView.findViewById(R.id.textview);
//set views
imgvw.setImageResource(R.drawable.your_image);
tv.setText("new text");
navigationView.setNavigationItemSelectedListener(this);
You can read more here
Sept 2018
For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.
Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)
Paperclip team deprecated the gem in favor of the Rails ActiveStorage.
Here is the github page for the ActiveStorage & plenty of resources are available everywhere
Also I found this video to be very helpful to understand the features of Activestorage
Here is how I do it and works both for create and edit:
//How to do it with enums
<div class="editor-field">
@Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
@Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
//And with Booleans
<div class="editor-field">
@Html.RadioButtonFor(x => x.IsMale, true) Male
@Html.RadioButtonFor(x => x.IsMale, false) Female
</div>
the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:
<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">
And the checked property is dependent on the Model.IsMale value.
Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.
In Package Manager Console
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
The show method does what you're looking for.
For example, given the following dataframe of 3 rows, I can print just the first two rows like this:
df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)
which yields:
+---+---+
| k| v|
+---+---+
|foo| 1|
|bar| 2|
+---+---+
only showing top 2 rows
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
You could also use an ArrayObject, for example:
<?php
$arr = array("test",
array("one"=>1,"two"=>2,"three"=>3),
array("one"=>1,"two"=>2,"three"=>3)
);
$o = new ArrayObject($arr);
echo $o->offsetGet(2)["two"],"\n";
foreach ($o as $key=>$val){
if (is_array($val)) {
foreach($val as $k => $v) {
echo $k . ' => ' . $v,"\n";
}
}
else
{
echo $val,"\n";
}
}
?>
//Output:
2
test
one => 1
two => 2
three => 3
one => 1
two => 2
three => 3
jsonify
prevents you from doing this in Flask 0.10 and lower for security reasons.
To do it anyway, just use json.dumps
in the Python standard library.
Try out df.apply() if you've a small/medium dataframe,
df['c2'] = df.apply(lambda x: 10 if x['c1'] == 'Value' else x['c1'], axis = 1)
Else, follow the slicing techniques mentioned in the above comments if you've got a big dataframe.
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
I personally use following approach to sort dates.
let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];
array.sort(function(date1, date2) {
date1 = new Date(date1);
date2 = new Date(date2);
if (date1 > date2) return 1;
if (date1 < date2) return -1;
})
The command select username from all_users;
requires less privileges
You're not the only person having problems with Python 2.6 and MySQL (http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/). Here's an explanation how it should run under Python 2.5 http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/ Good luck
If you just need to insert a new row with a data from another row,
insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;
This stored procedure inserts a rand number into a table. Look out, it inserts an endless numbers. Stop executing it when u get enough numbers.
create a table for the cursor:
CREATE TABLE [dbo].[SearchIndex](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Cursor] [nvarchar](255) NULL)
GO
Create a table to contain your numbers:
CREATE TABLE [dbo].[ID](
[IDN] [int] IDENTITY(1,1) NOT NULL,
[ID] [int] NULL)
INSERTING THE SCRIPT :
INSERT INTO [SearchIndex]([Cursor]) SELECT N'INSERT INTO ID SELECT FLOOR(rand() * 9 + 1) SELECT COUNT (ID) FROM ID
CREATING AND EXECUTING THE PROCEDURE:
CREATE PROCEDURE [dbo].[RandNumbers] AS
BEGIN
Declare CURSE CURSOR FOR (SELECT [Cursor] FROM [dbo].[SearchIndex] WHERE [Cursor] IS NOT NULL)
DECLARE @RandNoSscript NVARCHAR (250)
OPEN CURSE
FETCH NEXT FROM CURSE
INTO @RandNoSscript
WHILE @@FETCH_STATUS IS NOT NULL
BEGIN
Print @RandNoSscript
EXEC SP_EXECUTESQL @RandNoSscript;
END
END
GO
Fill your table:
EXEC RandNumbers
Even though your question says "using javascript", you can use the prefetch
attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:
<link rel="prefetch" href="(url)">
More info on support here: http://caniuse.com/#search=prefetch
Note that IE 9,10 aren't listed in the caniuse
matrix because Microsoft has discontinued support for them.
So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
(This explanation is only for positive numbers since it depends on the language otherwise)
Definition
The Modulus is the remainder of the euclidean division of one number by another. %
is called the modulo operation.
For instance, 9
divided by 4
equals 2
but it remains 1
. Here, 9 / 4 = 2
and 9 % 4 = 1
.
In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5
).
Calculation
The modulo operation can be calculated using this equation:
a % b = a - floor(a / b) * b
floor(a / b)
represents the number of times you can divide a
by b
floor(a / b) * b
is the amount that was successfully shared entirelya
) minus what was shared equals the remainder of the divisionApplied to the last example, this gives:
5 % 7 = 5 - floor(5 / 7) * 7 = 5
Modular Arithmetic
That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7)
because it exists k in Z such that 7k - 2 = 5
.
You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7
is 3.
In ES6 you can do something like this:
function foo(...args) _x000D_
{_x000D_
let [a,b,...c] = args;_x000D_
_x000D_
console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
In MongoDB Stitch functions it can be done using BSON like below:
Use the ObjectId
helper in the BSON utility package for this purpose like in the follwing example:
var id = "5bb9e9f84186b222c8901149";
BSON.ObjectId(id);
Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).
Here is what I obtain with your sample image and some other image with a sheet of paper I found around:
The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation
- erosion
) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.
At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:
Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).
For reference, here is a sample code in Mathematica:
f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &],
"ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5],
Polygon @@ convexvert}]]
If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".
tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log
You can also upload log from admin console : http://yoururl:4848
"+" is the adjacent sibling selector. It will select any p DIRECTLY AFTER a p (not a child or parent though, a sibling).
Whenever you need to access property dynamically you have to use square bracket for accessing property not "." operator
Syntax: object[propery}
const something = { bar: "Foobar!" };_x000D_
const foo = 'bar';_x000D_
// something.foo; -- not correct way at it is expecting foo as proprty in something={ foo: "value"};_x000D_
// correct way is something[foo]_x000D_
alert( something[foo])
_x000D_
You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.
My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
Don't forget to import it as well by typing:
import java.awt.BorderLayout;
There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!
// Java 8
int vInt = Integer.parseUnsignedInt("4294967295");
System.out.println(vInt); // -1
String sInt = Integer.toUnsignedString(vInt);
System.out.println(sInt); // 4294967295
long vLong = Long.parseUnsignedLong("18446744073709551615");
System.out.println(vLong); // -1
String sLong = Long.toUnsignedString(vLong);
System.out.println(sLong); // 18446744073709551615
// Guava 18.0
int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
System.out.println(vIntGu); // -1
String sIntGu = UnsignedInts.toString(vIntGu);
System.out.println(sIntGu); // 4294967295
long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
System.out.println(vLongGu); // -1
String sLongGu = UnsignedLongs.toString(vLongGu);
System.out.println(sLongGu); // 18446744073709551615
/**
Integer - Max range
Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1
Long - Max range
Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
*/
Since I upgraded to 6.3.2, I use XML Tools
.
In older versions: menu ? TextFX ? HTML Tidy ? Tidy: Reindent XML.
You're pretty close, you just need to replace the =
with a :
. You can use an object type literal (see spec section 3.5.3) or an interface. Using an object type literal is close to what you have:
var obj: { property: string; } = { property: "foo" };
But you can also use an interface
interface MyObjLayout {
property: string;
}
var obj: MyObjLayout = { property: "foo" };
Use the compareTo
method of BigDecimal :
public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.
Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
For this use below code in your app gradle file under android closure.
dexOptions { javaMaxHeapSize "4g" }
You can try Restlet edition for android:
The source can be downloaded from Restlet website:
Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:
select
s.SqmId,
m.c.value('@id', 'varchar(max)') as id,
m.c.value('@type', 'varchar(max)') as type,
m.c.value('@unit', 'varchar(max)') as unit,
m.c.value('@sum', 'varchar(max)') as [sum],
m.c.value('@count', 'varchar(max)') as [count],
m.c.value('@minValue', 'varchar(max)') as minValue,
m.c.value('@maxValue', 'varchar(max)') as maxValue,
m.c.value('.', 'nvarchar(max)') as Value,
m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)
Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...
Void methods require a semicolon at the end of the calling code.
In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>
like so
<% Html.RenderPartial("Path/to/my/partial/view"); %>
when you are using the Razor view engine the equivalent is
@{Html.RenderPartial("Path/to/my/partial/view");}
You can try this also-
if( !$('#EventStartTimeMin').val() ) {
// do something
}
You can use set
with the /p
argument:
SET /P variable=[promptString]
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So, simply use something like
set /p Input=Enter some text:
Later you can use that variable as argument to a command:
myCommand %Input%
Be careful though, that if your input might contain spaces it's probably a good idea to quote it:
myCommand "%Input%"
You can use a LENGTH(that_string)
minus the number of characters
you want to remove in the SUBSTRING()
select perhaps or use the TRIM()
function.
All do not work for me on eloquent collections, laravel eloquent collections use the key from the items I think which causes merging issues, you need to get the first collection back as an array, put that into a fresh collection and then push the others into the new collection;
public function getFixturesAttribute()
{
$fixtures = collect( $this->homeFixtures->all() );
$this->awayFixtures->each( function( $fixture ) use ( $fixtures ) {
$fixtures->push( $fixture );
});
return $fixtures;
}
http://www.dreamincode.net/forums/topic/99678-j2se-vs-j2ee-what-are-main-differences/
As far as the language goes it is not as though java changes. Java EE has access to all of the SE libraries. However EE adds a set of libraries for dealing with enterprise applications.
Java EE is more like a "platform" or an general area of development.
In Java SE you write applications that run as standalone java programs or as Applets. In JavaEE you can still do this, but you can also write applications that run inside of a Java EE container. The container can do a great amount of management for you such as scaling an application across threads, providing resource pools, and management features.
Java EE has a web framework based upon Servlets. It has JSP (Java Server Pages) which is a templating language that compiles from JSP to a Java servlet where it can be run by the container.
So Java EE is more or less Java SE + Enterprise platform technologies.
Java EE is far more than just a couple of extra libraries (that is what I thought when I first looked at it) since there are a ton of frameworks and technologies built upon the Java EE specifications.
But it all boils down to just plain old java.
Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config
and I was able to add in the correct "mime map" there.
Nope - but you could use a template column:
<script runat="server">
TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
object o = DataBinder.Eval(Container.DataItem, field);
if (converter == null) {
return (TResult)o;
}
return converter((T)o);
}
</script>
<asp:TemplateField>
<ItemTemplate>
<%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
</ItemTemplate>
</asp:TemplateField>
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
I adapted one of the above answers from cdhowie as I could not get it to work. This seems to work for me. I suspect it's also possible to do this with the UNIX_TIMESTAMP function been used.
SELECT * FROM your_table
WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));
if you want filename only :
for file in /home/user/*; do
f=$(echo "${file##*/}");
filename=$(echo $f| cut -d'.' -f 1); #file has extension, it return only filename
echo $filename
done
for more information about cut
command see here.
Windows can only show a limited number of Overlay Icons (15 total, 11 after what Windows uses). Programs like Office Groove, Dropbox, Mozy, Carbonite, etc, will hijack a bunch of the 11 possible overlay icons (boy would it be nice if Microsoft upped the number of these as the number of applications that use them seem to increase and increase)...
You can see what overlays are set up, and change them (at your own risk) in the registry here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers
If you are using TortoiseCVS (and have nothing else using overlay icons), you will get a couple of TortoiseSVN Icons, and all of your TortoiseCVS icons. This is because the overlay icons are used in alphabetical order. Again, at your own risk (editing the registry may blow up your computer, yada, yada, yada -- and if you are reading Stack Overflow and using Windows and haven't edited the registry, you are a rare beast indeed), feel free to rename them (I suggest putting numbers in front of the ones you want to use and "z_"'s prefixed to the ones you don't need). The TortoiseSVN Shell extensions are nicely named so you know what they do, the TortoiseCVS extensions are not. After looking through the source code, I found the pertinent information:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER
Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.
For more details u can refer to : https://stackify.com/java-remote-debugging/
great work on this class. Simple and easy to use. I modified the class to include a title in the first row of the export; figured I would share:
use:
CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));
class:
public class CsvExport
{
List<string> fields = new List<string>();
public string addTitle { get; set; } // string for the first row of the export
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> currentRow
{
get
{
return rows[rows.Count - 1];
}
}
public object this[string field]
{
set
{
if (!fields.Contains(field)) fields.Add(field);
currentRow[field] = value;
}
}
public void AddRow()
{
rows.Add(new Dictionary<string, object>());
}
string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
public string Export()
{
StringBuilder sb = new StringBuilder();
// if there is a title
if (!string.IsNullOrEmpty(addTitle))
{
// escape chars that would otherwise break the row / export
char[] csvTokens = new[] { '\"', ',', '\n', '\r' };
if (addTitle.IndexOfAny(csvTokens) >= 0)
{
addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
}
sb.Append(addTitle).Append(",");
sb.AppendLine();
}
// The header
foreach (string field in fields)
sb.Append(field).Append(",");
sb.AppendLine();
// The rows
foreach (Dictionary<string, object> row in rows)
{
foreach (string field in fields)
sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
sb.AppendLine();
}
return sb.ToString();
}
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
}
There is an issue open with respect to this.
For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.
Here is a sample playbook:
- name: "Empty directory"
hosts: *
tasks:
- name: "Create an empty directory (locally)"
local_action:
module: file
state: directory
path: "/tmp/empty"
- name: Empty remote directory
synchronize:
src: /tmp/empty/
dest: /home/mydata/web/
delete: yes
recursive: yes
The DateTime.Now
property returns the current date and time, for example 2011-07-01 10:09.45310
.
The DateTime.Today
property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000
.
The DateTime.Today
property actually is implemented to return DateTime.Now.Date
:
public static DateTime Today {
get {
DateTime now = DateTime.Now;
return now.Date;
}
}
If you don't know the column names and you want to specify str data type to all columns:
table = pd.read_excel("path_to_filename")
cols = table.columns
conv = dict(zip(cols ,[str] * len(cols)))
table = pd.read_excel("path_to_filename", converters=conv)
std::fill_n(array, elementCount, 0);
Assuming array
is a normal array (e.g. int[]
)
In my case, I created a self-signed certificate and had it working, except I was getting an error in the browser because the certificate was untrusted. So, I moved the cert into the Trusted Root Certification Authorities > Certificates folder in the Certificates snapin. It worked, and then I closed Visual Studio for the day.
The following day, I started my project and I received the error mentioned in the original question. The issue is that the certificate you configured IISExpress with must exist in the Personal > Certificates folder or HTTPS will stop working. Once IIS Express successfully starts, you can drag the cert back to the trusted location. It'll continue to work until you restart IIS Express.
Not wanting to fuss with dragging the cert back and forth every time, I just place a copy of the certificate in both places and now everything works fine.
First, make an ifstream
:
#include <fstream>
std::ifstream infile("thefile.txt");
The two standard methods are:
Assume that every line consists of two numbers and read token by token:
int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
Line-based parsing, using string streams:
#include <sstream>
#include <string>
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; } // error
// process pair (a,b)
}
You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline()
after token-based extraction got you to the end of a line already.
I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.
Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.
In Python, people actually care for that kind of overhead, so that you can embrace the following practice :
@property
to implement them without changing the syntax of the rest of your code.This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
This is an old question, nevertheless this topic never ceases to bug me.
As many of the answers here and across the web focus on "enforcing" the interface, I'd like to suggest an alternative view:
I feel the lack of interfaces the most when I'm using multiple classes that behave similarly (i.e. implement an interface).
For example, I have an Email Generator that expects to receive Email Sections Factories, that "know" how to generate the sections' content and HTML. Hence, they all need to have some sort of getContent(id)
and getHtml(content)
methods.
The closest pattern to interfaces (albeit it's still a workaround) I could think of is using a class that'll get 2 arguments, which will define the 2 interface methods.
The main challenge with this pattern is that the methods either have to be static
, or to get as argument the instance itself, in order to access its properties. However there are cases in which I find this trade-off worth the hassle.
class Filterable {_x000D_
constructor(data, { filter, toString }) {_x000D_
this.data = data;_x000D_
this.filter = filter;_x000D_
this.toString = toString;_x000D_
// You can also enforce here an Iterable interface, for example,_x000D_
// which feels much more natural than having an external check_x000D_
}_x000D_
}_x000D_
_x000D_
const evenNumbersList = new Filterable(_x000D_
[1, 2, 3, 4, 5, 6], {_x000D_
filter: (lst) => {_x000D_
const evenElements = lst.data.filter(x => x % 2 === 0);_x000D_
lst.data = evenElements;_x000D_
},_x000D_
toString: lst => `< ${lst.data.toString()} >`,_x000D_
}_x000D_
);_x000D_
_x000D_
console.log('The whole list: ', evenNumbersList.toString(evenNumbersList));_x000D_
evenNumbersList.filter(evenNumbersList);_x000D_
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
_x000D_
I needed to update and add suffix to few rows of the dataframe on conditional basis based on the another column's value of the same dataframe -
df with column Feature and Entity and need to update Entity based on specific feature type
df2= df1 df.loc[df.Feature == 'dnb', 'Entity'] = 'duns_' + df.loc[df.Feature == 'dnb','Entity']
Spring is an application framework which deals with IOC (Inversion of Control).
Struts 2 is a web application MVC framework which deals with actions.
Hibernate is an ORM (Object-Relational Mapping) that deals with persistent data.
Here's a working example, which is a fork of this answer:
$(document).ready(function(){
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
}
);
} else {
// user is not logged in
}
});
});
I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:
$(document).ready(function() {
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
FB.api('/me/likes/'+page_id, function(response) {
if (response.data[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
});
} else {
// user is not logged in
}
});
});?
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel
I would recommend to use: Git Lens.
In my case, it is due to a case-sensitivity typo in import path. For example,
Should be:
import Dashboard from './Dashboard/dashboard';
Instead of:
import Dashboard from './Dashboard/Dashboard';
As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:
<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 26 42"
width="26px" height="42px">
if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.
(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)
I would prefer AssertJ for this.
assertThatExceptionOfType(ExpectedException.class)
.isThrownBy(() -> {
// method call
}).withMessage("My message");
you can do like this. imageuri can be converted into string like this.
intent.putExtra("imageUri", imageUri.toString());
An alternative to using LINQ:
var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;
I have found using HashSet<T>
is quicker for lists of up to ~ 6,000 integers compared with:
var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;
What if the ad provider's view is not added to self.view
but to something like [UIApplication sharedApplication].keyWindow
?
Try something like:
[[UIApplication sharedApplication].keyWindow addSubview:yourSubview]
or
[[UIApplication sharedApplication].keyWindow bringSubviewToFront:yourSubview]
OneToOneField (one-to-one) realizes, in object orientation, the notion of composition, while ForeignKey (one-to-many) relates to agregation.
You import the function from outside the main instance, and don't add it to the methods block. so the context of this
is not the vm.
Either do this:
ready() {
checkAuth.call(this)
}
or add the method to your methods first (which will make Vue bind this
correctly for you) and call this method:
methods: {
checkAuth: checkAuth
},
ready() {
this.checkAuth()
}
jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML
.
Here's the regex:
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi
And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script>
section may not contain </script>
at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script
etc. will still work.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
A simple Google led me to pyTTS, and a few documents about it. It looks unmaintained and specific to Microsoft's speech engine, however.
On at least Mac OS X, you can use subprocess
to call out to the say
command, which is quite fun for messing with your coworkers but might not be terribly useful for your needs.
It sounds like Festival has a few public APIs, too:
Festival offers a BSD socket-based interface. This allows Festival to run as a server and allow client programs to access it. Basically the server offers a new command interpreter for each client that attaches to it. The server is forked for each client but this is much faster than having to wait for a Festival process to start from scratch. Also the server can run on a bigger machine, offering much faster synthesis. linky
There's also a full-featured C++ API, which you might be able to make a Python module out of (it's fun!). Festival also offers a pared-down C API -- keep scrolling in that document -- which you might be able to throw ctypes
at for a one-off.
Perhaps you've identified a hole in the market?
There are some very good answers here. I'd like to add the following here as well:
some_dict = {
"foo": "bar",
"lorem": "ipsum"
}
for index, (key, value) in enumerate(some_dict.items()):
print(index, key, value)
results in
0 foo bar
1 lorem ipsum
Appears to work with Python 2.7
and 3.5
One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
You can also try Nullable(T) Properties:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
if (s[i] == 'H') count++;
It just checks every character in the string, if the character is the character you are searching for, add one to count.
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
select
Roles
from
MyTable
where
Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'
In case your column is not XML
, you need to convert it. You can also use other syntax to query certain attributes of your XML data. Here is an example...
Let's suppose that data column has this:
<Utilities.CodeSystems.CodeSystemCodes iid="107" CodeSystem="2" Code="0001F" CodeTags="-19-"..../>
... and you only want the ones where CodeSystem = 2
then your query will be:
select
[data]
from
[dbo].[CodeSystemCodes_data]
where
CAST([data] as XML).value('(/Utilities.CodeSystems.CodeSystemCodes/@CodeSystem)[1]', 'varchar(max)') = '2'
These pages will show you more about how to query XML in T-SQL:
Querying XML fields using t-sql
Flattening XML Data in SQL Server
EDIT
After playing with it a little bit more, I ended up with this amazing query that uses CROSS APPLY. This one will search every row (role) for the value you put in your like expression...
Given this table structure:
create table MyTable (Roles XML)
insert into MyTable values
('<root>
<role>Alpha</role>
<role>Gamma</role>
<role>Beta</role>
</root>')
We can query it like this:
select * from
(select
pref.value('(text())[1]', 'varchar(32)') as RoleName
from
MyTable CROSS APPLY
Roles.nodes('/root/role') AS Roles(pref)
) as Result
where RoleName like '%ga%'
You can check the SQL Fiddle here: http://sqlfiddle.com/#!18/dc4d2/1/0
In your case, ('AND' and 'OR' and 'NOT')
evaluates to "NOT"
, which may or may not be in your list...
while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
print 'No Boolean Operator'
After coming across this error and not finding anything on the web that set me right, I thought I'd add another reason for getting this Exception - namely that the source and destination paths in the File Copy command are the same. It took me a while to figure it out, but it may help to add code somewhere to throw an exception if source and destination paths are pointing to the same file.
Good luck!
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.
int myNr = std::stoi(myString);
It will throw an exception on conversion error.
Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: http://en.cppreference.com/w/cpp/string/basic_string/stol
There's one more theoretical possibility to do it: professional versions of Windows have built-in POSIX support, so bash could have been compiled for Windows natively.
Pity, but I still haven't found a compiled one myself...
This code shows how to implement the delete.
#pragma mark - UITableViewDataSource
// Swipe to delete.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_chats removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
Optionally, in your initialization override, add the line below to show the Edit button item:
self.navigationItem.leftBarButtonItem = self.editButtonItem;
In reply to Dimitrys answer but using Ajax.BeginForm
the following works at least with MVC >5 (4 not tested).
write a model as shown in the other answers,
In the "parent view" you will probably use a table to show the data.
Model should be an ienumerable. I assume, the model has an id
-property. Howeverm below the template, a placeholder for the modal and corresponding javascript
<table>
@foreach (var item in Model)
{
<tr> <td id="[email protected]">
@Html.Partial("dataRowView", item)
</td> </tr>
}
</table>
<div class="modal fade" id="editor-container" tabindex="-1"
role="dialog" aria-labelledby="editor-title">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" id="editor-content-container"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.editor-container').click(function () {
var url = "/area/controller/MyEditAction";
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
});
});
});
function success(data,status,xhr) {
$('#editor-container').modal('hide');
$('#editor-content-container').html("");
}
function failure(xhr,status,error) {
$('#editor-content-container').html(xhr.responseText);
$('#editor-container').modal('show');
}
</script>
note the "editor-success-id" in data table rows.
The dataRowView
is a partial containing the presentation of an model's item.
@model ModelView
@{
var item = Model;
}
<div class="row">
// some data
<button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ...
).
@model Model
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "editor-success-" + @Model.Id,
OnSuccess = "success",
OnFailure = "failure",
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div class="modal-body">
<div class="form-horizontal">
// Models input fields
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
This is where magic happens: in AjaxOptions
, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.
This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.
But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:
the corresponding controller action method for the partial edit modal
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
// Find the data row and return the edit form
Model input = await db.Models.FindAsync(id);
return PartialView("EditModel", input);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
"Id,Fields,...")] ModelView input)
{
if (TryValidateModel(input))
{
// save changes, return new data row
// status code is something in 200-range
db.Entry(input).State = EntityState.Modified;
await db.SaveChangesAsync();
return PartialView("dataRowView", (ModelView)input);
}
// set the "error status code" that will redisplay the modal
Response.StatusCode = 400;
// and return the edit form, that will be displayed as a
// modal again - including the modelstate errors!
return PartialView("EditModel", (Model)input);
}
This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.
Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js
(may be installed by NuGet):
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.
In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.
Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip
Then import it into Eclipse.
If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip
An alterntive is to use an enum and a component class that extends the standard RadioButton.
public enum Genders
{
Male,
Female
}
[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
public GenderRadioButton()
{
InitializeComponent();
}
public GenderRadioButton (IContainer container)
{
container.Add(this);
InitializeComponent();
}
public Genders gender{ get; set; }
}
Use a common event handler for the GenderRadioButtons
private void Gender_CheckedChanged(Object sender, EventArgs e)
{
if (((RadioButton)sender).Checked)
{
//get selected value
Genders myGender = ((GenderRadioButton)sender).Gender;
//get the name of the enum value
string GenderName = Enum.GetName(typeof(Genders ), myGender);
//do any work required when you change gender
switch (myGender)
{
case Genders.Male:
break;
case Genders.Female:
break;
default:
break;
}
}
}
For Asp.Net MVC
@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList,
new {
@class = "chosen-select form-control"
})
or
@Html.ListBoxFor(model => model.parameterName,
ViewBag.ParameterValueList as MultiSelectList,
new{
data_placeholder = "Select Options ",
@class = "chosen-select form-control"
})
I Recommend you implement INotifyPropertyChanged and change your databinding code to this:
this.textBox.DataBindings.Add("Text",
this.Food,
"Name",
false,
DataSourceUpdateMode.OnPropertyChanged);
That'll fix it.
Note that the default DataSourceUpdateMode
is OnValidation
, so if you don't specify OnPropertyChanged
, the model object won't be updated until after your validations have occurred.
its an old question but anyway heres something i used incase someone was looking for the same thing
if (!$('#myModal').is(':visible')) {
// if modal is not shown/visible then do something
}
oImg.setAttribute('width', '1px');
px
is for CSS only. Use either:
oImg.width = '1';
to set a width through HTML, or:
oImg.style.width = '1px';
to set it through CSS.
Note that old versions of IE don't create a proper image with document.createElement()
, and old versions of KHTML don't create a proper DOM Node with new Image()
, so if you want to be fully backwards compatible use something like:
// IEWIN boolean previously sniffed through eg. conditional comments
function img_create(src, alt, title) {
var img = IEWIN ? new Image() : document.createElement('img');
img.src = src;
if ( alt != null ) img.alt = alt;
if ( title != null ) img.title = title;
return img;
}
Also be slightly wary of document.body.appendChild
if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body>
element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild)
.
To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div>
as the body's first child and put any tracking/preload images you don't want to be visible in there.
For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.
You have to account for all values in the pivot set. you can accomplish this using a cartesian product.
select pivoted.*
from (
select cartesian.key1, cartesian.key2, isnull(relationship.[value],'nullvalue') as [value]
from (
select k1.key1, k2.key2
from ( select distinct key1 from relationship) k1
,( select distinct key2 from relationship) k2
) cartesian
left outer join relationship on relationship.key1 = cartesian.key1 and relationship.key2 = carterisan.key2
) data
pivot (
max(data.value) for ([key2_v1], [key2_v2], [key2_v3], ...)
) pivoted
/*Maximum value that can be entered is 2,147,483,647
* Program to convert entered number into string
* */
import java.util.Scanner;
public class NumberToWords
{
public static void main(String[] args)
{
double num;//for taking input number
Scanner obj=new Scanner(System.in);
do
{
System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
num=obj.nextDouble();
if(num<=2147483647)//checking if entered number exceeds maximum integer value
{
int number=(int)num;//type casting double number to integer number
splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
}
else
System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
}while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{ //splitNumber array-contains the numbers in pair of 3 digits
int splitNumber[]=new int[4],temp=number,i=0,index;
//splitting number into pair of 3
if(temp==0)
System.out.println("zero");
while(temp!=0)
{
splitNumber[i++]=temp%1000;
temp/=1000;
}
//passing each pair of 3 digits to another function
for(int j=i-1;j>-1;j--)
{ //toWords function will split pair of 3 digits to separate digits
if(splitNumber[j]!=0)
{toWords(splitNumber[j]);
if(j==3)//if the number contained more than 9 digits
System.out.print("billion,");
else if(j==2)//if the number contained more than 6 digits & less than 10 digits
System.out.print("million,");
else if(j==1)
System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
}
}
}
//function that splits number into individual digits
public static void toWords(int number)
//splitSmallNumber array contains individual digits of number passed to this function
{ int splitSmallNumber[]=new int[3],i=0,j;
int temp=number;//making temporary copy of the number
//logic to split number into its constituent digits
while(temp!=0)
{
splitSmallNumber[i++]=temp%10;
temp/=10;
}
//printing words for each digit
for(j=i-1;j>-1;j--)
//{ if the digit is greater than zero
if(splitSmallNumber[j]>=0)
//if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
{ if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
{
switch(splitSmallNumber[j])
{
case 1:System.out.print("one ");break;
case 2:System.out.print("two ");break;
case 3:System.out.print("three ");break;
case 4:System.out.print("four ");break;
case 5:System.out.print("five ");break;
case 6:System.out.print("six ");break;
case 7:System.out.print("seven ");break;
case 8:System.out.print("eight ");break;
case 9:System.out.print("nine ");break;
}
}
//if digit is at 2nd place
if(j==1)
{ //if digit at 2nd place is 0 or 1
if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
System.out.print("hundred ");
switch(splitSmallNumber[1])
{ case 1://if digit at 2nd place is 1 example-213
switch(splitSmallNumber[0])
{
case 1:System.out.print("eleven ");break;
case 2:System.out.print("twelve ");break;
case 3:System.out.print("thirteen ");break;
case 4:System.out.print("fourteen ");break;
case 5:System.out.print("fifteen ");break;
case 6:System.out.print("sixteen ");break;
case 7:System.out.print("seventeen ");break;
case 8:System.out.print("eighteen ");break;
case 9:System.out.print("nineteen ");break;
case 0:System.out.print("ten ");break;
}break;
//if digit at 2nd place is not 1
case 2:System.out.print("twenty ");break;
case 3:System.out.print("thirty ");break;
case 4:System.out.print("forty ");break;
case 5:System.out.print("fifty ");break;
case 6:System.out.print("sixty ");break;
case 7:System.out.print("seventy ");break;
case 8:System.out.print("eighty ");break;
case 9:System.out.print("ninety ");break;
//case 0: System.out.println("hundred ");break;
}
}
}
}
}
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
Both the methods are defined in Object class. And both are in its simplest implementation. So when you need you want add some more implementation to these methods then you have override in your class.
For Ex: equals() method in object only checks its equality on the reference. So if you need compare its state as well then you can override that as it is done in String class.
I'm trying to get nearest lower power of 2 and made this function. May it help you.Just multiplied nearest lower number times 2 to get nearest upper power of 2
int nearest_upper_power(int number){
int temp=number;
while((number&(number-1))!=0){
temp<<=1;
number&=temp;
}
//Here number is closest lower power
number*=2;
return number;
}
if you are using jQuery; this is one a way to do it:
$('.link').each(function() {
$(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});
Here is an easier to read version doing the same thing:
//Iterate all the elements in jQuery object
$('.link').each(function() {
//get text from element and make it lower-case
var string = $(this).text().toLowerCase();
//set element text to the new string that is lower-case
$(this).text(string);
//set the css to capitalize
$(this).css('text-transform','capitalize');
});
A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.
That said, you can turn the string into a byte array and then look at its size as follows:
// The input string for this test
final String string = "Hello World";
// Check length, in characters
System.out.println(string.length()); // prints "11"
// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"
final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"
final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"
final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"
final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"
So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes()
. And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:
final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms
// Check length, in characters
System.out.println(interesting.length()); // prints "4"
// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"
final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"
final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"
final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")
final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")
(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)
Very similar to Holger's answer. If you need to grab the URL can do something like:
Uri uri = Context.Request.Url;
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number
The Uri class provides a whole range of methods, many which I have not listed.
In my instance, I needed to grab LocalHost
along with the Port Number
, so this is what I did:
var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Which successfully grabbed: http://localhost:12345
When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.
In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.
A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.
Taken from The Open University M362 Unit 3 "Interacting process" course material.
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
Maybe a better solution would be to add an extra column that is automatically set to 1 on each row. As soon as there is an element that is not null change it to a 0.
then
If(drEntitity.rows[i].coulmn[8] = 1)
{
dtEntity.Rows.Add(drEntity);
}
else
{
//don't add, will create a new one (drEntity = dtEntity.NewRow();)
}
My 2 cents on the problem: I was experiencing the same problem, while some part of my path was in Cyrillic. So check the path to your project for special characters. Once I removed this, the problem was fixed
If you are working with character variables (note that stringsAsFactors
is false here) you can use replace:
junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")
junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
# nm val
# 1 A a
# 2 b b
# 3 C c
# 4 D d
# ...
The following batch file is based on twalberg's answer but will work in Windows:
@ECHO OFF
C: :: <== OR USE A DIFFERENT DRIVE
CD \path\to\where\git\files\are :: <== CHANGE TO THE ACTUAL PATH
SET /p b="Enter full path of an ALREADY MERGED branch to compare with origin/master: "
bash --login -i -c "git diff --name-only %b% $(git merge-base %b1% origin/drop2/master)"
PAUSE
The above assumes that the main branch is origin/master and that git bash was included when Git was installed (and its location is in the path environment). I actually needed to show the actual differences using a configured diff tool (kdiff3) so substituted the following bash command above:
bash --login -i -c "git difftool --dir-diff %b% $(git merge-base %b1% origin/drop2/master)"
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
Update 2019.
You can now use the object-fit
css property that accepts the following values: fill | contain | cover | none | scale-down
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
As an example, you could have a container that holds an image.
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
I think sometimes it's just enogh to simply restart the virtual device. :-)
Add background dynamically in onCreate
method:
getWindow().setBackgroundDrawableResource(R.drawable.background);
also remove background from XML.
This workaround is simpler and more elegant than explode:
$my_date = str_replace("/", ".", $my_date);
$my_date = strtotime($my_date);
$my_date = date("Y-m-d", $my_date);
You don't have to know what format you're getting the date in, but if it comes with slashes they are replaced with full stops and it is treated as European by strtotime.
Java itself has no equivalent features, but third-party libraries exist which offer similar functionality, e.g.Kilim.
Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.
const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\" }";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
using (System.IO.Stream s = webRequest.GetRequestStream())
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
sw.Write(jsonData);
}
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
php.net: http://php.net/manual/pt_BR/function.error-reporting.php
You could use a CASE statement, like
SELECT name
,address
,CASE WHEN a < b THEN '1'
ELSE '2' END AS one_or_two
FROM ...
There is another way which doesn't rely on defining functions (because sometimes that's less readable for small code snippets), doesn't use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn't use goto (...) and most importantly let's you keep your indentation level for the outer if so you don't have to start nesting stuff.
if some_condition:
...
if condition_a:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
# keep doing something
if condition_b:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if:
# keep doing something
Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn't require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it's easily readable, all in one place and with the same indentation.
And it should be pretty efficient.
The following works in MVC5:
document.getElementById('theID').value = 'new value';
You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.
MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.
InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.
This helped me understand / streamline, only what I needed to animate:
// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}
.base {
max-width: 0vw;
opacity: 0;
transition-property: max-width, opacity; // relative order
transition-duration: 2s, 4s; // effects relatively ordered animation properties
transition-delay: 6s; // effects delay of all animation properties
animation-timing-function: ease;
&:hover {
max-width: 100vw;
opacity: 1;
transition-duration: 5s; // effects duration of all aniomation properties
transition-delay: 2s, 7s; // effects relatively ordered animation properties
}
}
~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
export default class App extends Component {
render() {
return (
<View>// you need to wrap the two Views an another View
<View style={styles.box1}></View>
<View style={styles.box2}></View>
</View>
);
}
}
const styles = StyleSheet.create({
box1:{
height:100,
width:100,
backgroundColor:'red'
},
box2:{
height:100,
width:100,
backgroundColor:'green',
position: 'absolute',
top:10,
left:30
},
});
function getLocaleShortDateString(d)
{
var f={"ar-SA":"dd/MM/yy","bg-BG":"dd.M.yyyy","ca-ES":"dd/MM/yyyy","zh-TW":"yyyy/M/d","cs-CZ":"d.M.yyyy","da-DK":"dd-MM-yyyy","de-DE":"dd.MM.yyyy","el-GR":"d/M/yyyy","en-US":"M/d/yyyy","fi-FI":"d.M.yyyy","fr-FR":"dd/MM/yyyy","he-IL":"dd/MM/yyyy","hu-HU":"yyyy. MM. dd.","is-IS":"d.M.yyyy","it-IT":"dd/MM/yyyy","ja-JP":"yyyy/MM/dd","ko-KR":"yyyy-MM-dd","nl-NL":"d-M-yyyy","nb-NO":"dd.MM.yyyy","pl-PL":"yyyy-MM-dd","pt-BR":"d/M/yyyy","ro-RO":"dd.MM.yyyy","ru-RU":"dd.MM.yyyy","hr-HR":"d.M.yyyy","sk-SK":"d. M. yyyy","sq-AL":"yyyy-MM-dd","sv-SE":"yyyy-MM-dd","th-TH":"d/M/yyyy","tr-TR":"dd.MM.yyyy","ur-PK":"dd/MM/yyyy","id-ID":"dd/MM/yyyy","uk-UA":"dd.MM.yyyy","be-BY":"dd.MM.yyyy","sl-SI":"d.M.yyyy","et-EE":"d.MM.yyyy","lv-LV":"yyyy.MM.dd.","lt-LT":"yyyy.MM.dd","fa-IR":"MM/dd/yyyy","vi-VN":"dd/MM/yyyy","hy-AM":"dd.MM.yyyy","az-Latn-AZ":"dd.MM.yyyy","eu-ES":"yyyy/MM/dd","mk-MK":"dd.MM.yyyy","af-ZA":"yyyy/MM/dd","ka-GE":"dd.MM.yyyy","fo-FO":"dd-MM-yyyy","hi-IN":"dd-MM-yyyy","ms-MY":"dd/MM/yyyy","kk-KZ":"dd.MM.yyyy","ky-KG":"dd.MM.yy","sw-KE":"M/d/yyyy","uz-Latn-UZ":"dd/MM yyyy","tt-RU":"dd.MM.yyyy","pa-IN":"dd-MM-yy","gu-IN":"dd-MM-yy","ta-IN":"dd-MM-yyyy","te-IN":"dd-MM-yy","kn-IN":"dd-MM-yy","mr-IN":"dd-MM-yyyy","sa-IN":"dd-MM-yyyy","mn-MN":"yy.MM.dd","gl-ES":"dd/MM/yy","kok-IN":"dd-MM-yyyy","syr-SY":"dd/MM/yyyy","dv-MV":"dd/MM/yy","ar-IQ":"dd/MM/yyyy","zh-CN":"yyyy/M/d","de-CH":"dd.MM.yyyy","en-GB":"dd/MM/yyyy","es-MX":"dd/MM/yyyy","fr-BE":"d/MM/yyyy","it-CH":"dd.MM.yyyy","nl-BE":"d/MM/yyyy","nn-NO":"dd.MM.yyyy","pt-PT":"dd-MM-yyyy","sr-Latn-CS":"d.M.yyyy","sv-FI":"d.M.yyyy","az-Cyrl-AZ":"dd.MM.yyyy","ms-BN":"dd/MM/yyyy","uz-Cyrl-UZ":"dd.MM.yyyy","ar-EG":"dd/MM/yyyy","zh-HK":"d/M/yyyy","de-AT":"dd.MM.yyyy","en-AU":"d/MM/yyyy","es-ES":"dd/MM/yyyy","fr-CA":"yyyy-MM-dd","sr-Cyrl-CS":"d.M.yyyy","ar-LY":"dd/MM/yyyy","zh-SG":"d/M/yyyy","de-LU":"dd.MM.yyyy","en-CA":"dd/MM/yyyy","es-GT":"dd/MM/yyyy","fr-CH":"dd.MM.yyyy","ar-DZ":"dd-MM-yyyy","zh-MO":"d/M/yyyy","de-LI":"dd.MM.yyyy","en-NZ":"d/MM/yyyy","es-CR":"dd/MM/yyyy","fr-LU":"dd/MM/yyyy","ar-MA":"dd-MM-yyyy","en-IE":"dd/MM/yyyy","es-PA":"MM/dd/yyyy","fr-MC":"dd/MM/yyyy","ar-TN":"dd-MM-yyyy","en-ZA":"yyyy/MM/dd","es-DO":"dd/MM/yyyy","ar-OM":"dd/MM/yyyy","en-JM":"dd/MM/yyyy","es-VE":"dd/MM/yyyy","ar-YE":"dd/MM/yyyy","en-029":"MM/dd/yyyy","es-CO":"dd/MM/yyyy","ar-SY":"dd/MM/yyyy","en-BZ":"dd/MM/yyyy","es-PE":"dd/MM/yyyy","ar-JO":"dd/MM/yyyy","en-TT":"dd/MM/yyyy","es-AR":"dd/MM/yyyy","ar-LB":"dd/MM/yyyy","en-ZW":"M/d/yyyy","es-EC":"dd/MM/yyyy","ar-KW":"dd/MM/yyyy","en-PH":"M/d/yyyy","es-CL":"dd-MM-yyyy","ar-AE":"dd/MM/yyyy","es-UY":"dd/MM/yyyy","ar-BH":"dd/MM/yyyy","es-PY":"dd/MM/yyyy","ar-QA":"dd/MM/yyyy","es-BO":"dd/MM/yyyy","es-SV":"dd/MM/yyyy","es-HN":"dd/MM/yyyy","es-NI":"dd/MM/yyyy","es-PR":"dd/MM/yyyy","am-ET":"d/M/yyyy","tzm-Latn-DZ":"dd-MM-yyyy","iu-Latn-CA":"d/MM/yyyy","sma-NO":"dd.MM.yyyy","mn-Mong-CN":"yyyy/M/d","gd-GB":"dd/MM/yyyy","en-MY":"d/M/yyyy","prs-AF":"dd/MM/yy","bn-BD":"dd-MM-yy","wo-SN":"dd/MM/yyyy","rw-RW":"M/d/yyyy","qut-GT":"dd/MM/yyyy","sah-RU":"MM.dd.yyyy","gsw-FR":"dd/MM/yyyy","co-FR":"dd/MM/yyyy","oc-FR":"dd/MM/yyyy","mi-NZ":"dd/MM/yyyy","ga-IE":"dd/MM/yyyy","se-SE":"yyyy-MM-dd","br-FR":"dd/MM/yyyy","smn-FI":"d.M.yyyy","moh-CA":"M/d/yyyy","arn-CL":"dd-MM-yyyy","ii-CN":"yyyy/M/d","dsb-DE":"d. M. yyyy","ig-NG":"d/M/yyyy","kl-GL":"dd-MM-yyyy","lb-LU":"dd/MM/yyyy","ba-RU":"dd.MM.yy","nso-ZA":"yyyy/MM/dd","quz-BO":"dd/MM/yyyy","yo-NG":"d/M/yyyy","ha-Latn-NG":"d/M/yyyy","fil-PH":"M/d/yyyy","ps-AF":"dd/MM/yy","fy-NL":"d-M-yyyy","ne-NP":"M/d/yyyy","se-NO":"dd.MM.yyyy","iu-Cans-CA":"d/M/yyyy","sr-Latn-RS":"d.M.yyyy","si-LK":"yyyy-MM-dd","sr-Cyrl-RS":"d.M.yyyy","lo-LA":"dd/MM/yyyy","km-KH":"yyyy-MM-dd","cy-GB":"dd/MM/yyyy","bo-CN":"yyyy/M/d","sms-FI":"d.M.yyyy","as-IN":"dd-MM-yyyy","ml-IN":"dd-MM-yy","en-IN":"dd-MM-yyyy","or-IN":"dd-MM-yy","bn-IN":"dd-MM-yy","tk-TM":"dd.MM.yy","bs-Latn-BA":"d.M.yyyy","mt-MT":"dd/MM/yyyy","sr-Cyrl-ME":"d.M.yyyy","se-FI":"d.M.yyyy","zu-ZA":"yyyy/MM/dd","xh-ZA":"yyyy/MM/dd","tn-ZA":"yyyy/MM/dd","hsb-DE":"d. M. yyyy","bs-Cyrl-BA":"d.M.yyyy","tg-Cyrl-TJ":"dd.MM.yy","sr-Latn-BA":"d.M.yyyy","smj-NO":"dd.MM.yyyy","rm-CH":"dd/MM/yyyy","smj-SE":"yyyy-MM-dd","quz-EC":"dd/MM/yyyy","quz-PE":"dd/MM/yyyy","hr-BA":"d.M.yyyy.","sr-Latn-ME":"d.M.yyyy","sma-SE":"yyyy-MM-dd","en-SG":"d/M/yyyy","ug-CN":"yyyy-M-d","sr-Cyrl-BA":"d.M.yyyy","es-US":"M/d/yyyy"};
var l=navigator.language?navigator.language:navigator['userLanguage'],y=d.getFullYear(),m=d.getMonth()+1,d=d.getDate();
f=(l in f)?f[l]:"MM/dd/yyyy";
function z(s){s=''+s;return s.length>1?s:'0'+s;}
f=f.replace(/yyyy/,y);f=f.replace(/yy/,String(y).substr(2));
f=f.replace(/MM/,z(m));f=f.replace(/M/,m);
f=f.replace(/dd/,z(d));f=f.replace(/d/,d);
return f;
}
using:
shortedDate=getLocaleShortDateString(new Date(1992, 0, 7));
shortedDate = getLocaleShortDateString(new Date(1992, 0, 7));_x000D_
console.log(shortedDate);_x000D_
_x000D_
function getLocaleShortDateString(d) {_x000D_
var f={"ar-SA":"dd/MM/yy","bg-BG":"dd.M.yyyy","ca-ES":"dd/MM/yyyy","zh-TW":"yyyy/M/d","cs-CZ":"d.M.yyyy","da-DK":"dd-MM-yyyy","de-DE":"dd.MM.yyyy","el-GR":"d/M/yyyy","en-US":"M/d/yyyy","fi-FI":"d.M.yyyy","fr-FR":"dd/MM/yyyy","he-IL":"dd/MM/yyyy","hu-HU":"yyyy. MM. dd.","is-IS":"d.M.yyyy","it-IT":"dd/MM/yyyy","ja-JP":"yyyy/MM/dd","ko-KR":"yyyy-MM-dd","nl-NL":"d-M-yyyy","nb-NO":"dd.MM.yyyy","pl-PL":"yyyy-MM-dd","pt-BR":"d/M/yyyy","ro-RO":"dd.MM.yyyy","ru-RU":"dd.MM.yyyy","hr-HR":"d.M.yyyy","sk-SK":"d. M. yyyy","sq-AL":"yyyy-MM-dd","sv-SE":"yyyy-MM-dd","th-TH":"d/M/yyyy","tr-TR":"dd.MM.yyyy","ur-PK":"dd/MM/yyyy","id-ID":"dd/MM/yyyy","uk-UA":"dd.MM.yyyy","be-BY":"dd.MM.yyyy","sl-SI":"d.M.yyyy","et-EE":"d.MM.yyyy","lv-LV":"yyyy.MM.dd.","lt-LT":"yyyy.MM.dd","fa-IR":"MM/dd/yyyy","vi-VN":"dd/MM/yyyy","hy-AM":"dd.MM.yyyy","az-Latn-AZ":"dd.MM.yyyy","eu-ES":"yyyy/MM/dd","mk-MK":"dd.MM.yyyy","af-ZA":"yyyy/MM/dd","ka-GE":"dd.MM.yyyy","fo-FO":"dd-MM-yyyy","hi-IN":"dd-MM-yyyy","ms-MY":"dd/MM/yyyy","kk-KZ":"dd.MM.yyyy","ky-KG":"dd.MM.yy","sw-KE":"M/d/yyyy","uz-Latn-UZ":"dd/MM yyyy","tt-RU":"dd.MM.yyyy","pa-IN":"dd-MM-yy","gu-IN":"dd-MM-yy","ta-IN":"dd-MM-yyyy","te-IN":"dd-MM-yy","kn-IN":"dd-MM-yy","mr-IN":"dd-MM-yyyy","sa-IN":"dd-MM-yyyy","mn-MN":"yy.MM.dd","gl-ES":"dd/MM/yy","kok-IN":"dd-MM-yyyy","syr-SY":"dd/MM/yyyy","dv-MV":"dd/MM/yy","ar-IQ":"dd/MM/yyyy","zh-CN":"yyyy/M/d","de-CH":"dd.MM.yyyy","en-GB":"dd/MM/yyyy","es-MX":"dd/MM/yyyy","fr-BE":"d/MM/yyyy","it-CH":"dd.MM.yyyy","nl-BE":"d/MM/yyyy","nn-NO":"dd.MM.yyyy","pt-PT":"dd-MM-yyyy","sr-Latn-CS":"d.M.yyyy","sv-FI":"d.M.yyyy","az-Cyrl-AZ":"dd.MM.yyyy","ms-BN":"dd/MM/yyyy","uz-Cyrl-UZ":"dd.MM.yyyy","ar-EG":"dd/MM/yyyy","zh-HK":"d/M/yyyy","de-AT":"dd.MM.yyyy","en-AU":"d/MM/yyyy","es-ES":"dd/MM/yyyy","fr-CA":"yyyy-MM-dd","sr-Cyrl-CS":"d.M.yyyy","ar-LY":"dd/MM/yyyy","zh-SG":"d/M/yyyy","de-LU":"dd.MM.yyyy","en-CA":"dd/MM/yyyy","es-GT":"dd/MM/yyyy","fr-CH":"dd.MM.yyyy","ar-DZ":"dd-MM-yyyy","zh-MO":"d/M/yyyy","de-LI":"dd.MM.yyyy","en-NZ":"d/MM/yyyy","es-CR":"dd/MM/yyyy","fr-LU":"dd/MM/yyyy","ar-MA":"dd-MM-yyyy","en-IE":"dd/MM/yyyy","es-PA":"MM/dd/yyyy","fr-MC":"dd/MM/yyyy","ar-TN":"dd-MM-yyyy","en-ZA":"yyyy/MM/dd","es-DO":"dd/MM/yyyy","ar-OM":"dd/MM/yyyy","en-JM":"dd/MM/yyyy","es-VE":"dd/MM/yyyy","ar-YE":"dd/MM/yyyy","en-029":"MM/dd/yyyy","es-CO":"dd/MM/yyyy","ar-SY":"dd/MM/yyyy","en-BZ":"dd/MM/yyyy","es-PE":"dd/MM/yyyy","ar-JO":"dd/MM/yyyy","en-TT":"dd/MM/yyyy","es-AR":"dd/MM/yyyy","ar-LB":"dd/MM/yyyy","en-ZW":"M/d/yyyy","es-EC":"dd/MM/yyyy","ar-KW":"dd/MM/yyyy","en-PH":"M/d/yyyy","es-CL":"dd-MM-yyyy","ar-AE":"dd/MM/yyyy","es-UY":"dd/MM/yyyy","ar-BH":"dd/MM/yyyy","es-PY":"dd/MM/yyyy","ar-QA":"dd/MM/yyyy","es-BO":"dd/MM/yyyy","es-SV":"dd/MM/yyyy","es-HN":"dd/MM/yyyy","es-NI":"dd/MM/yyyy","es-PR":"dd/MM/yyyy","am-ET":"d/M/yyyy","tzm-Latn-DZ":"dd-MM-yyyy","iu-Latn-CA":"d/MM/yyyy","sma-NO":"dd.MM.yyyy","mn-Mong-CN":"yyyy/M/d","gd-GB":"dd/MM/yyyy","en-MY":"d/M/yyyy","prs-AF":"dd/MM/yy","bn-BD":"dd-MM-yy","wo-SN":"dd/MM/yyyy","rw-RW":"M/d/yyyy","qut-GT":"dd/MM/yyyy","sah-RU":"MM.dd.yyyy","gsw-FR":"dd/MM/yyyy","co-FR":"dd/MM/yyyy","oc-FR":"dd/MM/yyyy","mi-NZ":"dd/MM/yyyy","ga-IE":"dd/MM/yyyy","se-SE":"yyyy-MM-dd","br-FR":"dd/MM/yyyy","smn-FI":"d.M.yyyy","moh-CA":"M/d/yyyy","arn-CL":"dd-MM-yyyy","ii-CN":"yyyy/M/d","dsb-DE":"d. M. yyyy","ig-NG":"d/M/yyyy","kl-GL":"dd-MM-yyyy","lb-LU":"dd/MM/yyyy","ba-RU":"dd.MM.yy","nso-ZA":"yyyy/MM/dd","quz-BO":"dd/MM/yyyy","yo-NG":"d/M/yyyy","ha-Latn-NG":"d/M/yyyy","fil-PH":"M/d/yyyy","ps-AF":"dd/MM/yy","fy-NL":"d-M-yyyy","ne-NP":"M/d/yyyy","se-NO":"dd.MM.yyyy","iu-Cans-CA":"d/M/yyyy","sr-Latn-RS":"d.M.yyyy","si-LK":"yyyy-MM-dd","sr-Cyrl-RS":"d.M.yyyy","lo-LA":"dd/MM/yyyy","km-KH":"yyyy-MM-dd","cy-GB":"dd/MM/yyyy","bo-CN":"yyyy/M/d","sms-FI":"d.M.yyyy","as-IN":"dd-MM-yyyy","ml-IN":"dd-MM-yy","en-IN":"dd-MM-yyyy","or-IN":"dd-MM-yy","bn-IN":"dd-MM-yy","tk-TM":"dd.MM.yy","bs-Latn-BA":"d.M.yyyy","mt-MT":"dd/MM/yyyy","sr-Cyrl-ME":"d.M.yyyy","se-FI":"d.M.yyyy","zu-ZA":"yyyy/MM/dd","xh-ZA":"yyyy/MM/dd","tn-ZA":"yyyy/MM/dd","hsb-DE":"d. M. yyyy","bs-Cyrl-BA":"d.M.yyyy","tg-Cyrl-TJ":"dd.MM.yy","sr-Latn-BA":"d.M.yyyy","smj-NO":"dd.MM.yyyy","rm-CH":"dd/MM/yyyy","smj-SE":"yyyy-MM-dd","quz-EC":"dd/MM/yyyy","quz-PE":"dd/MM/yyyy","hr-BA":"d.M.yyyy.","sr-Latn-ME":"d.M.yyyy","sma-SE":"yyyy-MM-dd","en-SG":"d/M/yyyy","ug-CN":"yyyy-M-d","sr-Cyrl-BA":"d.M.yyyy","es-US":"M/d/yyyy"};_x000D_
_x000D_
var l = navigator.language ? navigator.language : navigator['userLanguage'],_x000D_
y = d.getFullYear(),_x000D_
m = d.getMonth() + 1,_x000D_
d = d.getDate();_x000D_
f = (l in f) ? f[l] : "MM/dd/yyyy";_x000D_
_x000D_
function z(s) {_x000D_
s = '' + s;_x000D_
return s.length > 1 ? s : '0' + s;_x000D_
}_x000D_
f = f.replace(/yyyy/, y);_x000D_
f = f.replace(/yy/, String(y).substr(2));_x000D_
f = f.replace(/MM/, z(m));_x000D_
f = f.replace(/M/, m);_x000D_
f = f.replace(/dd/, z(d));_x000D_
f = f.replace(/d/, d);_x000D_
return f;_x000D_
}
_x000D_
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
To make a field required, use required
or required="true"
I think required="required"
has been deprecated in version 3 of bootstrap.
It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.
sudo mysql_secure_installation
You can use regex.findall()
:
import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)
$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));
with latitude and longitude in radian.
so
SELECT
acos(
cos(radians( $latitude0 ))
* cos(radians( $latitude1 ))
* cos(radians( $longitude0 ) - radians( $longitude1 ))
+ sin(radians( $latitude0 ))
* sin(radians( $latitude1 ))
) AS greatCircleDistance
FROM yourTable;
is your SQL query
to get your results in Km or miles, multiply the result with the mean radius of Earth (3959
miles,6371
Km or 3440
nautical miles)
The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.
SELECT
id
FROM spatialEnabledTable
WHERE
MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))
Could you use FILE*
instead, and the measure the performance you've gained?
A couple of options is to use fwrite/write
instead of fstream
:
#include <stdio.h>
int main ()
{
FILE * pFile;
char buffer[] = { 'x' , 'y' , 'z' };
pFile = fopen ( "myfile.bin" , "w+b" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose (pFile);
return 0;
}
If you decide to use write
, try something similar:
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);
if (filedesc < 0) {
return -1;
}
if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
write(2, "There was an error writing to testfile.txt\n", 43);
return -1;
}
return 0;
}
I would also advice you to look into memory map
. That may be your answer. Once I had to process a 20GB file in other to store it in the database, and the file as not even opening. So the solution as to utilize moemory map. I did that in Python
though.
SELECT
@@SERVERNAME AS ServerName,
CASE WHEN LEFT(CAST(serverproperty('productversion') as char), 1) = 9 THEN '2005'
WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 10 THEN '2008'
WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 11 THEN '2012'
END AS MajorVersion,
SERVERPROPERTY ('productlevel') AS MinorVersion,
SERVERPROPERTY('productversion') AS FullVersion,
SERVERPROPERTY ('edition') AS Edition
A nice trick to use in place of the various print formats:
(1) Pad with spaces to the right:
('hi' + ' ')[:8]
(2) Pad with leading zeros on the left:
('0000' + str(2))[-4:]
Just added to mrjandro's solution a quick hack to get rid of simple connection errors / timeouts.
You can adjust the threshold changing max_error_count variable value and add notifications of any sort.
import socket
max_error_count = 10
def increase_error_count():
# Quick hack to handle false Port not open errors
with open('ErrorCount.log') as f:
for line in f:
error_count = line
error_count = int(error_count)
print "Error counter: " + str(error_count)
file = open('ErrorCount.log', 'w')
file.write(str(error_count + 1))
file.close()
if error_count == max_error_count:
# Send email, pushover, slack or do any other fancy stuff
print "Sending out notification"
# Reset error counter so it won't flood you with notifications
file = open('ErrorCount.log', 'w')
file.write('0')
file.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print "Port is open"
else:
print "Port is not open"
increase_error_count()
And here you find a Python 3 compatible version (just fixed print syntax):
import socket
max_error_count = 10
def increase_error_count():
# Quick hack to handle false Port not open errors
with open('ErrorCount.log') as f:
for line in f:
error_count = line
error_count = int(error_count)
print ("Error counter: " + str(error_count))
file = open('ErrorCount.log', 'w')
file.write(str(error_count + 1))
file.close()
if error_count == max_error_count:
# Send email, pushover, slack or do any other fancy stuff
print ("Sending out notification")
# Reset error counter so it won't flood you with notifications
file = open('ErrorCount.log', 'w')
file.write('0')
file.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print ("Port is open")
else:
print ("Port is not open")
increase_error_count()
This suggestion is based on pixel manipulation in canvas 2d context.
From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData
and putImageData
.
getImageData
usage:
var myImageData = context.getImageData(left, top, width, height);
The putImageData
syntax:
context.putImageData(myImageData, x, y);
Where context
is your canvas 2d context, and x
and y
are the position on the canvas.
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x
is the horizontal offset, y
is the vertical offset.
The code making image half-transparent:
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:
Use e.g.
D:\Visual Studio Projects\my_app\MyFile.pdb
Dont use e.g.
$(IntDir)\MyFile.pdb
in all the Sub-Projects !!!
= Compiler Param /Fd
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
I also encountered this problem when I tried to present a UIViewController
in viewDidLoad
. James Bedford's answer worked, but my app showed the background first for 1 or 2 seconds.
After some research, I've found a way to solve this using the addChildViewController
.
- (void)viewDidLoad
{
...
[self.view addSubview: navigationViewController.view];
[self addChildViewController: navigationViewController];
...
}
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Another alternative is pushd
, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd
:
C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_
var ws = new WebSocket("ws://" + window.location.host + ":6666");
ws.onopen = function() { ws.send( .. etc
Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by @npocmaka:
powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)
You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Method for further reference):
0x10 Stop
0x20 Question Mark
0x30 Exclamation Mark
0x40 Information Mark
Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.
I changed the code to:
# read data
dat<-read.dta("file.dta")
# vars to delete
var.in<-c("iden", "name", "x_serv", "m_serv")
# what I'm keeping
var.out<-setdiff(names(dat),var.in)
# keep only the ones I want
dat <- dat[var.out]
Anyway, juba's answer is the best solution to my problem!
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}