On Oracle 12.2
, you can use built-in constant, ORA_MAX_NAME_LEN
,
set to 128 bytes (as per 12.2)
Prior to Oracle 12.1
max size was 30 bytes.
255 chars, though the complete path should not be longer than that as well. There is a nice table over at Wikipedia about this: http://en.wikipedia.org/wiki/Filename.
list2 = ['%sbar' % (x,) for x in list]
And don't use list
as a name; it shadows the built-in type.
This happens to me whenever I do autoload stuff in autoload.php like the 'database'
To resolve this, If you're using Windows OS
Open your php.ini.
Search and uncomment this line - extension=php_mysql.dll
(Please also check If the PHP directive points to where your extensions is located.
Mine is extension_dir = "C:\php-5.4.8-Win32-VC9-x86\ext"
)
Restart Apache and refresh your page
If you are converting DataFrame to JSON, NaN
will give error so best solution is in this use case is to replace NaN
with None
.
Here is how:
df1 = df.where((pd.notnull(df)), None)
export const universalBtoa = str => {
try {
return btoa(str);
} catch (err) {
return Buffer.from(str).toString('base64');
}
};
export const universalAtob = b64Encoded => {
try {
return atob(b64Encoded);
} catch (err) {
return Buffer.from(b64Encoded, 'base64').toString();
}
};
I ran into this on a friend's HTML code and in his case, he was missing quotes.
For example:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" style="width:90;font-size:10>
<input type="submit" value="submit"/>
</form>
In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.
Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.
Also, if you have any tags like center, move them out of the form.
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<center> <-- bad
As strange it may seems, it can have an impact.
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
and
is the same as &&
but with lower precedence. They both use short-circuit evaluation.
WARNING: and
even has lower precedence than =
so you'll usually want to avoid and
. An example when and
should be used can be found in the Rails Guide under "Avoiding Double Render Errors".
Below are the steps that worked for me
from google.colab import drive drive.mount('/content/drive')
import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)
%cd drive/MyDrive/ColabNotebooks %pwd
import my_module
If you get the following error 'Name Null is not defined' then do the following
5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)
5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive
5.3 import my_module will work now
input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid
int 21h
nv:
mov ah, 09h
mov dx, offset invalid
int 21h
mov ah, 04ch
int 21
end
On the latest macOS version you can use this command:
lsof -nP -i4TCP:$PORT | grep LISTEN
If you find it hard to remember then maybe you should create a bash
function and export it with a friendlier name like so
vi ~/.bash_profile
and then add the following lines to that file and save it.
function listening_on() {
lsof -nP -i4TCP:"$1" | grep LISTEN
}
Now you can type listening_on 80
in your Terminal and see which process is listening on port 80
.
git clone
means you are making a copy of the repository in your system.
git fork
means you are copying the repository to your Github account.
git pull
means you are fetching the last modified repository.
git push
means you are returning the repository after modifying it.
In layman's term:
git clone
is downloading and git pull
is refreshing.
In ASP.NET MVC (starting in version 3), you can add the AllowHtml
attribute to a property on your model.
It allows a request to include HTML markup during model binding by skipping request validation for the property.
[AllowHtml]
public string Description { get; set; }
The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.
If the only thing you've installed in /usr/local
is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git
to clear it out. But /usr/local/
is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh
is a better bet. It is careful to only remove homebrew's files and leave the rest alone.
\begin{tikzpicture}
\tikzstyle{every node}=[font=\fontsize{30}{30}\selectfont]
\end{tikzpicture}
SWIFT 4:
1. Create an @IBAction with segue inside controller you want to unwind to:
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
2. In the storyboard, from the controller you want to segue (unwind) from ctrl+drag from the controller sign to exit sign and choose method you created earlier:
3. Now you can notice that in document outline you have new line with title "Unwind segue....". Now you should click on this line and open attribute inspector to set identifier (in my case unwindSegueIdentifier).
4. You're almost done! Now you need to open view controller you wish to unwind from and create some method that will perform segue. For example you can add button, connect it with code with @IBAction, after that inside this IBAction add perfromSegue(withIdentifier:sender:) method:
@IBAction func unwindToSomeVCWithSegue(_ sender: UIButton) {
performSegue(withIdentifier: "unwindSegueIdentifier", sender: nil)
}
So that is all you have to do!
There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.
$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.
Read More .. jquery-post-vs-get-vs-ajax
So,
$HOME
is what I need to modify.However I have been unable to find where this mythical
$HOME
variable is set so I assumed it was a Linux system version of PATH or something.
Git 2.23 (Q3 2019) is quite explicit on how HOME
is set.
See commit e12a955 (04 Jul 2019) by Karsten Blees (kblees
).
(Merged by Junio C Hamano -- gitster
-- in commit fc613d2, 19 Jul 2019)
mingw: initialize HOME on startup
HOME
initialization was historically duplicated in many different places, including/etc/profile
, launch scripts such asgit-bash.vbs
andgitk.cmd
, and (although slightly broken) in thegit-wrapper
.Even unrelated projects such as
GitExtensions
andTortoiseGit
need to implement the same logic to be able to call git directly.Initialize
HOME
in Git's own startup code so that we can eventually retire all the duplicate initialization code.
Now, mingw.c includes the following code:
/* calculate HOME if not set */ if (!getenv("HOME")) { /* * try $HOMEDRIVE$HOMEPATH - the home share may be a network * location, thus also check if the path exists (i.e. is not * disconnected) */ if ((tmp = getenv("HOMEDRIVE"))) { struct strbuf buf = STRBUF_INIT; strbuf_addstr(&buf, tmp); if ((tmp = getenv("HOMEPATH"))) { strbuf_addstr(&buf, tmp); if (is_directory(buf.buf)) setenv("HOME", buf.buf, 1); else tmp = NULL; /* use $USERPROFILE */ } strbuf_release(&buf); } /* use $USERPROFILE if the home share is not available */ if (!tmp && (tmp = getenv("USERPROFILE"))) setenv("HOME", tmp, 1); }
It seems to work using
html, body { overflow: hidden; }
inside the IFrame
edit: Of course this is only working, if you have access to the Iframe's content (which I have in my case)
Android uses some files called resources where values are stored for the XML files.
Now when you use @id/ for an XML object, It is trying to refer to an id which is already registered in the values files. On the other hand, when you use @+id/ it registers a new id in the values files as implied by the '+' symbol.
Hope this helps :).
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
The word "canonical" is just a synonym for "standard" or "usual". It doesn`t have any Java-specific meaning.
This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):
var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
XmlReaderSettings _configsettings = new XmlReaderSettings();
_configsettings.IgnoreComments = true;
XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
XmlDocument doc_config = new XmlDocument();
doc_config.Load(_configreader);
_configreader.Close();
foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
{
if (RootName.LocalName == "appSettings")
{
if (RootName.HasChildNodes)
{
foreach (XmlNode _child in RootName.ChildNodes)
{
if (_child.Attributes["key"].Value == "HostName")
{
if (_child.Attributes["value"].Value == "false")
_child.Attributes["value"].Value = "true";
}
}
}
}
}
doc_config.Save(ConfigFilePath);
For EF 6
using System.Data.Entity;
query.Include(x => x.Collection.Select(y => y.Property))
Make sure to add using System.Data.Entity;
to get the version of Include
that takes in a lambda.
For EF Core
Use the new method ThenInclude
query.Include(x => x.Collection)
.ThenInclude(x => x.Property);
I used Ofer's answer for a while and found it great in most cases. Unfortunately, due to inconsistencies between pandas's to_csv and prettytable's from_csv, I had to use prettytable in a different way.
One failure case is a dataframe containing commas:
pd.DataFrame({'A': [1, 2], 'B': ['a,', 'b']})
Prettytable raises an error of the form:
Error: Could not determine delimiter
The following function handles this case:
def format_for_print(df):
table = PrettyTable([''] + list(df.columns))
for row in df.itertuples():
table.add_row(row)
return str(table)
If you don't care about the index, use:
def format_for_print2(df):
table = PrettyTable(list(df.columns))
for row in df.itertuples():
table.add_row(row[1:])
return str(table)
If you have a look at MySQL Improved Extension Overview, it should tell you everything you need to know about the differences between the two.
The main useful features are:
You are not using the function in_array (http://php.net/manual/en/function.in-array.php) correctly:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
The $needle has to have a value in the array, so you first need to extract the url from the string (with a regular expression for example). Something like this:
$url = extrctUrl('my domain name is website3.com');
//$url will be 'website3.com'
in_array($url, $owned_urls)
Ctrl + Alt + L is format file (includes the two below)
Ctrl + Alt + O is optimize imports
Ctrl + Alt + I will fix indentation on a particular line
I usually run Ctrl + Alt + L a few times before committing my work. I'd rather it do the cleanup/reformatting at my command instead of automatically.
That is pretty straight forward. If you need from within the same class:
Class clazz = this.getClass();
ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
try {
Class typeClass = Class.forName( parameterizedType.getActualTypeArguments()[0].getTypeName() );
// You have the instance of type 'T' in typeClass variable
System.out.println( "Class instance name: "+ typeClass.getName() );
} catch (ClassNotFoundException e) {
System.out.println( "ClassNotFound!! Something wrong! "+ e.getMessage() );
}
My guess is a wrong version of project A jar in your local maven repository. It seems that the dependency is resolved otherwise I think maven does not start compiling but usually these compiling error means that you have a version mix up. try to make a maven clean install
of your project A and see if it changes something for the project B...
Also a little more information on your setting could be useful:
For Jquery UI buttons this works :
$("#buttonId").button( "option", "disabled", true | false );
Just as a build on @markE's answer—if you want to create a local server. You won't have this error on a local server.
If you have PHP installed on your computer:
php -S localhost:3000
? Notice the capital 'S'If you have Node.js installed on your computer:
npm init -y
npm install live-server -g
or sudo npm install live-server -g
on a maclive-server
and it should automatically open up a new tab in the browser with your website open.Note: remember to have an index.html file in the root of your folder or else you might have some issues.
For inserting a separator:
df$x <- paste(df$n, "-", df$s)
Inspired by PointZeroTwo's answer, here's a sample using NUnit and FakeItEasy.
SystemUnderTest
in this example is the class that you want to test - no sample content given for it but I assume you have that already!
[TestFixture]
public class HttpClientTests
{
private ISystemUnderTest _systemUnderTest;
private HttpMessageHandler _mockMessageHandler;
[SetUp]
public void Setup()
{
_mockMessageHandler = A.Fake<HttpMessageHandler>();
var httpClient = new HttpClient(_mockMessageHandler);
_systemUnderTest = new SystemUnderTest(httpClient);
}
[Test]
public void HttpError()
{
// Arrange
A.CallTo(_mockMessageHandler)
.Where(x => x.Method.Name == "SendAsync")
.WithReturnType<Task<HttpResponseMessage>>()
.Returns(Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("abcd")
}));
// Act
var result = _systemUnderTest.DoSomething();
// Assert
// Assert.AreEqual(...);
}
}
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution.
Note: Using -Xss sets the stack size of every thread and is a very bad idea.
Another approach is byte code manipulation to change the code as follows;
public static long fact(int n) {
return n < 2 ? n : n > 127 ? 0 : n * fact(n - 1);
}
given every answer for n > 127 is 0. This avoid changing the source code.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();
The public
keyword is used only when declaring a class method.
Since you're declaring a simple function and not a class you need to remove public
from your code.
You can do it with gridview's datarow bound event. try the following sample of code:
protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}
For more details about the row databound event study Thsi....
Try numpy.clip
:
>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
You can clip only the bottom half with clip(0)
.
>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])
You can clip only the top half with clip(max=n)
. (This is much better than my previous suggestion, which involved passing NaN
to the first parameter and using out
to coerce the type.):
>>> a.clip(max=2)
array([ 1, 2, 2, -4, 2])
Another interesting approach is to use where
:
>>> numpy.where(a <= 2, a, 2)
array([ 1, 2, 2, -4, 2])
Finally, consider aix's answer. I prefer clip
for simple operations because it's self-documenting, but his answer is preferable for more complex operations.
Simply, change
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>
to
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>
ie, add:
data-role="none"
Don't do this.
Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages
or /var/opt/udi
or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.
Bottom line: Do not mingle code and data.
Data is precious. Code comes and goes.
Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)
Make it a required argument value and do this.
import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )
Do not "assume" a directory based on the location of your software. It will not work out well in the long run.
if (!$(this).hasClass("test")) {
Something like this should work:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
You can actualy fake the transparency of option
DOMElements with the following CSS:
option {
/* Whatever color you want */
background-color: #82caff;
}
The option
tag does not support rgba
colors yet.
In DBeaver (or other editors) the script file you're working can prompt to save as UTF8 and that will change the char:
–
into
–
or
–
If you want to count all files in the directory - including files in subdirectories, the most pythonic way is:
import os
file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)
We use sum that is faster than explicitly adding the file counts (timings pending)
This line is the problem:
int estimatedPopulation (int currentPopulation,
float growthRate (birthRate, deathRate))
Make it:
int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)
instead and invoke the function with three arguments like
estimatePopulation( currentPopulation, birthRate, deathRate );
OR declare it with two arguments like:
int estimatedPopulation (int currentPopulation, float growthrt ) { ... }
and call it as
estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));
Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate
variable in the main()
hides the function with the same name. So within main()
you can only access grouthRate
as float
. On the other hand, outside of the main()
you can only access that name as a function, since that automatic variable is only visible within the scope of main()
.
Just hope I didn't confuse you further :)
Opt 1: using toLowerCase()
var x = 'ABC';
x = x.toLowerCase();
Opt 2: Using your own function
function convertToLowerCase(str) {
var result = '';
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
if (code > 64 && code < 91) {
result += String.fromCharCode(code + 32);
} else {
result += str.charAt(i);
}
}
return result;
}
Call it as:
x = convertToLowerCase(x);
Maven uses batch files to do its business. With any batch script, you must call another script using the call
command so it knows to return back to your script after the called script completes. Try prepending call
to all commands.
Another thing you could try is using the start
command which should work similarly.
I think your problem may lie in how your datepicker is setup. Why don't you disconnect the input... do not use altField. Instead explicitly set the values when the onSelect fires. This will give you control of each interaction; the user text field, and the datepicker.
Note: Sometimes you have to call the routine on .change() and not .onSelect() because onSelect can be called on different interactions that you are not expecting.
Pseudo Code:
$('#date').datepicker({
//altField: , //do not use
onSelect: function(date){
$('#date').val(date); //Set my textbox value
//Do your search routine
},
}).change(function(){
//Or do it here...
});
$('#date').change(function(){
var thisDate = $(this).val();
if(isValidDate(thisDate)){
$('#date').datepicker('setDate', thisDate); //Set my datepicker value
//Do your search routine
});
});
RFC 2396 section 4.1:
When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.
(emphasis added)
As of Visual Studio Code Release 1.22 this comes free without the need of an extension.
Shift+Alt+O will take care of you.
If you are on a remote machine, you may also want to add the -f option to force the reboot. Otherwise your session may close and a stubborn app can hang the system.
I use this whenever I want to force an immediate reboot:
shutdown -t 0 -r -f
For a more friendly "give them some time" option, you can use this:
shutdown -t 30 -r
As you can see in the comments, the -f is implied by the timeout.
Brutus 2006 is a utility that provides a GUI for these options.
I think it will be sometime before we get to see access to the NFC as the pure security side of it like for example being able to walk past somebody brush past them and & get your phone to the zap the card details or simply Wave your phone over someone's wallet which They left on the desk.
I think the first step is for Apple to talk to banks and find more ways of securing cards and NFC before This will be allowed
Without any additional packages:
true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
aList = getROC_AUC(probs, true_Y)
stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)
plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")
The correct solution that i get is
<html>
<head>
<script type="text/javascript" language="JavaScript">
function clickedButton()
{
window.location = 'new url'
}
</script>
</head>
<form name="login_form" method="post">
..................
<input type="button" value="Login" onClick="clickedButton()"/>
</form>
</html>
Here the new url is given inside the single quote.
The request body is available as byte stream by HttpServletRequest#getInputStream()
:
InputStream body = request.getInputStream();
// ...
Or as character stream by HttpServletRequest#getReader()
:
Reader body = request.getReader();
// ...
Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter()
and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.
why you need a for-loop for this? the solution is very obvious:
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
that's it. no for-loop needed.
Put the value in the plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
The error was use:
<source>${java.version}</source>
<target>${java.version}</target>
Java 8 is now very common nowadays.
Arrays.sort(myArr,(double[] a,double[] b)->{
//here multiple lines of code can be placed
return a[0]-b[0];
});
Please refer to this SO Post
example of a regular expression in jquery for phone numbers
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
are supported
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
I tried one after other and found a best answer at the time:
https://stackoverflow.com/a/3187524/985399
I skip old browsers so I made the code shorter to work on modern browsers (IE9+)
document.addEventListener("mouseout", function(e) {_x000D_
let t = e.relatedTarget || e.toElement;_x000D_
if (!t || t.nodeName == "HTML") {_x000D_
console.log("left window");_x000D_
}_x000D_
});_x000D_
_x000D_
document.write("<br><br>PROBLEM<br><br><div>Mouseout trigg on HTML elements</div>")
_x000D_
Here you see the browser support
That was pretty short I thought
But a problem still remained because "mouseout" trigg on all elements in the document.
To prevent it from happen, use mouseleave (IE5.5+). See the good explanation in the link.
The following code works without triggering on elements inside the element to be inside or outside of. Try also drag-release outside the document.
var x = 0_x000D_
_x000D_
document.addEventListener("mouseleave", function(e) { console.log(x++) _x000D_
})_x000D_
_x000D_
document.write("<br><br>SOLUTION<br><br><div>Mouseleave do not trigg on HTML elements</div>")
_x000D_
You can set the event on any HTML element. Do not have the event on document.body
though, because the windows scrollbar may shrink the body and fire when mouse pointer is abowe the scroll bar when you want to scroll but not want to trigg a mouseLeave event over it. Set it on document
instead, as in the example.
This is quite likely the simplest way to achieve what you are looking for.
In order to use this map
function in this instance, we will have to pass a currentValue
(always-required) parameter, as well an index
(optional) parameter.
In the below example, station
is our currentValue
, and x
is our index
.
station
represents the current value of the object within the array as it is iterated over.
x
automatically increments; increasing by one each time a new object is mapped.
render () {
return (
<div>
{stations.map((station, x) => (
<div key={x}> {station} </div>
))}
</div>
);
}
What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.
If #box
is empty, nothing, but if it's not these do very different things. The former will add a div
as the last child node of #box
. The latter completely replaces the contents of #box
with a single empty div
, text and all.
You can change the port while you open your XAMP control panel, follow the steps:
httpd.conf
, a text file will openlisten:80
,listen:80
replace with listen:8080
andOnce done that, you will be able to start your local server.
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
This is whole story how date problem was and how Big DBMSs handled these problems.
During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.
When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.
Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?
This is how the Big DBMSs handle these questions:
- Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
- Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
- Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)
def search(itemID,list):
return[i for i in list if i.itemID==itemID]
Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.
public enum Gender {
MALE,
FEMALE
}
If you want them to be more complex, you can add values to them like this.
public enum Gender {
MALE("Male", 0),
FEMALE("Female", 1);
private String stringValue;
private int intValue;
private Gender(String toString, int value) {
stringValue = toString;
intValue = value;
}
@Override
public String toString() {
return stringValue;
}
}
Then to use the enum, you would do something like this:
Gender me = Gender.MALE
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
I realize this is an older post, but I came it across it today while working on a script that would take dates and times from a log file and compute the delta. The script below is certainly overkill, and I highly recommend checking my logic and maths.
#!/bin/bash
dTime=""
tmp=""
#firstEntry="$(head -n 1 "$LOG" | sed 's/.*] \([0-9: -]\+\).*/\1/')"
firstEntry="2013-01-16 01:56:37"
#lastEntry="$(tac "$LOG" | head -n 1 | sed 's/.*] \([0-9: -]\+\).*/\1/')"
lastEntry="2014-09-17 18:24:02"
# I like to make the variables easier to parse
firstEntry="${firstEntry//-/ }"
lastEntry="${lastEntry//-/ }"
firstEntry="${firstEntry//:/ }"
lastEntry="${lastEntry//:/ }"
# remove the following lines in production
echo "$lastEntry"
echo "$firstEntry"
# compute days in last entry
for i in `seq 1 $(echo $lastEntry|awk '{print $2}')`; do {
case "$i" in
1|3|5|7|8|10|12 )
dTime=$(($dTime+31))
;;
4|6|9|11 )
dTime=$(($dTime+30))
;;
2 )
dTime=$(($dTime+28))
;;
esac
} done
# do leap year calculations for all years between first and last entry
for i in `seq $(echo $firstEntry|awk '{print $1}') $(echo $lastEntry|awk '{print $1}')`; do {
if [ $(($i%4)) -eq 0 ] && [ $(($i%100)) -eq 0 ] && [ $(($i%400)) -eq 0 ]; then {
if [ "$i" = "$(echo $firstEntry|awk '{print $1}')" ] && [ $(echo $firstEntry|awk '{print $2}') -lt 2 ]; then {
dTime=$(($dTime+1))
} elif [ $(echo $firstEntry|awk '{print $2}') -eq 2 ] && [ $(echo $firstEntry|awk '{print $3}') -lt 29 ]; then {
dTime=$(($dTime+1))
} fi
} elif [ $(($i%4)) -eq 0 ] && [ $(($i%100)) -ne 0 ]; then {
if [ "$i" = "$(echo $lastEntry|awk '{print $1}')" ] && [ $(echo $lastEntry|awk '{print $2}') -gt 2 ]; then {
dTime=$(($dTime+1))
} elif [ $(echo $lastEntry|awk '{print $2}') -eq 2 ] && [ $(echo $lastEntry|awk '{print $3}') -ne 29 ]; then {
dTime=$(($dTime+1))
} fi
} fi
} done
# substract days in first entry
for i in `seq 1 $(echo $firstEntry|awk '{print $2}')`; do {
case "$i" in
1|3|5|7|8|10|12 )
dTime=$(($dTime-31))
;;
4|6|9|11 )
dTime=$(($dTime-30))
;;
2 )
dTime=$(($dTime-28))
;;
esac
} done
dTime=$(($dTime+$(echo $lastEntry|awk '{print $3}')-$(echo $firstEntry|awk '{print $3}')))
# The above gives number of days for sample. Now we need hours, minutes, and seconds
# As a bit of hackery I just put the stuff in the best order for use in a for loop
dTime="$(($(echo $lastEntry|awk '{print $6}')-$(echo $firstEntry|awk '{print $6}'))) $(($(echo $lastEntry|awk '{print $5}')-$(echo $firstEntry|awk '{print $5}'))) $(($(echo $lastEntry|awk '{print $4}')-$(echo $firstEntry|awk '{print $4}'))) $dTime"
tmp=1
for i in $dTime; do {
if [ $i -lt 0 ]; then {
case "$tmp" in
1 )
tmp="$(($(echo $dTime|awk '{print $1}')+60)) $(($(echo $dTime|awk '{print $2}')-1))"
dTime="$tmp $(echo $dTime|awk '{print $3" "$4}')"
tmp=1
;;
2 )
tmp="$(($(echo $dTime|awk '{print $2}')+60)) $(($(echo $dTime|awk '{print $3}')-1))"
dTime="$(echo $dTime|awk '{print $1}') $tmp $(echo $dTime|awk '{print $4}')"
tmp=2
;;
3 )
tmp="$(($(echo $dTime|awk '{print $3}')+24)) $(($(echo $dTime|awk '{print $4}')-1))"
dTime="$(echo $dTime|awk '{print $1" "$2}') $tmp"
tmp=3
;;
esac
} fi
tmp=$(($tmp+1))
} done
echo "The sample time is $(echo $dTime|awk '{print $4}') days, $(echo $dTime|awk '{print $3}') hours, $(echo $dTime|awk '{print $2}') minutes, and $(echo $dTime|awk '{print $1}') seconds."
You will get output as follows.
2012 10 16 01 56 37
2014 09 17 18 24 02
The sample time is 700 days, 16 hours, 27 minutes, and 25 seconds.
I modified the script a bit to make it standalone (ie. just set variable values), but maybe the general idea comes across as well. You'd might want some additional error checking for negative values.
I just experienced this with the line:
$('<div id="editor" />').dialogelfinder({
I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.
As soon as I commented out the second load, the error went away.
Below is my working code.
List<sampleObject> list = new ArrayList<>();
File file = new ClassPathResource("json/test.json").getFile();
ObjectMapper objectMapper = new ObjectMapper();
sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));
Hope it helps one!
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2);
into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
I encountered the same problem and finally found out that the <tx:annotaion-driven />
was not defined within the [dispatcher]-servlet.xml
where component-scan element enabled @service
annotated class.
Simply put <tx:annotaion-driven />
with component-scan element together, the problem disappeared.
Faced this issue on Android studio 4.1, windows 10.
The solution that worked for me:
1 - Go to gradle.properties file which is in the root directory of the project.
2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.
3 - Now close any open project from File -> close project.
4 - On the Welcome window, Go to Configure > Settings.
5 - Go to Build, Execution, Deployment > Compiler
6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.
Now close the android studio and restart it. The issue will be gone.
x = x + 1 print(x) a = x + 5 print(a)
Here is my utility class, you may use:
package <removed>;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
* Author @espresso stackoverflow.
* Sample use:
* Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
Model.Person res = personSvc.update(reqObj);
final String resJson = ProtoUtil.toJson(res);
**/
public class ProtoUtil {
public static <T extends Message> String toJson(T obj){
try{
return JsonFormat.printer().print(obj);
}catch(Exception e){
throw new RuntimeException("Error converting Proto to json", e);
}
}
public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
try{
Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
JsonFormat.parser().ignoringUnknownFields().merge(protoJsonStr,builder);
T out = (T) builder.build();
return out;
}catch(Exception e){
throw new RuntimeException(("Error converting Json to proto", e);
}
}
}
Here's a more concise approach...
df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)
The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.
Result:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
NOTE: sort
is deprecated, use sort_values
instead
Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/
Usage:
$('selector').fixedHeaderTable({ fixedColumn: 1 });
Set the fixedColumn
option if you want any number of columns to be also fixed for horizontal scrolling.
EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.
EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)
If it is hosted in IIS, there is no need to specify a base address, it will be the address of the virtual directory.
I found a tricky solution... which works only in a RelativeLayout. We only need to put a View above a ListView and set clickable 'true' on View and false for the ListView
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview
android:clickable="false" />
<View
android:layout_width="match_parent"
android:background="@drawable/gradient_white"
android:layout_height="match_parent"
android:clickable="true"
android:layout_centerHorizontal="true"
android:layout_alignTop="@+id/listview" />
Add the following namespace,
using System.IO;
and use the Directory
class to reach on the specific folder:
string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
File.Delete(fileName);
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Same as Michael's except this one works :P
I have combined several sources to produce the code below, which I am currently using. I have also removed the Windows.Forms references so I can use it from console and WPF applications without additional references.
using System;
using System.Runtime.InteropServices;
public class MouseOperations
{
[Flags]
public enum MouseEventFlags
{
LeftDown = 0x00000002,
LeftUp = 0x00000004,
MiddleDown = 0x00000020,
MiddleUp = 0x00000040,
Move = 0x00000001,
Absolute = 0x00008000,
RightDown = 0x00000008,
RightUp = 0x00000010
}
[DllImport("user32.dll", EntryPoint = "SetCursorPos")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(out MousePoint lpMousePoint);
[DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
public static void SetCursorPosition(int x, int y)
{
SetCursorPos(x, y);
}
public static void SetCursorPosition(MousePoint point)
{
SetCursorPos(point.X, point.Y);
}
public static MousePoint GetCursorPosition()
{
MousePoint currentMousePoint;
var gotPoint = GetCursorPos(out currentMousePoint);
if (!gotPoint) { currentMousePoint = new MousePoint(0, 0); }
return currentMousePoint;
}
public static void MouseEvent(MouseEventFlags value)
{
MousePoint position = GetCursorPosition();
mouse_event
((int)value,
position.X,
position.Y,
0,
0)
;
}
[StructLayout(LayoutKind.Sequential)]
public struct MousePoint
{
public int X;
public int Y;
public MousePoint(int x, int y)
{
X = x;
Y = y;
}
}
}
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
SELECT Email, COUNT(*)
FROM user_log
WHILE Email IS NOT NULL
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=MyISAM' at line 36
Which correction below:
CREATE TABLE users_online (
ip varchar(15) NOT NULL default '',
time int(11) default NULL,
PRIMARY KEY (ip),
UNIQUE KEY id (ip),
KEY id_2 (ip)
TYPE=MyISAM;
)
#
# Data untuk tabel `users_online`
#
INSERT INTO users_online VALUES ('127.0.0.1', 1158666872);
cd /home/<user_name>/
sudo vi .bash_profile
add these lines at the end
LD_LIBRARY_PATH=/usr/local/lib:<any other paths you want>
export LD_LIBRARY_PATH
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
Your code doesn't seem so ugly to me...
however, an alternative (not much better) could be e.g. :
df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100
------------------
Smoker Freq Perc
1 No 19 47.5
2 Yes 21 52.5
Your problem is in your use of the_field()
, which is for Advanced Custom Fields, a wordpress plugin.
If you want to use a field in a variable you have to use this: $web = get_field('website');
.
For me, plain old .contents()
appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.
For example, this wrapped all the text content of the TDs in my table with pre
tags and had no problems.
jQuery("#resultTable td").content().wrap("<pre/>")
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
In-order to make SQL server send email notification you need to create mail profile from Management, database mail.
1) User Right click to get the mail profile menu and choose configure database mail
2)choose the first open (set up a database mail by following the following tasks) and press next Note: if the SMTP is not configured please refer the the URL below
http://www.symantec.com/business/support/index?page=content&id=TECH86263
3) in the second screen fill the the profile name and add SMTP account, then press next
4) choose the type of mail account ( public or private ) then press next
5) change the parameters that related to the sending mail options, and press next 6) press finish
Now to make SQL server send an email if action X happened you can do that via trigger or job ( This is the common ways not the only ones).
1) you can create Job from SQL server agent, then right click on operators and check mails (fill the your email for example) and press OK after that right click Jobs and choose new job and fill the required info as well as the from steps, name, ...etc and from notification tab select the profile you made.
2) from triggers please refer to the example below.
AS
declare @results varchar(max)
declare @subjectText varchar(max)
declare @databaseName VARCHAR(255)
SET @subjectText = 'your subject'
SET @results = 'your results'
-- write the Trigger JOB
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQLAlerts',
@recipients = '[email protected]',
@body = @results,
@subject = @subjectText,
@exclude_query_output = 1 --Suppress 'Mail Queued' message
GO
I had the same issue until i close teamviewer
running on my pc. Then it worked fine!
The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php
Since xampp is Offline, it sets up a local server whose address is like this
http://localhost/
Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\
folder.
The browser locates the server in localhost and will search through the above folder for any resources available in there.
So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).
Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache
Or, building on Rusian L.'s suggestion, if the item you're searching for can be in the list more than once::
[Extension()]
public void ReplaceAll<T>(List<T> input, T search, T replace)
{
int i = 0;
do {
i = input.FindIndex(i, s => EqualityComparer<T>.Default.Equals(s, search));
if (i > -1) {
FileSystem.input(i) = replace;
continue;
}
break;
} while (true);
}
No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled
When your form is maximized, set its minimum size = max size, so user cannot resize it.
this.WindowState = FormWindowState.Maximized;
this.MinimumSize = this.Size;
this.MaximumSize = this.Size;
Sprint as defined in pure Scrum has the duration 30 calendar days. However Iteration length could be anything as defined by the team.
We can simply create a template reference variable [2] and link that to the else condition inside an *ngIf directive
The possible Syntaxes [1] are:
<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>
<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>
<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>
<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>
DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html
Sources:
This is an old post but regardless, you can also get boldface and italic characters by leveraging utf-32. There are even greek and math symbols that can be used as well as the roman alphabet.
For people live in 2020, and want a clean answer...
delegate
: defines a function pointer.event
: defines
+=
, -=
), andnew
keyword anymore.Regarding the adjective protected:
// eventTest.SomeoneSay = null; // Compile Error.
// eventTest.SomeoneSay = new Say(SayHello); // Compile Error.
Also notice this section from Microsoft: https://docs.microsoft.com/en-us/dotnet/standard/events/#raising-multiple-events
delegate
:public class DelegateTest
{
public delegate void Say(); // Define a pointer type "void <- ()" named "Say".
private Say say;
public DelegateTest() {
say = new Say(SayHello); // Setup the field, Say say, first.
say += new Say(SayGoodBye);
say.Invoke();
}
public void SayHello() { /* display "Hello World!" to your GUI. */ }
public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}
event
:public class EventTest
{
public delegate void Say();
public event Say SomeoneSay; // Use the type "Say" to define event, an
// auto-setup-everything-good field for you.
public EventTest() {
SomeoneSay += SayHello;
SomeoneSay += SayGoodBye;
SomeoneSay();
}
public void SayHello() { /* display "Hello World!" to your GUI. */ }
public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}
Event vs. Delegate - Explaining the important differences between the Event and Delegate patterns in C# and why they're useful.: https://dzone.com/articles/event-vs-delegate
The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode
or
[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")
UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:
Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"
I had the same problem with Java 7 u51. Only after I reset Internet Explorer it work again, Java was enabled in browser etc.
Internet options -> Advanced -> Reset...
For AWS users.
I had to use the following steps to get there.
1) Ensure that pip and django are installed at the sudo level
2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0
3) Add Public IP and DNS to ALLOWED_HOSTS
4) Launch development server with sudo on port 80
Site now available at either of the following (no need for :80 as that is default for http):
flex: 1
means the following:
flex-grow : 1; ? The div will grow in same proportion as the window-size
flex-shrink : 1; ? The div will shrink in same proportion as the window-size
flex-basis : 0; ? The div does not have a starting value as such and will
take up screen as per the screen size available for
e.g:- if 3 divs are in the wrapper then each div will take 33%.
If you do df.count > 0
. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.
The best way to do this is to perform df.take(1)
and check if its null. This will return java.util.NoSuchElementException
so better to put a try around df.take(1)
.
The dataframe return an error when take(1)
is done instead of an empty row. I have highlighted the specific code lines where it throws the error.
Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:
using Map = std::map<K,V>;
Map map;
// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);
A couple of other minor style changes:
Map::const_iterator
) when possible/convenient, over using auto
.using
for template types, to make ancillary types (Map::const_iterator
) easier to read/maintain.//More Efficiently
public class Multiples {
public static void main(String[]args) {
int j = 5;
System.out.println(j % 4 == 0);
}
}
You need to use a back_inserter
:
std::copy(input.begin(), input.end(), std::back_inserter(output));
std::copy
doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy
, you must make sure it points to a range that is at least large enough to hold the input range.
std::back_inserter
creates an output iterator that calls push_back
on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector
to hold the range being copied:
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Or, you could use the std::vector
range constructor:
std::vector<double> output(input.begin(), input.end());
I agree with the answer from zacherates.
But what you can do is to call intern()
on your non-literal strings.
From zacherates example:
// ... but they are not the same object
new String("test") == "test" ==> false
If you intern the non-literal String equality is true
:
new String("test").intern() == "test" ==> true
I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.
it's easy
every folder of those you downloaded has a different kind of roboto font, means they are different fonts
example: "roboto_regular_macroman"
to use any of them:
1- extract the folder of the font you want to use
2- upload it near the css file
3- now include it in the css file
example for including the font which called "roboto_regular_macroman":
@font-face {
font-family: 'Roboto';
src: url('roboto_regular_macroman/Roboto-Regular-webfont.eot');
src: url('roboto_regular_macroman/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
url('roboto_regular_macroman/Roboto-Regular-webfont.woff') format('woff'),
url('roboto_regular_macroman/Roboto-Regular-webfont.ttf') format('truetype'),
url('roboto_regular_macroman/Roboto-Regular-webfont.svg#RobotoRegular') format('svg');
font-weight: normal;
font-style: normal;
}
watch for the path of the files, here i uploaded the folder called "roboto_regular_macroman" in the same folder where the css is
then you can now simply use the font by typing font-family: 'Roboto';
useHistory
hook:If you have React >= 16.8
and functional components you can use the useHistory
hook from react-router.
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
withRouter
HOC:As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
browserHistory
You can achieve this functionality using react-router BrowserHistory
. Code below:
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
connected-react-router
If you have connected your component with redux, and have configured connected-react-router all you have to do is
this.props.history.push("/new/url");
ie, you don't need withRouter
HOC to inject history
to the component props.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
Use org.springframework.web.context.request.WebRequest
as a parameter in your controller method, it provides the method getParameterMap()
, the advantage is that you do not tight your application to the Servlet API, the WebRequest is a example of JavaEE pattern Context Object.
BuildToolsVersion & Dependencies must be same with Base API version.
buildToolsVersion '23.0.2' & compile
&
com.android.support:appcompat-v7:24.0.0-alpha1
can not match with base API level.
It should be
compile 'com.android.support:appcompat-v7:21.0.3'
Done
You can continue to use getApplicationContext()
, but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
, and the error will not show.
And don't forget to add permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
Use a O/R framework such as hibernate
Very simple...
1- just grab activity by getActivity()
in the fragment
2- then call finish();
So just getActivity().finish();
will finish the parent activity.
If you are using navigationController
then add the UINavigationControllerDelegate
protocol to class and add the delegate method as follows:
class ViewController:UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController,
animated: Bool) {
if viewController === self {
// do here what you want
}
}
}
This method is called whenever the navigation controller will slide to a new screen. If the back button was pressed, the new view controller is ViewController
itself.
Actually, even that didn't work for me. When I executed "select dbms_metadata.get_ddl('TABLESPACE','TABLESPACE_NAME') from dual;" I again got only the first three lines, but this time each line was padded out to 15,000 characters. I was able to work around this with:
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),80) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),160) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),240) from dual;
It sure seemed like there ought to be an easier way, but I couldn't seem to find it.
You can simply make the start_date required using
<input type="submit" value="Submit" required />
You don't even need the checkform() then.
Thanks
In MySQL you could try:
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
Of course this would be a massively inefficient query because it would do a full table scan.
Update: Here's a proof
create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL |
+-------+------------------+
| foo | fooblah |
| foo | somethingfooblah |
| foo | foo |
| bar | barblah |
| bar | somethingbarblah |
| bar | bar |
+-------+------------------+
6 rows in set (0.38 sec)
It's a chunk of memory allocated from the operating system by the memory manager in use by a process. Calls to malloc()
et alia then take memory from this heap instead of having to deal with the operating system directly.
uniq
should do fine if you're file is/can be sorted, if you can't sort the file for some reason you can use awk
:
awk '{a[$0]++}END{for(i in a)if(a[i]<2)print i}'
Using TortoiseSVN worked easily on Windows for me.
Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok
Using SVN 1.8.8 TortoiseSVN version 1.8.5
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
If you know the element type then: (eg: replace 'element' with 'div')
$("element[id$='txtTitle']")
If you don't know the element type:
$("[id$='txtTitle']")
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
$("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
Datepicker is not part of jQuery. You have to get jQuery UI to use the datepicker.
You can convert a numpy array to list and get its index .
for example:
tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1
this is just what you wanted.
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty()
call that returns true?
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
(See update at end of answer.)
You can get a NodeList
of all of the input
elements via getElementsByTagName
(DOM specification, MDC, MSDN), then simply loop through it:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
There I've used it on the document
, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:
var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
...but you've said you don't want to use the parent form
, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).
Update: getElementsByTagName
is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input
elements?
That's where the useful querySelectorAll
comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
You can also use it at the element level. For instance, if we have a div
element in our element
variable, we can find all of the span
s with the class foo
that are inside that div
like this:
var fooSpans = element.querySelectorAll("span.foo");
querySelectorAll
and its cousin querySelector
(which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.
In MySQL TRUE
and FALSE
are synonyms for TINYINT(1)
.
So therefore its basically the same thing, but MySQL is converting to 0/1 - so just use a TINYINT
if that's easier for you
P.S.
The performance is likely to be so minuscule (if at all), that if you need to ask on StackOverflow, then it won't affect your database :)
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
break;
leaves your loop.
continue;
skips any code for the remainder of that loop and goes on to the next loop, so long as the condition is still true.
import numpy
X = numpy.array(the_big_nested_list_you_had)
It's still not going to do what you want; you have more bugs, like trying to unpack a 3-dimensional shape into two target variables in test
.
Have <option value="">- Please select a name -</option>
as the first option and use JavaScript (and backend validation) to ensure the user has selected something other than an empty value.
You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800
from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()
I had to delete Tomcat's work directory as it had cached previously generated files. To do this:
This will cause the work directory to be newly generated.
And then I noticed that this simply isn't how you work there*, and I threw everything out, spent a few days reading manuals, set up my shell (bash), set up a GVIM environment, learned the GCC/binutils toolchain, make and gdb and lived happily ever after.
I'd mostly agree, but the problem is also one of perception: we forget how difficult it was to become productive in any chose IDE (or other environment). I find IDE's (Visual Studio, NetBeans, Eclipse) amazingly cumbersome in so many ways.
As an old-time UNIX guy, I always use Emacs. But that has a pretty steep and long learning curve, so I'm not sure I can recommend it to newcomers.
I'd second that; use Emacs as my primary editor on both Linux and on MSW (XP2,W2K). I would disagree that it has a steep learning curve, but would say that because of the huge number of features it has a long learning curve. You can be productive within a short time, but if you want you can learn new features of it for years to come.
However -- don't expect all the features of Emacs to be available on drop-down menus, there is just too much functionality to find it there.
As I metioned, I've used GNU Emacs on MSW for years. And it's always worked well with Visual Studio until I "upgraded" to 2008; now it sometimes delays many seconds before refreshing files from disk. The main reason for editing in the VS window is the "Intellisense" code completion feature.
Had the same problem and thanks to you mentioning that the real problem was related to CSS I found the issue:
Having position:relative
instead of position:absolute
in your .ui-dialog
CSS rule makes the dialog and width:'auto'
behave strangely.
.ui-dialog { position: absolute;}
Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).
BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.
EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141
Attention, this is only advised if your
runOnceOnStartup
method depends on a fully initialized spring context. For example: you wan to call a dao with transaction demarcation
You can also use a scheduled method with fixedDelay set very high
@Scheduled(fixedDelay = Long.MAX_VALUE)
public void runOnceOnStartup() {
dosomething();
}
This has the advantage that the whole application is wired up (Transactions, Dao, ...)
seen in Scheduling tasks to run once, using the Spring task namespace
One more idea for anyone else getting this...
I had some gzipped svg, but it had a php error in the output, which caused this error message. (Because there was text in the middle of gzip binary.) Fixing the php error solved it.
I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".
Simplified:
DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();
Not really a technical solution, but SQL Server 2017 flat file import is totally revamped, and imported my large-ish file with 5 clicks, handled encoding / field length issues without any input from me
The reliable only way to protect code is to run it on a server you control and provide your clients with a client which interfaces with that server.
You can use these string functions,
strstr — Find the first occurrence of a string
stristr — Case-insensitive strstr()
strrchr — Find the last occurrence of a character in a string
strpos — Find the position of the first occurrence of a substring in a string
strpbrk — Search a string for any of a set of characters
If that doesn't help then you should use preg
regular expression
preg_match — Perform a regular expression match
Try To Give Full path for reading image.
Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));
your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java
If the object of your class is created at end your code works fine for me and displays the image
// PracticeFrame pframe = new PracticeFrame();//comment this
new PracticeFrame().add(panel);
echo '<p class="paragrah"' . $i . '">'
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
You can make the query using convert to varbinary – it’s very easy. Example:
Select * from your_table where convert(varbinary, your_column) = convert(varbinary, 'aBcD')
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
The NotificationCompat.Builder is the most easy way to create Notifications
on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.
To create a simple Notification just do (see Android API Guide on Notifications):
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setContentIntent(pendingIntent); //Required on Gingerbread and below
You have to set at least smallIcon
, contentTitle
and contentText
. If you miss one the Notification will not show.
Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException
will be thrown.
To create an intent that does nothing, use:
final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You can add sound through the builder, i.e. a sound from the RingtoneManager:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
The Notification is added to the bar through the NotificationManager:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
You can also hide again advanced option after reconfigure:
-- show advanced options
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
-- enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
-- hide advanced options
EXEC sp_configure 'show advanced options', 0
GO
RECONFIGURE
GO
If you are using netbeans go to tools-> java Platform, change jdk_home which points to c:/programfiles/java/jdk1_7 to c:programFiles(x86)/java/jdk1_6_21
if not editable find netbeans.cnf and make change as stated abouve for jdk_home. restart neatbeans and how it works I had the same problem , but i worked .
Session.Abandon();
did not work for me either.
The way I had to write it to get it to work was like this. Might work for you too.
HttpContext.Current.Session.Abandon();
Simply do this:
def which_index(self):
return [
i for i in range(len(self.states))
if self.states[i] == True
]
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
Follow the following steps:
This SQL query will extract the data for you. It is easy and fast.
SELECT *
FROM table_name
WHERE extract( YEAR_MONTH from timestamp)="201010";
try instead this,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
I had this problem, and for me the answer was different than the other answers to this question.
I have an application with a lot of customers. I catch all error in the application_error in global.asax
and I send myself an email with the error detail. After I published a new version of my apps, I began receiving a lot of Validation of viewstate MAC failed error message.
After a day of searching I realized that I have a timer in my apps, that refresh an update panel every minute. So when I published a new version of my apps, and some customer have left her computer open on my website. I receive an error message every time that the timer refresh because the actual viewstate does not match with the new one. I received this message until all customers closed the website or refresh their browser to get the new version.
I'm sorry for my English, and I know that my case is very specific, but if it can help someone to save a day, I think that it is a good thing.
Try accessing the placeholder attribute of the input and change its value like the following:
$('#some_input_id').attr('placeholder','New Text Here');
Can also clear the placeholder if required like:
$('#some_input_id').attr('placeholder','');
I was having the same problem. To fix it I added the following headers:
Content-Type: application/json
I had to manually add the content type even though I also had the type of "json" in the raw post field parameters.
string str("(555) 555-5555");
char chars[] = "()-";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
// you need include <algorithm> to use general algorithms like std::remove()
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
// output: 555 5555555
cout << str << endl;
To use as function:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
//example of usage:
removeCharsFromString( str, "()-" );
I build this solution, reformulate
does not take care if variable names have white spaces.
add_backticks = function(x) {
paste0("`", x, "`")
}
x_lm_formula = function(x) {
paste(add_backticks(x), collapse = " + ")
}
build_lm_formula = function(x, y){
if (length(y)>1){
stop("y needs to be just one variable")
}
as.formula(
paste0("`",y,"`", " ~ ", x_lm_formula(x))
)
}
# Example
df <- data.frame(
y = c(1,4,6),
x1 = c(4,-1,3),
x2 = c(3,9,8),
x3 = c(4,-4,-2)
)
# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"
# Run Model
lm(formula = formula, data = df)
# output
Call:
lm(formula = formula, data = df)
Coefficients:
(Intercept) x1 x2 x3
-5.6316 0.7895 1.1579 NA
```
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
I have modified your code a little. Here's a working version (for me):
<select name="dd1" id="dd1">
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select>
<div style="color:red;" id="msg_id"></div>
<script>
$('#everything').submit(function(e){
var department = $("#msg_id");
var msg = "Please select Department";
if ($('#dd1').val() == "") {
department.append(msg);
e.preventDefault();
return false;
}
});
</script>
If you can afford working via the file data, you can do
find -mmin +14400 -delete
Evidently you can use Arrays.fill(), The way you have it done also works though.
I know this question is several years old, but what I think you're trying to do is get it so where a large element, like an image doesn't interfere with the height of a div?
I just ran into something similar, where I wanted an image to overflow a div, but I wanted it to be at the end of a string of text, so I didn't know where it would end up being.
A solution I figured out was to put the margin-bottom: -element's height, so if the image is 20px hight,
margin-bottom: -20px;
vertical-align: top;
for example.
That way it floated over the outside of the div, and stayed next to the last word in the string.
Try this code
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
oXL.Quit();
//...
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
This convention is used for special variables or methods (so-called “magic method”) such as __init__
and __len__
. These methods provides special syntactic features or do special things.
For example, __file__
indicates the location of Python file, __eq__
is executed when a == b
expression is executed.
A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__
that will be executed at first when an instance of a class is created).
class A:
def __init__(self, a): # use special method '__init__' for initializing
self.a = a
def __custom__(self): # custom special method. you might almost do not use it
pass
You should be able to clear your credentials from your browser via "Clear Browsing Data..." in chrome://settings/advanced
Use the string.substring(from, to)
API. In your case, use string.substring(0,8).
If you don't want jquery then you can do it with javascript :-
@Html.DropDownList("Sortby", new SelectListItem[]
{
new SelectListItem() { Text = "Newest to Oldest", Value = "0" },
new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
new { @onchange="callChangefunc(this.value)"
});
<script>
function callChangefunc(val){
window.location.href = "/Controller/ActionMethod?value=" + val;
}
</script>
To get the appID you could use the following line of code:
var applicationId = ((GuidAttribute)typeof(Program).Assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value;
For this you need to include the System.Runtime.InteropServices;
This answer is community wiki. If you feel it could be made better, feel free to edit it!
In Swift, Optional<Wrapped>
is an option type: it can contain any value from the original ("Wrapped") type, or no value at all (the special value nil
). An optional value must be unwrapped before it can be used.
Optional is a generic type, which means that Optional<Int>
and Optional<String>
are distinct types — the type inside <>
is called the Wrapped type. Under the hood, an Optional is an enum with two cases: .some(Wrapped)
and .none
, where .none
is equivalent to nil
.
Optionals can be declared using the named type Optional<T>
, or (most commonly) as a shorthand with a ?
suffix.
var anInt: Int = 42
var anOptionalInt: Int? = 42
var anotherOptionalInt: Int? // `nil` is the default when no value is provided
var aVerboseOptionalInt: Optional<Int> // equivalent to `Int?`
anOptionalInt = nil // now this variable contains nil instead of an integer
Optionals are a simple yet powerful tool to express your assumptions while writing code. The compiler can use this information to prevent you from making mistakes. From The Swift Programming Language:
Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code requires a
String
, type safety prevents you from passing it anInt
by mistake. Likewise, type safety prevents you from accidentally passing an optionalString
to a piece of code that requires a non-optionalString
. Type safety helps you catch and fix errors as early as possible in the development process.
Some other programming languages also have generic option types: for example, Maybe in Haskell, option in Rust, and optional in C++17.
In programming languages without option types, a particular "sentinel" value is often used to indicate the absence of a valid value. In Objective-C, for example, nil
(the null pointer) represents the lack of an object. For primitive types such as int
, a null pointer can't be used, so you would need either a separate variable (such as value: Int
and isValid: Bool
) or a designated sentinel value (such as -1
or INT_MIN
). These approaches are error-prone because it's easy to forget to check isValid
or to check for the sentinel value. Also, if a particular value is chosen as the sentinel, that means it can no longer be treated as a valid value.
Option types such as Swift's Optional
solve these problems by introducing a special, separate nil
value (so you don't have to designate a sentinel value), and by leveraging the strong type system so the compiler can help you remember to check for nil when necessary.
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
This is done with the !
operator on an optional. For example:
let anOptionalString: String?
print(anOptionalString!) // <- CRASH
Fatal error: Unexpectedly found nil while unwrapping an Optional value
As anOptionalString
is nil
here, you will get a crash on the line where you force unwrap it.
These are defined with a !
, rather than a ?
after the type.
var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used
These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
print(optionalDouble) // <- CRASH
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
In order to work out which variable caused the crash, you can hold ? while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil
at runtime, and therefore crash when they are implicitly unwrapped. When fixing connections, try deleting the lines of code that define your outlets, then reconnect them.
As a general rule, you should never explicitly force unwrap an optional with the !
operator. There may be cases where using !
is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.
While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
The simplest way to check whether an optional contains a value, is to compare it to nil
.
if anOptionalInt != nil {
print("Contains a value!")
} else {
print("Doesn’t contain a value.")
}
However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...}
or if var x = anOptional {...}
, depending if you need to modify the value of the new variable after binding it.
For example:
if let number = anOptionalInt {
print("Contains a value! It is \(number)!")
} else {
print("Doesn’t contain a number")
}
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number
) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.
What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
var anOptionalInt : Int?
var anOptionalString : String?
if let number = anOptionalInt, let text = anOptionalString {
print("anOptionalInt contains a value: \(number). And so does anOptionalString, it’s: \(text)")
} else {
print("One or more of the optionals don’t contain a value")
}
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
if let number = anOptionalInt, number > 0 {
print("anOptionalInt contains a value: \(number), and it’s greater than zero!")
}
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}
.
So, to use them with an optional binding, you can do this:
guard let number = anOptionalInt else {
return
}
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If anOptionalInt
contains a value, it will be unwrapped and assigned to the new number
constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.
The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
guard let number = anOptionalInt else {
return
}
print("anOptionalInt contains a value, and it’s: \(number)!")
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where
clause.
Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b
, where a
is an optional type and b
is the same type as a
(although usually non-optional).
It essentially lets you say “If a
contains a value, unwrap it. If it doesn’t then return b
instead”. For example, you could use it like this:
let number = anOptionalInt ?? 0
This will define a number
constant of Int
type, that will either contain the value of anOptionalInt
, if it contains a value, or 0
otherwise.
It’s just shorthand for:
let number = anOptionalInt != nil ? anOptionalInt! : 0
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ?
when using it.
For example, say we have a variable foo
, of type an optional Foo
instance.
var foo : Foo?
If we wanted to call a method on foo
that doesn’t return anything, we can simply do:
foo?.doSomethingInteresting()
If foo
contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.
(This is similar behaviour to sending messages to nil
in Objective-C)
This can therefore also be used to set properties as well as call methods. For example:
foo?.bar = Bar()
Again, nothing bad will happen here if foo
is nil
. Your code will simply continue executing.
Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil
.
(This is because an optional value will return Void?
rather than Void
on a method that doesn’t return anything)
For example:
if (foo?.bar = Bar()) != nil {
print("bar was set successfully")
} else {
print("bar wasn’t set successfully")
}
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo
is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo
itself before accessing methods or calling methods that return values.
Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo
has an optional property baz
, which has a property qux
– you could write the following:
let optionalQux = foo?.baz?.qux
Again, because foo
and baz
are optional, the value returned from qux
will always be an optional regardless of whether qux
itself is optional.
map
and flatMap
An often underused feature with optionals is the ability to use the map
and flatMap
functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil
.
For example, let’s say you have an optional string:
let anOptionalString:String?
By applying the map
function to it – we can use the stringByAppendingString
function in order to concatenate it to another string.
Because stringByAppendingString
takes a non-optional string argument, we cannot input our optional string directly. However, by using map
, we can use allow stringByAppendingString
to be used if anOptionalString
has a value.
For example:
var anOptionalString:String? = "bar"
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // Optional("foobar")
However, if anOptionalString
doesn’t have a value, map
will return nil
. For example:
var anOptionalString:String?
anOptionalString = anOptionalString.map {unwrappedString in
return "foo".stringByAppendingString(unwrappedString)
}
print(anOptionalString) // nil
flatMap
works similarly to map
, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.
try!
Swift's error handling system can be safely used with Do-Try-Catch:
do {
let result = try someThrowingFunc()
} catch {
print(error)
}
If someThrowingFunc()
throws an error, the error will be safely caught in the catch
block.
The error
constant you see in the catch
block has not been declared by us - it's automatically generated by catch
.
You can also declare error
yourself, it has the advantage of being able to cast it to a useful format, for example:
do {
let result = try someThrowingFunc()
} catch let error as NSError {
print(error.debugDescription)
}
Using try
this way is the proper way to try, catch and handle errors coming from throwing functions.
There's also try?
which absorbs the error:
if let result = try? someThrowingFunc() {
// cool
} else {
// handle the failure, but there's no error information available
}
But Swift's error handling system also provides a way to "force try" with try!
:
let result = try! someThrowingFunc()
The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use try!
if you can prove that its result will never fail in your context - and this is very rare.
Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?
, in the rare cases where handling the error is not important.
I used following code on my sample application to start new activity.
Button next = (Button) findViewById(R.id.TEST);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent( view.getContext(), MyActivity.class);
startActivityForResult(myIntent, 0);
}
});
You should learn about EAFP vs LBYL.
from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
if isinstance(infile, basestring):
infile=open(infile,'r')
if isinstance(outfile, basestring):
outfile=open(outfile,'w')
for lineno, line in enumerate(infile, 1):
line = line.strip()
try:
print >>outfile, int(line,16)
except ValueError:
return "Bad value at line %i: %r" % (lineno, line)
if __name__ == "__main__":
from sys import argv, exit
exit(main(*argv[1:]))
A more powerful and flexible example can be found here: C# File Upload with form fields, cookies and headers
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+------+----------------------+
select group_concat(name) from Pets
group by type
Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values
Result:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+
In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):
def change
add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end
The normal index would have been:
:index_studies_on_professor_id_and_user_id
The logic would be:
index
becomes idx
_id
Which usually does the job.
There is a module on npm called mssqlhelper
You can install it to your project by npm i mssqlhelper
Example of connecting and performing a query:
var db = require('./index');
db.config({
host: '192.168.1.100'
,port: 1433
,userName: 'sa'
,password: '123'
,database:'testdb'
});
db.query(
'select @Param1 Param1,@Param2 Param2'
,{
Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
,Param2: { type : 'Int',value : 321 }
}
,function(res){
if(res.err)throw new Error('database error:'+res.err.msg);
var rows = res.tables[0].rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
}
}
);
You can read more about it here: https://github.com/play175/mssqlhelper
:o)
This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
Hope it helps someone like me!
This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function.
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (based on the official example):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<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="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
why not printf '%02d' $num
? See help printf
for this internal bash command.
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.
If you are making the fetch call to your localhost which I'm guessing is run by node.js in the same directory as your backbone code, than it will most likely be on http://localhost:3000
or something like that. Than this should be your model:
var model = Backbone.Model.extend({
url: '/item'
});
And in your node.js you now have to accept that call like this:
app.get('/item', function(req, res){
res.send('some info here');
});