Migrate to androidX library
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate
to AndroidX from the menu bar.
Source: https://developer.android.com/jetpack/androidx/migrate
You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)
Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)
Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):
Function getTextFromPDF(ByVal strFilename As String) As String
Dim objAVDoc As New AcroAVDoc
Dim objPDDoc As New AcroPDDoc
Dim objPage As AcroPDPage
Dim objSelection As AcroPDTextSelect
Dim objHighlight As AcroHiliteList
Dim pageNum As Long
Dim strText As String
strText = ""
If (objAvDoc.Open(strFilename, "") Then
Set objPDDoc = objAVDoc.GetPDDoc
For pageNum = 0 To objPDDoc.GetNumPages() - 1
Set objPage = objPDDoc.AcquirePage(pageNum)
Set objHighlight = New AcroHiliteList
objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
Set objSelection = objPage.CreatePageHilite(objHighlight)
If Not objSelection Is Nothing Then
For tCount = 0 To objSelection.GetNumText - 1
strText = strText & objSelection.GetText(tCount)
Next tCount
End If
Next pageNum
objAVDoc.Close 1
End If
getTextFromPDF = strText
End Function
What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.
Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.
Hope that helps!
I faced the same error but i solved this by selecting invalidate caches/restart option.
Click
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
std::chrono::milliseconds
to integer (uint64_t
to avoid overflow)#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
std::cout << timeSinceEpochMillisec() << std::endl;
return 0;
}
I found this on another site not sure if it works or not.
Application.Wait Now + 1/(24*60*60.0*2)
the numerical value 1 = 1 day
1/24 is one hour
1/(24*60) is one minute
so 1/(24*60*60*2) is 1/2 second
You need to use a decimal point somewhere to force a floating point number
Not sure if this will work worth a shot for milliseconds
Application.Wait (Now + 0.000001)
In similar case I used the following code:
DateTime upperBound = DateTime.Today.AddDays(1); // If today is October 9, then upperBound is set to 2012-10-10 00:00:00
return var _My_ResetSet_Array = _DB
.tbl_MyTable
.Where(x => x.Active == true
&& x.DateTimeValueColumn < upperBound) // Accepts all dates earlier than October 10, time of day doesn't matter here
.Select(x => x);
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
use an unsigned long long (i.e. a 64 bit unit) to represent the system time:
typedef unsigned long long u64;
u64 u64useconds;
struct timeval tv;
gettimeofday(&tv,NULL);
u64useconds = (1000000*tv.tv_sec) + tv.tv_usec;
Your curtime
variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t
values just fine.
memset
is generally designed to be very very fast general-purpose setting/zeroing code. It handles all cases with different sizes and alignments, which affect the kinds of instructions you can use to do your work. Depending on what system you're on (and what vendor your stdlib comes from), the underlying implementation might be in assembler specific to that architecture to take advantage of whatever its native properties are. It might also have internal special cases to handle the case of zeroing (versus setting some other value).
That said, if you have very specific, very performance critical memory zeroing to do, it's certainly possible that you could beat a specific memset
implementation by doing it yourself. memset
and its friends in the standard library are always fun targets for one-upmanship programming. :)
#include <ctime>
#include <cstdio>
#include <iostream>
#include <chrono>
#include <sys/time.h>
using namespace std;
using namespace std::chrono;
void f1()
{
high_resolution_clock::time_point t1 = high_resolution_clock::now();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
double dif = duration_cast<nanoseconds>( t2 - t1 ).count();
printf ("Elasped time is %lf nanoseconds.\n", dif );
}
void f2()
{
timespec ts1,ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
clock_gettime(CLOCK_REALTIME, &ts2);
double dif = double( ts2.tv_nsec - ts1.tv_nsec );
printf ("Elasped time is %lf nanoseconds.\n", dif );
}
void f3()
{
struct timeval t1,t0;
gettimeofday(&t0, 0);
gettimeofday(&t1, 0);
double dif = double( (t1.tv_usec-t0.tv_usec)*1000);
printf ("Elasped time is %lf nanoseconds.\n", dif );
}
void f4()
{
high_resolution_clock::time_point t1 , t2;
double diff = 0;
t1 = high_resolution_clock::now() ;
for(int i = 1; i <= 10 ; i++)
{
t2 = high_resolution_clock::now() ;
diff+= duration_cast<nanoseconds>( t2 - t1 ).count();
t1 = t2;
}
printf ("high_resolution_clock:: Elasped time is %lf nanoseconds.\n", diff/10 );
}
void f5()
{
timespec ts1,ts2;
double diff = 0;
clock_gettime(CLOCK_REALTIME, &ts1);
for(int i = 1; i <= 10 ; i++)
{
clock_gettime(CLOCK_REALTIME, &ts2);
diff+= double( ts2.tv_nsec - ts1.tv_nsec );
ts1 = ts2;
}
printf ("clock_gettime:: Elasped time is %lf nanoseconds.\n", diff/10 );
}
void f6()
{
struct timeval t1,t2;
double diff = 0;
gettimeofday(&t1, 0);
for(int i = 1; i <= 10 ; i++)
{
gettimeofday(&t2, 0);
diff+= double( (t2.tv_usec-t1.tv_usec)*1000);
t1 = t2;
}
printf ("gettimeofday:: Elasped time is %lf nanoseconds.\n", diff/10 );
}
int main()
{
// f1();
// f2();
// f3();
f6();
f4();
f5();
return 0;
}
This works and shows more than 255 characters in the message box.
Sub TestStrLength()
Dim s As String
Dim i As Integer
s = ""
For i = 1 To 500
s = s & "1234567890"
Next i
MsgBox s
End Sub
The message box truncates the string to 1023 characters, but the string itself can be very large.
I would also recommend that instead of using fixed variables names with numbers (e.g. Var1
, Var2
, Var3
, ... Var255
) that you use an array. This is much shorter declaration and easier to use - loops.
Here's an example:
Sub StrArray()
Dim var(256) As Integer
Dim i As Integer
Dim s As String
For i = 1 To 256
var(i) = i
Next i
s = "Tims_pet_Robot"
For i = 1 To 256
s = s & " """ & var(i) & """"
Next i
SecondSub (s)
End Sub
Sub SecondSub(s As String)
MsgBox "String length = " & Len(s)
End Sub
Updated this to show that a string can be longer than 255 characters and used in a subroutine/function as a parameter that way. This shows that the string length is 1443 characters. The actual limit in VBA is 2GB per string.
Perhaps there is instead a problem with the API that you are using and that has a limit to the string (such as a fixed length string). The issue is not with VBA itself.
Ok, I see the problem is specifically with the Application.OnTime method itself. It is behaving like Excel functions in that they only accept strings that are up to 255 characters in length. VBA procedures and functions though do not have this limit as I have shown. Perhaps then this limit is imposed for any built-in Excel object method.
Update:
changed ...longer than 256 characters...
to ...longer than 255 characters...
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
If you wish more look at: http://developer.android.com/intl/pt-br/guide/topics/resources/string-resource.html#FormattingAndStyling
#pragma once
is based on the full path of the filename. So what you likely have is there are two identical copies of either MyClass.h or Winsock2.h in different directories.
For completeness' sake, here's the way to do it with arrow
(better dates and times for Python):
sometime = arrow.now()
abitlater = sometime.shift(seconds=3)
To avoid the fact that destroy_all
instantiates all the records and destroys them one at a time, you can use it directly from the model class.
So instead of :
u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
You can do :
u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"
The result is one query to destroy all the associated records
In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
Use this example, you can split with the colspan
attribute
<TABLE BORDER>
<TR>
<TD>Item 1</TD>
<TD>Item 1</TD>
<TD COLSPAN=2>Item 2</TD>
</TR>
<TR>
<TD>Item 3</TD>
<TD>Item 3</TD>
<TD>Item 4</TD>
<TD>Item 5</TD>
</TR>
</TABLE>
More examples at http://hypermedia.univ-paris8.fr/jean/internet/ex_table.html.
Believe it or not, this is normal behaviour. An exception is thrown but handled by the XmlSerializer, so if you just ignore it everything should continue on fine.
I have found this very annoying, and there have been many complaints about this if you search around a bit, but from what I've read Microsoft don't plan on doing anything about it.
You can avoid getting Exception popups all the time while debugging if you switch off first chance exceptions for that specific exception. In Visual Studio, go to Debug -> Exceptions (or press Ctrl + Alt + E), Common Language Runtime Exceptions -> System.IO -> System.IO.FileNotFoundException.
You can find information about another way around it in the blog post C# XmlSerializer FileNotFound exception (which discusses Chris Sells' tool XmlSerializerPreCompiler).
You can add directories to your ctags lookup. For example, I have a ctags index built for Qt4, and have this in my .vimrc:
set tags+=/usr/local/share/ctags/qt4
Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.
From jacoco:prepare-agent that says:
One of the ways to do this in case of maven-surefire-plugin - is to use syntax for late property evaluation:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>@{argLine} -your -extra -arguments</argLine> </configuration> </plugin>
Note the @{argLine}
that's added to -your -extra -arguments
.
Thanks Slava Semushin for noticing the change and reporting in the comment.
Following jacoco:prepare-agent that says:
[org.jacoco:jacoco-maven-plugin:0.7.2-SNAPSHOT:prepare-agent] Prepares a property pointing to the JaCoCo runtime agent that can be passed as a VM argument to the application under test. Depending on the project packaging type by default a property with the following name is set:
- tycho.testArgLine for packaging type eclipse-test-plugin and
- argLine otherwise.
Note that these properties must not be overwritten by the test configuration, otherwise the JaCoCo agent cannot be attached. If you need custom parameters please append them. For example:
<argLine>${argLine} -your -extra -arguments</argLine>
Resulting coverage information is collected during execution and by default written to a file when the process terminates.
you should change the following line in maven-surefire-plugin
plugin configuration from (note the ${argLine}
inside <argLine>
):
<argLine>-Xmx2048m</argLine>
to
<argLine>${argLine} -Xmx2048m</argLine>
Make also the necessary changes to the other plugin maven-failsafe-plugin
and replace the following (again, notice the ${argLine}
):
<argLine>-Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
to
<argLine>${argLine} -Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
A great ES6 option would be to padStart
an empty string. Like this:
var str = ''.padStart(10, "#");
Note: this won't work in IE (without a polyfill).
I started with the code from Dominic Barnes, incorporated the feedback from cWoDeR and I still had problems with the breadcrumbs at the third level when I used a sub-directory. So I rewrote it and have included the code below.
Note that I have set up my web site structure such that pages to be subordinate to (linked from) a page at the root level are set up as follows:
Create a folder with the EXACT same name as the file (including capitalization), minus the suffix, as a folder at the root level
place all subordinate files/pages into this folder
(eg, if want sobordinate pages for Customers.php:
create a folder called Customers at the same level as Customers.php
add an index.php file into the Customers folder which redirects to the calling page for the folder (see below for code)
This structure will work for multiple levels of subfolders.
Just make sure you follow the file structure described above AND insert an index.php file with the code shown in each subfolder.
The code in the index.php page in each subfolder looks like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redirected</title>
</head>
<body>
<?php
$root_dir = "web_root/" ;
$last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ;
$path_to_redirect = "/".$root_dir.$last_dir[0].".php" ;
header('Location: '.$path_to_redirect) ;
?>
</body>
</html>
If you use the root directory of the server as your web root (ie /var/www/html) then set $root_dir="": (do NOT leave the trailing "/" in). If you use a subdirectory for your web site (ie /var/www/html/web_root then set $root_dir = "web_root/"; (replace web_root with the actual name of your web directory)(make sure to include the trailing /)
at any rate, here is my (derivative) code:
<?php
// Big Thank You to the folks on StackOverflow
// See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb
// Edited to enable using subdirectories to /var/www/html as root
// eg, using /var/www/html/<this folder> as the root directory for this web site
// To enable this, enter the name of the subdirectory being used as web root
// in the $directory2 variable below
// Make sure to include the trailing "/" at the end of the directory name
// eg use $directory2="this_folder/" ;
// do NOT use $directory2="this_folder" ;
// If you actually ARE using /var/www/html as the root directory,
// just set $directory2 = "" (blank)
// with NO trailing "/"
// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ' , $home = 'Home')
{
// This sets the subdirectory as web_root (If you want to use a subdirectory)
// If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /)
$directory2 = "web_root/" ;
// This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ;
$path_array = array_filter(explode('/',$path)) ;
// This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root
// This removes the first item in the array path so it doesn't repeat
if ($directory2 != "")
{
array_shift($path_array) ;
}
// This will build our "base URL" ... Also accounts for HTTPS :)
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ;
// Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
$breadcrumbs = Array("<a href=\"$base\">$home</a>") ;
// Get the index for the last value in our path array
$last = end($path_array) ;
// Initialize the counter
$crumb_counter = 2 ;
// Build the rest of the breadcrumbs
foreach ($path_array as $crumb)
{
// Our "title" is the text that will be displayed representing the filename without the .suffix
// If there is no "." in the crumb, it is a directory
if (strpos($crumb,".") == false)
{
$title = $crumb ;
}
else
{
$title = substr($crumb,0,strpos($crumb,".")) ;
}
// If we are not on the last index, then create a hyperlink
if ($crumb != $last)
{
$calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ;
$calling_page_path = "/".implode('/',$calling_page_array).".php" ;
$breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ;
}
// Otherwise, just display the title
else
{
$breadcrumbs[] = $title ;
}
$crumb_counter = $crumb_counter + 1 ;
}
// Build our temporary array (pieces of bread) into one big string :)
return implode($separator, $breadcrumbs) ;
}
// <p><?= breadcrumbs() ? ></p>
// <p><?= breadcrumbs(' > ') ? ></p>
// <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p>
?>
I seem to find the trick:
Just remove the form target
attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me:
<form>
<input name="foo" required>
<button id="submit">Submit</button>
</form>
<script>
$('#submit').click( function(e){
var isValid = true;
$('form input').map(function() {
isValid &= this.validity['valid'] ;
}) ;
if (isValid) {
console.log('valid!');
// post something..
} else
console.log('not valid!');
});
</script>
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
The C++ standard explicitly talks about this, see section "17.5.2.1.3 Bitmask types":
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf
Given this "template" you get:
enum AnimalFlags : unsigned int
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
};
constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
return static_cast<AnimalFlags>(
static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}
AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
X = X | Y; return X;
}
And similar for the other operators. Also note the "constexpr", it is needed if you want the compiler to be able to execute the operators compile time.
If you are using C++/CLI and want to able assign to enum members of ref classes you need to use tracking references instead:
AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
X = X | Y; return X;
}
NOTE: This sample is not complete, see section "17.5.2.1.3 Bitmask types" for a complete set of operators.
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
Both of these errors arise as a result of a provisioning profile not existing. To create one, simply do the following as suggested in the error message:
Some people argue that a method should have a single point of exit (e.g., only one return
). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.
The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.
Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.
Determining your Node version
node -v // or node --version
npm -v // npm version or long npm --version
Ensure that you have n
installed
sudo npm install -g n // -g for global installation
Upgrading to the latest stable version
sudo n stable
Changing to a specific version
sudo n 10.16.0
Answer inspired by this article.
You could try this registry hack:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000
If it works, just keep increasing the KeepAliveTime
. It is currently set for 2 minutes.
Maybe .text
instead of .html
?
compgen -c python | grep -P '^python\d'
This lists some other python things too, But hey, You can identify all python versions among them.
this
can be omitted. All you need to get the current class name is:
GetType().Name
app.get('/category', function(req, res) {
var string = query
res.redirect('/?valid=' + string);
});
in the ejs you can directly use valid:
<% var k = valid %>
Here are the timeit results for the top 2 answers. Note that "file.txt" is a text file containing 100,000+ lines of random string with a file size of 1MB+.
Using itertools:
import itertools
from timeit import timeit
timeit("""with open("file.txt", "r") as fo:
for line in itertools.islice(fo, 90000, None):
line.strip()""", number=100)
>>> 1.604976346003241
Using two for loops:
from timeit import timeit
timeit("""with open("file.txt", "r") as fo:
for i in range(90000):
next(fo)
for j in fo:
j.strip()""", number=100)
>>> 2.427317383000627
clearly the itertools method is more efficient when dealing with large files.
Simple check to see if two time periods overlap:
bool overlap = a.start < b.end && b.start < a.end;
or in your code:
bool overlap = tStartA < tEndB && tStartB < tEndA;
(Use <=
instead of <
if you change your mind about wanting to say that two periods that just touch each other overlap.)
sometimes you need to select some fields by FirstOrDefault()
or singleOrDefault()
you can use the below query:
List<ResultLine> result = Lines
.GroupBy(l => l.ProductCode)
.Select(cl => new Models.ResultLine
{
ProductName = cl.select(x=>x.Name).FirstOrDefault(),
Quantity = cl.Count().ToString(),
Price = cl.Sum(c => c.Price).ToString(),
}).ToList();
This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).
Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.
The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:
a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns
OR
b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along
The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.
I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue
I had the same problem as I like using the Try-method-pattern which basically seems to be incompatible to the async-await-paradigm...
Important to me is that I can call the Try-method within a single if-clause and do not have to pre-define the out-variables before, but can do it in-line like in the following example:
if (TryReceive(out string msg))
{
// use msg
}
So I came up with the following solution:
Define a helper struct:
public struct AsyncOut<T, OUT>
{
private readonly T returnValue;
private readonly OUT result;
public AsyncOut(T returnValue, OUT result)
{
this.returnValue = returnValue;
this.result = result;
}
public T Out(out OUT result)
{
result = this.result;
return returnValue;
}
public T ReturnValue => returnValue;
public static implicit operator AsyncOut<T, OUT>((T returnValue ,OUT result) tuple) =>
new AsyncOut<T, OUT>(tuple.returnValue, tuple.result);
}
Define async Try-method like this:
public async Task<AsyncOut<bool, string>> TryReceiveAsync()
{
string message;
bool success;
// ...
return (success, message);
}
Call the async Try-method like this:
if ((await TryReceiveAsync()).Out(out string msg))
{
// use msg
}
For multiple out parameters you can define additional structs (e.g. AsyncOut<T,OUT1, OUT2>) or you can return a tuple.
This error creeps in if we make some spelling mistake in entering the variable name. Like in stored proc, I have the variable name x and in my insert statement I am using
insert into tablename values(y);
It will throw an error column not allowed here.
If you don't care about dirty reads (i.e. in a predominately READ situation), then NOLOCK
is fine.
BUT, be aware that the majority of locking problems are due to not having the 'correct' indexes for your query workload (assuming the hardware is up to the task).
And the guru's explanation was correct. It is usually a band-aid solution to a more serious problem.
Edit: I'm definitely not suggesting that NOLOCK should be used. I guess I should have made that obviously clear. (I would only ever use it, in extreme circumstances where I had analysed that it was OK). AS an example, a while back I worked on some TSQL that had been sprinkled with NOLOCK to try and alleviate locking problems. I removed them all, implemented the correct indexes, and ALL of the deadlocks went away.
Copy a file in a sane way:
#include <fstream>
int main()
{
std::ifstream src("from.ogv", std::ios::binary);
std::ofstream dst("to.ogv", std::ios::binary);
dst << src.rdbuf();
}
This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost
has a copy file method in its filesystem class.
There is a C method for interacting with the file system:
#include <copyfile.h>
int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);
I ended up with this function to safely replace text without side effects (so far):
function replaceInText(element, pattern, replacement) {
for (let node of element.childNodes) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
replaceInText(node, pattern, replacement);
break;
case Node.TEXT_NODE:
node.textContent = node.textContent.replace(pattern, replacement);
break;
case Node.DOCUMENT_NODE:
replaceInText(node, pattern, replacement);
}
}
}
It's for cases where the 16kB of findAndReplaceDOMText
are a bit too heavy.
Composite primary keys are what you want where you want to create a many to many relationship with a fact table. For example, you might have a holiday rental package that includes a number of properties in it. On the other hand, the property could also be available as a part of a number of rental packages, either on its own or with other properties. In this scenario, you establish the relationship between the property and the rental package with a property/package fact table. The association between a property and a package will be unique, you will only ever join using property_id with the property table and/or package_id with the package table. Each relationship is unique and an auto_increment key is redundant as it won't feature in any other table. Hence defining the composite key is the answer.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
If you do not want to use angular-ui-router, but would like to have your controllers lazy loaded via RequireJS, there are couple of problems with event $routeChangeStart
when using your controllers as RequireJS modules (lazy loaded).
You cannot be sure the controller will be loaded before $routeChangeStart
gets triggered -- in fact it wont be loaded. That means you cannot access properties of next
route like locals
or $$route
because they are not yet setup.
Example:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}]
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(next.$$route, next.locals); // undefined, undefined
});
}]);
This means you cannot check access rights in there.
Solution:
As loading of controller is done via resolve, you can do the same with your access control check:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}],
access: ["$q", function($q) {
var deferred = $q.defer();
if (/* some logic to determine access is granted */) {
deferred.resolve();
} else {
deferred.reject("You have no access rights to go there");
}
return deferred.promise;
}],
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeError", function(event, next, current, error) {
console.log("Error: " + error); // "Error: You have no access rights to go there"
});
}]);
Note here that instead of using event $routeChangeStart
I'm using $routeChangeError
As distribute has been merged back into setuptools, it is now recommended to install/upgrade setuptools instead:
[sudo] pip install --upgrade setuptools
Three possible problems with the above code:
This is why org.apache.tools.ant.util.ResourceUtils.copyResource
is so complicated. Also note that while transferFrom is OK, transferTo breaks on JDK 1.4 on Linux (see Bug ID:5056395) – Jesse Glick Jan
Ok, I recently met the same issue too while working on a WordPress
installation using apache2
on the server on Ubuntu 20.04
.
I experienced this issue when I changed file ownership to another user:
Here's what worked for me:
$ sudo chown -R www-data:www-data /var/www/YOUR-DIRECTORY
Here's a bit more context into the issue:
The above command gives ownership of all the files [in that folder] to the www-data user and group. This is the user that the Apache web server runs as, and Apache will need to be able to read and write WordPress
files in order to serve the website and perform automatic updates.
Be sure to point to your server’s relevant directory (replace YOUR-DIRECTORY
with your actual folder).
You could run through this insightful article on digitalocean.
This will get ALL parameters from the request. For Debugging purposes only:
@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
Map<String, String[]> parameters = request.getParameterMap();
for(String key : parameters.keySet()) {
System.out.println(key);
String[] vals = parameters.get(key);
for(String val : vals)
System.out.println(" -> " + val);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("test");
return mv;
}
You can use as following.
$start_date = date('Y-m-d H:i:s');
$end_date = date("Y-m-d 23:59:59", strtotime('+3 days', strtotime($start_date)));
You can also set days as constant and use like below.
if (!defined('ADD_DAYS')) define('ADD_DAYS','+3 days');
$end_date = date("Y-m-d 23:59:59", strtotime(ADD_DAYS, strtotime($start_date)));
You can use print_r to get human-readable output. But to display it as text we add "echo '';"
echo ''; print_r($row);
If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p
first, or use the --rsync-path
trick as explained here :
rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/
Or use the --relative
option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:
rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/
This way, you will end up with /pre_existing/dir/new/x/y/z/
And if you want to have "y/z/" created, but not inside "new/x/", you can add ./
where you want --relative
to begin:
rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/
would create /pre_existing/dir/y/z/.
Descending order using underscore can be done by multiplying the return value by -1.
//Ascending Order:
_.sortBy([2, 3, 1], function(num){
return num;
}); // [1, 2, 3]
//Descending Order:
_.sortBy([2, 3, 1], function(num){
return num * -1;
}); // [3, 2, 1]
If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.
//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
As of the C++11
standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string>
(as per paragraph 21.5).
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument
or std::out_of_range
).
If conversion succeeded and idx
is not 0
, idx
will contain the index of the first character that was not used for decoding. This could be an index behind the last character.
Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10
until z=35
). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.
Finally, for each function there is also an overload that accepts a std::wstring
as it's first parameter.
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.
As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.
There are also similar functions defined that are named to_wstring
, these will return a std::wstring
.
The only way would probably be to set different widths for different screen sizes, but this approach is pretty inacurate and you should use a js solution.
h1 {
font-size: 20px;
}
@media all and (max-device-width: 720px){
h1 {
font-size: 18px;
}
}
@media all and (max-device-width: 640px){
h1 {
font-size: 16px;
}
}
@media all and (max-device-width: 320px){
h1 {
font-size: 12px;
}
}
If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common = {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
};
}]);
How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."
On some older C code (quite some time ago), I found code analogous to:
std::string weekEnumToStr(int n)
{
std::string s("unknown");
switch (n)
{
case 0: { s = "Mon"; } break;
case 1: { s = "Tue"; } break;
case 2: { s = "Wed"; } break;
case 3: { s = "Thu"; } break;
case 4: { s = "Fri"; } break;
case 5: { s = "Sat"; } break;
case 6: { s = "Sun"; } break;
}
return s;
}
Con: This establishes a "pathological dependency" between the enumeration values and the function... meaning if you change the enum you must change the function to match. I suppose this is true even for a std::map.
I vaguely remember we found a utility to generate the function code from the enum code. The enum table length had grown to several hundred ... and at some point it is maybe a sound choice to write code to write code.
Note -
in an embedded system enhancement effort, my team replaced many tables (100+?) of null-terminated-strings used to map enum int values to their text strings.
The problem with the tables was that a value out of range was often not noticed because many of these tables were gathered into one region of code / memory, such that a value out-of-range reached past the named table end(s) and returned a null-terminated-string from some subsequent table.
Using the function-with-switch statement also allowed us to add an assert in the default clause of the switch. The asserts found several more coding errors during test, and our asserts were tied into a static-ram-system-log our field techs could search.
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://dork.com/service", new NameValueCollection()
{
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
string result = System.Text.Encoding.UTF8.GetString(response);
}
You will need these includes:
using System;
using System.Collections.Specialized;
using System.Net;
If you're insistent on using a static method/class:
public static class Http
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}
Then simply:
var response = Http.Post("http://dork.com/service", new NameValueCollection() {
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
How to disable clicking another div click until first one popup div close
<p class="btn1">One</p>
<div id="box1" class="popup">
Test Popup Box One
<span class="close">X</span>
</div>
<!-- Two -->
<p class="btn2">Two</p>
<div id="box2" class="popup">
Test Popup Box Two
<span class="close">X</span>
</div>
<style>
.disabledbutton {
pointer-events: none;
}
.close {
cursor: pointer;
}
</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
$("#box1").css('display','block');
$(".btn2,.btn3").addClass("disabledbutton");
});
$(".close").click(function(){
$("#box1").css('display','none');
$(".btn2,.btn3").removeClass("disabledbutton");
});
</script>
The commands from WEFX worked for me after I enabled the parent features RemoteServerAdministrationTools, RemoteServerAdministrationTools-Roles, and RemoteServerAdministrationTools-Roles-AD
You can add to the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
This is by far the easiest way to do it.
One of the most interesting features in HTML5
is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:
For more reference see Introducing the HTML5 storage APIs
And how to use
http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:
CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
Still, you may get:
ERROR: source database "originaldb" is being accessed by other users
To disconnect all other users from the database, you can use this query:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();
Use color property to change the color of your target element as follow :
.icon-cog { // selector of your element
color: black;
}
Or in the newest version of font-awesome , you can choose among filled or not filled icons
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
you can use pow(base, exponent)
from #include <math.h>
or create your own:
int myPow(int x,int n)
{
int i; /* Variable used in loop counter */
int number = 1;
for (i = 0; i < n; ++i)
number *= x;
return(number);
}
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
The syntax is
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
I had massive problems with getting any of those scripts to work with sending mail in powershell. Turned out you need to create an app-password for your gmail-account to authenticate in the script. Now it works flawlessly!
Answered by the OP:
Add this to your CSS file.
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Set the fixed height of the footer here */
#push,
#footer {
height: 60px;
}
#footer {
background-color: #eee;
}
/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
replot
This is another way to get multiple plots at once:
plot file1.data
replot file2.data
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
unanswered core problem persists:
My working directory is now c:\users\projectname.git So then I try to import the project using the eclipse "import" option. When I try to import selecting the option "Use the new projects wizard" the source code is not imported, if I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project. When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?
Yes it should.
It's a bug. Reported here.
Here is a workaround:
Import as general project
Notice the imported data is no valid Eclipse project (no build path available)
Open the .project
xml file in the project folder in Eclipse. If you can't see this file, see How can I get Eclipse to show .* files?.
Go to source
tab
Search for
<natures></natures>
and change it to<natures><nature>org.eclipse.jdt.core.javanature</nature></natures>
and save the file
(idea comes from here)
Right click the src
folder, go to Build Path...
and click Use as Source Folder
After that, you should be able to run & debug the project, and also use team actions via right-click in the package explorer.
If you still have troubles running the project (something like "main class not found"), make sure the <buildSpec>
inside the .project
file is set (as described here):
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
You can query with a regular expression:
db.users.find({"name": /m/});
If the string is coming from the user, maybe you want to escape the string before using it. This will prevent literal chars from the user to be interpreted as regex tokens.
For example, searching the string "A." will also match "AB" if not escaped.
You can use a simple replace
to escape your string before using it. I made it a function for reusing:
function textLike(str) {
var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
return new RegExp(escaped, 'i');
}
So now, the string becomes a case-insensitive pattern matching also the literal dot. Example:
> textLike('A.');
< /A\./i
Now we are ready to generate the regular expression on the go:
db.users.find({ "name": textLike("m") });
Regarding WSDL (meaning "SOAP") as being "heavy-weight". Heavy matters how? If the toolset is doing all the "heavy lifting" for you, then why does it matter?
I have never yet needed to consume a complicated REST API. When I do, I expect I'll wish for a WSDL, which my tools will gladly convert into a set of proxy classes, so I can just call what appear to be methods. Instead, I suspect that in order to consume a non-trivial REST-based API, it will be necessary to write by hand a substantial amount of "light-weight" code.
Even when that's all done, you still will have translated human-readable documentation into code, with all the attendant risk that the humans read it wrong. Since WSDL is a machine-readable description of the service, it's much harder to "read it wrong".
Just a note: since this post, I have had the opportunity to work with a moderately complicated REST service. I did, indeed, wish for a WSDL or the equivalent, and I did, indeed, have to write a lot of code by hand. In fact, a substantial part of the development time was spent removing the code duplication of all the code that called different service operations "by hand".
Accepted answer is right but lacks solution. To avoid this error, you can add setHttpRequestRetryHandler (or setRetryHandler for apache components 4.4) for your HTTP client like in this answer.
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
Method that works nicely in Safari. Also works in Firefox and Opera, but with a warning.
Location: http://[email protected]/
This tells browser to open URL with new username, overriding previous one.
Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/
You can do something like this easily:
[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
At the time of writing this, the top voted answers on this page are imprecise and muddled on the declarative vs. imperative definition, including the answer that quotes Wikipedia. Some answers are conflating the terms in different ways.
Refer also to my explanation of why spreadsheet programming is declarative, regardless that the formulas mutate the cells.
Also, several answers claim that functional programming must be a subset of declarative. On that point it depends if we differentiate "function" from "procedure". Lets handle imperative vs. declarative first.
Definition of declarative expression
The only attribute that can possibly differentiate a declarative expression from an imperative expression is the referential transparency (RT) of its sub-expressions. All other attributes are either shared between both types of expressions, or derived from the RT.
A 100% declarative language (i.e. one in which every possible expression is RT) does not (among other RT requirements) allow the mutation of stored values, e.g. HTML and most of Haskell.
Definition of RT expression
RT is often referred to as having "no side-effects". The term effects does not have a precise definition, so some people don't agree that "no side-effects" is the same as RT. RT has a precise definition:
An expression
e
is referentially transparent if for all programsp
every occurrence ofe
inp
can be replaced with the result of evaluatinge
, without affecting the observable result ofp
.
Since every sub-expression is conceptually a function call, RT requires that the implementation of a function (i.e. the expression(s) inside the called function) may not access the mutable state that is external to the function (accessing the mutable local state is allowed). Put simply, the function (implementation) should be pure.
Definition of pure function
A pure function is often said to have "no side-effects". The term effects does not have a precise definition, so some people don't agree.
Pure functions have the following attributes.
Remember that RT applies to expressions (which includes function calls) and purity applies to (implementations of) functions.
An obscure example of impure functions that make RT expressions is concurrency, but this is because the purity is broken at the interrupt abstraction layer. You don't really need to know this. To make RT expressions, you call pure functions.
Derivative attributes of RT
Any other attribute cited for declarative programming, e.g. the citation from 1999 used by Wikipedia, either derives from RT, or is shared with imperative programming. Thus proving that my precise definition is correct.
Note, immutability of external values is a subset of the requirements for RT.
Declarative languages don't have looping control structures, e.g. for
and while
, because due to immutability, the loop condition would never change.
Declarative languages don't express control-flow other than nested function order (a.k.a logical dependencies), because due to immutability, other choices of evaluation order do not change the result (see below).
Declarative languages express logical "steps" (i.e. the nested RT function call order), but whether each function call is a higher level semantic (i.e. "what to do") is not a requirement of declarative programming. The distinction from imperative is that due to immutability (i.e. more generally RT), these "steps" cannot depend on mutable state, rather only the relational order of the expressed logic (i.e. the order of nesting of the function calls, a.k.a. sub-expressions).
For example, the HTML paragraph <p>
cannot be displayed until the sub-expressions (i.e. tags) in the paragraph have been evaluated. There is no mutable state, only an order dependency due to the logical relationship of tag hierarchy (nesting of sub-expressions, which are analogously nested function calls).
Evaluation order
The choice of evaluation order of sub-expressions can only give a varying result when any of the function calls are not RT (i.e. the function is not pure), e.g. some mutable state external to a function is accessed within the function.
For example, given some nested expressions, e.g. f( g(a, b), h(c, d) )
, eager and lazy evaluation of the function arguments will give the same results if the functions f
, g
, and h
are pure.
Whereas, if the functions f
, g
, and h
are not pure, then the choice of evaluation order can give a different result.
Note, nested expressions are conceptually nested functions, since expression operators are just function calls masquerading as unary prefix, unary postfix, or binary infix notation.
Tangentially, if all identifiers, e.g. a
, b
, c
, d
, are immutable everywhere, state external to the program cannot be accessed (i.e. I/O), and there is no abstraction layer breakage, then functions are always pure.
By the way, Haskell has a different syntax, f (g a b) (h c d)
.
Evaluation order details
A function is a state transition (not a mutable stored value) from the input to the output. For RT compositions of calls to pure functions, the order-of-execution of these state transitions is independent. The state transition of each function call is independent of the others, due to lack of side-effects and the principle that an RT function may be replaced by its cached value. To correct a popular misconception, pure monadic composition is always declarative and RT, in spite of the fact that Haskell's IO
monad is arguably impure and thus imperative w.r.t. the World
state external to the program (but in the sense of the caveat below, the side-effects are isolated).
Eager evaluation means the functions arguments are evaluated before the function is called, and lazy evaluation means the arguments are not evaluated until (and if) they are accessed within the function.
Definition: function parameters are declared at the function definition site, and function arguments are supplied at the function call site. Know the difference between parameter and argument.
Conceptually, all expressions are (a composition of) function calls, e.g. constants are functions without inputs, unary operators are functions with one input, binary infix operators are functions with two inputs, constructors are functions, and even control statements (e.g. if
, for
, while
) can be modeled with functions. The order that these argument functions (do not confuse with nested function call order) are evaluated is not declared by the syntax, e.g. f( g() )
could eagerly evaluate g
then f
on g
's result or it could evaluate f
and only lazily evaluate g
when its result is needed within f
.
Caveat, no Turing complete language (i.e. that allows unbounded recursion) is perfectly declarative, e.g. lazy evaluation introduces memory and time indeterminism. But these side-effects due to the choice of evaluation order are limited to memory consumption, execution time, latency, non-termination, and external hysteresis thus external synchronization.
Functional programming
Because declarative programming cannot have loops, then the only way to iterate is functional recursion. It is in this sense that functional programming is related to declarative programming.
But functional programming is not limited to declarative programming. Functional composition can be contrasted with subtyping, especially with respect to the Expression Problem, where extension can be achieved by either adding subtypes or functional decomposition. Extension can be a mix of both methodologies.
Functional programming usually makes the function a first-class object, meaning the function type can appear in the grammar anywhere any other type may. The upshot is that functions can input and operate on functions, thus providing for separation-of-concerns by emphasizing function composition, i.e. separating the dependencies among the subcomputations of a deterministic computation.
For example, instead of writing a separate function (and employing recursion instead of loops if the function must also be declarative) for each of an infinite number of possible specialized actions that could be applied to each element of a collection, functional programming employs reusable iteration functions, e.g. map
, fold
, filter
. These iteration functions input a first-class specialized action function. These iteration functions iterate the collection and call the input specialized action function for each element. These action functions are more concise because they no longer need to contain the looping statements to iterate the collection.
However, note that if a function is not pure, then it is really a procedure. We can perhaps argue that functional programming that uses impure functions, is really procedural programming. Thus if we agree that declarative expressions are RT, then we can say that procedural programming is not declarative programming, and thus we might argue that functional programming is always RT and must be a subset of declarative programming.
Parallelism
This functional composition with first-class functions can express the depth in the parallelism by separating out the independent function.
Brent’s Principle: computation with work w and depth d can be implemented in a p-processor PRAM in time O(max(w/p, d)).
Both concurrency and parallelism also require declarative programming, i.e. immutability and RT.
So where did this dangerous assumption that Parallelism == Concurrency come from? It’s a natural consequence of languages with side-effects: when your language has side-effects everywhere, then any time you try to do more than one thing at a time you essentially have non-determinism caused by the interleaving of the effects from each operation. So in side-effecty languages, the only way to get parallelism is concurrency; it’s therefore not surprising that we often see the two conflated.
Note the evaluation order also impacts the termination and performance side-effects of functional composition.
Eager (CBV) and lazy (CBN) are categorical duels[10], because they have reversed evaluation order, i.e. whether the outer or inner functions respectively are evaluated first. Imagine an upside-down tree, then eager evaluates from function tree branch tips up the branch hierarchy to the top-level function trunk; whereas, lazy evaluates from the trunk down to the branch tips. Eager doesn't have conjunctive products ("and", a/k/a categorical "products") and lazy doesn't have disjunctive coproducts ("or", a/k/a categorical "sums")[11].
Performance
As with non-termination, eager is too eager with conjunctive functional composition, i.e. compositional control structure does unnecessary work that isn't done with lazy. For example, eager eagerly and unnecessarily maps the entire list to booleans, when it is composed with a fold that terminates on the first true element.
This unnecessary work is the cause of the claimed "up to" an extra log n factor in the sequential time complexity of eager versus lazy, both with pure functions. A solution is to use functors (e.g. lists) with lazy constructors (i.e. eager with optional lazy products), because with eager the eagerness incorrectness originates from the inner function. This is because products are constructive types, i.e. inductive types with an initial algebra on an initial fixpoint[11]
As with non-termination, lazy is too lazy with disjunctive functional composition, i.e. coinductive finality can occur later than necessary, resulting in both unnecessary work and non-determinism of the lateness that isn't the case with eager[10][11]. Examples of finality are state, timing, non-termination, and runtime exceptions. These are imperative side-effects, but even in a pure declarative language (e.g. Haskell), there is state in the imperative IO monad (note: not all monads are imperative!) implicit in space allocation, and timing is state relative to the imperative real world. Using lazy even with optional eager coproducts leaks "laziness" into inner coproducts, because with lazy the laziness incorrectness originates from the outer function (see the example in the Non-termination section, where == is an outer binary operator function). This is because coproducts are bounded by finality, i.e. coinductive types with a final algebra on an final object[11].
Lazy causes indeterminism in the design and debugging of functions for latency and space, the debugging of which is probably beyond the capabilities of the majority of programmers, because of the dissonance between the declared function hierarchy and the runtime order-of-evaluation. Lazy pure functions evaluated with eager, could potentially introduce previously unseen non-termination at runtime. Conversely, eager pure functions evaluated with lazy, could potentially introduce previously unseen space and latency indeterminism at runtime.
Non-termination
At compile-time, due to the Halting problem and mutual recursion in a Turing complete language, functions can't generally be guaranteed to terminate.
With eager but not lazy, for the conjunction of Head
"and" Tail
, if either Head
or Tail
doesn't terminate, then respectively either List( Head(), Tail() ).tail == Tail()
or List( Head(), Tail() ).head == Head()
is not true because the left-side doesn't, and right-side does, terminate.
Whereas, with lazy both sides terminate. Thus eager is too eager with conjunctive products, and non-terminates (including runtime exceptions) in those cases where it isn't necessary.
With lazy but not eager, for the disjunction of 1
"or" 2
, if f
doesn't terminate, then List( f ? 1 : 2, 3 ).tail == (f ? List( 1, 3 ) : List( 2, 3 )).tail
is not true because the left-side terminates, and right-side doesn't.
Whereas, with eager neither side terminates so the equality test is never reached. Thus lazy is too lazy with disjunctive coproducts, and in those cases fails to terminate (including runtime exceptions) after doing more work than eager would have.
[10] Declarative Continuations and Categorical Duality, Filinski, sections 2.5.4 A comparison of CBV and CBN, and 3.6.1 CBV and CBN in the SCL.
[11] Declarative Continuations and Categorical Duality, Filinski, sections 2.2.1 Products and coproducts, 2.2.2 Terminal and initial objects, 2.5.2 CBV with lazy products, and 2.5.3 CBN with eager coproducts.
If you're working with localised strings, you might not be able to rely on the bold string always being at the end of the sentence. If this is the case then the following works well:
e.g. Query "blah" does not match any items
/* Create the search query part of the text, e.g. "blah".
The variable 'text' is just the value entered by the user. */
let searchQuery = "\"\(text)\""
/* Put the search text into the message */
let message = "Query \(searchQuery). does not match any items"
/* Find the position of the search string. Cast to NSString as we want
range to be of type NSRange, not Swift's Range<Index> */
let range = (message as NSString).rangeOfString(searchQuery)
/* Make the text at the given range bold. Rather than hard-coding a text size,
Use the text size configured in Interface Builder. */
let attributedString = NSMutableAttributedString(string: message)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range)
/* Put the text in a label */
label.attributedText = attributedString
Use:
private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
{
string path = System.IO.Path.Combine(path1, path2.TrimStart('\\', '/'), path3.TrimStart('\\', '/'), path4.TrimStart('\\', '/'));
string url = path.Replace('\\','/');
return new Uri(url);
}
It has the benefit of behaving exactly like Path.Combine
.
If you have multiples docker containers launched, use this
$ docker rm $(docker ps -aq)
It will remove all the current dockers listed in the "ps -aq" command.
Source : aaam on https://github.com/docker/docker/issues/12487
I have had the same problem with a simple Activity carrying only one fragment (which would get replaced sometimes). I then realized I use onSaveInstanceState only in the fragment (and onCreateView to check for savedInstanceState), not in the activity.
On device turn the activity containing the fragments gets restarted and onCreated is called. There I did attach the required fragment (which is correct on the first start).
On the device turn Android first re-created the fragment that was visible and then called onCreate of the containing activity where my fragment was attached, thus replacing the original visible one.
To avoid that I simply changed my activity to check for savedInstanceState:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
/**making sure you are not attaching the fragments again as they have
been
*already added
**/
return;
}
else{
// following code to attach fragment initially
}
}
I did not even Overwrite onSaveInstanceState of the activity.
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
Just in case someone is still looking for the answer,
let the browser take care of that. Try this:
display: table
on the container element.display: table-cell
on the child elements.The browser will evenly divide it whether you have 3 or 10 columns.
EDIT
the container element should also have: table-layout: fixed
otherwise the browser will determine the width of each element (most of the time not that bad).
From this reference:
If you acquire a table lock explicitly with LOCK TABLES, you can request a READ LOCAL lock rather than a READ lock to enable other sessions to perform concurrent inserts while you have the table locked.
This solution works with unittest
and nose
for Python 2 and Python 3:
#!/usr/bin/env python
import unittest
def make_function(description, a, b):
def ghost(self):
self.assertEqual(a, b, description)
print(description)
ghost.__name__ = 'test_{0}'.format(description)
return ghost
class TestsContainer(unittest.TestCase):
pass
testsmap = {
'foo': [1, 1],
'bar': [1, 2],
'baz': [5, 5]}
def generator():
for name, params in testsmap.iteritems():
test_func = make_function(name, params[0], params[1])
setattr(TestsContainer, 'test_{0}'.format(name), test_func)
generator()
if __name__ == '__main__':
unittest.main()
The highest-ranked answer by Mudassar Bashir using the "title" attribute seems the easiest way to do this, but it gives you less control over how the comment/tooltip is displayed.
I found that The answer by Christophe for a custom tooltip class seems to give much more control over the behavior of the comment/tooltip. Since the provided demo does not include a table, as per the question, here is a demo that includes a table.
Note that the "position" style for the parent element of the span (a in this case), must be set to "relative" so that the comment does not push the table contents around when it is displayed. It took me a little while to figure that out.
#MyTable{_x000D_
border-style:solid;_x000D_
border-color:black;_x000D_
border-width:2px_x000D_
}_x000D_
_x000D_
#MyTable td{_x000D_
border-style:solid;_x000D_
border-color:black;_x000D_
border-width:1px;_x000D_
padding:3px;_x000D_
}_x000D_
_x000D_
.CellWithComment{_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
.CellComment{_x000D_
display:none;_x000D_
position:absolute; _x000D_
z-index:100;_x000D_
border:1px;_x000D_
background-color:white;_x000D_
border-style:solid;_x000D_
border-width:1px;_x000D_
border-color:red;_x000D_
padding:3px;_x000D_
color:red; _x000D_
top:20px; _x000D_
left:20px;_x000D_
}_x000D_
_x000D_
.CellWithComment:hover span.CellComment{_x000D_
display:block;_x000D_
}
_x000D_
<table id="MyTable">_x000D_
<caption>Cell 1,2 Has a Comment</caption>_x000D_
<thead>_x000D_
<tr>_x000D_
<td>Heading 1</td>_x000D_
<td>Heading 2</td>_x000D_
<td>Heading 3</td>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr></tr>_x000D_
<td>Cell 1,1</td>_x000D_
<td class="CellWithComment">Cell 1,2_x000D_
<span class="CellComment">Here is a comment</span>_x000D_
</td>_x000D_
<td>Cell 1,3</td>_x000D_
<tr>_x000D_
<td>Cell 2,1</td>_x000D_
<td>Cell 2,2</td>_x000D_
<td>Cell 2,3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Some awk
version.
awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'
When pattern found, set c=5
If c
is true, print and decrease number of c
I had this problem and
dumpbin /exports mydll.dll
and
depends mydll.dll
showed 'DllRegisterServer'.
The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.
The new Grid CSS specification provides a far more elegant solution. Using position: absolute
may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.
Most minimal Grid Overlay example:
HTML
<div class="container">
<div class="content">This is the content</div>
<div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>
CSS
.container {
display: grid;
}
.content, .overlay {
grid-area: 1 / 1;
}
That's it. If you don't build for Internet Explorer, your code will most probably work.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:showAsAction="always"
/>
</menu>
This did the trick for me!
Instead of passing reference object passed the saved object, below is explanation which solve my issue:
//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)
//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
If you want to copy files and see a "progress" I suggest the script below in Batch that I used from another script as a base
I used a progress bar and a percentage while the script copies the game files Nuclear throne:
@echo off
title NTU Installer
setlocal EnableDelayedExpansion
@echo Iniciando instalacao...
if not exist "C:\NTU" (
md "C:\NTU
)
if not exist "C:\NTU\Profile" (
md "C:\NTU\Profile"
)
ping -n 5 localhost >nul
for %%f in (*.*) do set/a vb+=1
set "barra="
::loop da barra
for /l %%i in (1,1,70) do set "barra=!barra!Û"
rem barra vaiza para ser preenchida
set "resto="
rem loop da barra vazia
for /l %%i in (1,1,110) do set "resto=!resto!"
set i=0
rem carregameno de arquivos
for %%f in (*.*) do (
>>"log_ntu.css" (
copy "%%f" "C:\NTU">nul
echo Copiado:%%f
)
cls
set /a i+=1,percent=i*100/vb,barlen=70*percent/100
for %%a in (!barlen!) do echo !percent!%% /
[!barra:~0,%%a!%resto%]
echo Instalado:[%%f] / Complete:[!percent!%%/100%]
ping localhost -n 1.9 >nul
)
xcopy /e "Profile" "C:\NTU\Profile">"log_profile.css"
@echo Criando atalho na area de trabalho...
copy "NTU.lnk" "C:\Users\%username%\Desktop">nul
ping localhost -n 4 >nul
@echo Arquivos instalados!
pause
There is a customization that went into Boto3 recently which helps with this (among other things). It is currently exposed on the low-level S3 client, and can be used like this:
s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')
# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')
# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())
These functions will automatically handle reading/writing files as well as doing multipart uploads in parallel for large files.
Note that s3_client.download_file
won't create a directory. It can be created as pathlib.Path('/path/to/file.txt').parent.mkdir(parents=True, exist_ok=True)
.
As of PHP 7.1 you can simply do this:
$date = new DateTime( "NOW" );
echo $date->format( "m-d-Y H:i:s.u" );
It will display as:
04-11-2018 10:54:01.321688
System.out is "standard output" (stdout) and System.err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model. Most modern programming environments (C, Perl, etc.) support this model.
The standard output stream is used to print output from "normal operations" of the program, while the error stream is for "error messages". These need to be separate -- though in most cases they appear on the same console.
Suppose you have a simple program where you enter a phone number and it prints out the person who has that number. If you enter an invalid number, the program should inform you of that error, but it shouldn't do that as the answer: If you enter "999-ABC-4567" and the program prints an error message "Not a valid number", that doesn't mean there is a person named "Not a valid number" whose number is 999-ABC-4567. So it prints out nothing to the standard output, and the message "Not a valid number" is printed to the error output.
You can set up the execution environment to distinguish between the two streams, for example, make the standard output print to the screen and error output print to a file.
If you have date in DateTime
variable then its a DateTime
object and doesn't contain any format. Formatted date are expressed as string
when you call DateTime.ToString
method and provide format in it.
Lets say you have two DateTime
variable, you can use the compare method for comparision,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Code snippet taken from msdn.
Surround what you want to be bold with:
<span style="font-weight:bold">Your bold text</span>
This would go inside your <td>
tag.
Use JSON_UNESCAPED_UNICODE
inside json_encode()
if your php version >=5.4.
Enable NSZombieEnabled to know which object is being released and then accessed.
Then check if the getResultSetFromDB:
has anything to do with that. Also check if docids
has anything inside and if it is being retained.
This way you can be sure there is nothing wrong.
Integer.valueOf(android.os.Build.VERSION.SDK);
Values are:
Platform Version API Level
Android 9.0 28
Android 8.1 27
Android 8.0 26
Android 7.1 25
Android 7.0 24
Android 6.0 23
Android 5.1 22
Android 5.0 21
Android 4.4W 20
Android 4.4 19
Android 4.3 18
Android 4.2 17
Android 4.1 16
Android 4.0.3 15
Android 4.0 14
Android 3.2 13
Android 3.1 12
Android 3.0 11
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
CAUTION: don't use android.os.Build.VERSION.SDK_INT
if <uses-sdk android:minSdkVersion="3" />
.
You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT
is since SDK 4 (Donut 1.6).
To run Mocha with
mocha
command from your terminal you need to install mocha globally onthis
machine:
npm install --global mocha
Then cd
to your projectFolder/test and run mocha yourTestFileName.js
If you want to make
mocha
available inside yourpackage.json
as a development dependency:
npm install --save-dev mocha
Then add mocha
to your scripts inside package.json
.
"scripts": {
"test": "mocha"
},
Then run npm test
inside your terminal.
You can delete newlines with tr
:
var=`hg st -R "$path" | tr -d '\n'`
if [ -n $var ]; then
echo $var
done
After running configure, you can change the config option in the file Modules/Setup as below:
zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz
Or you can uncomment the zlib line as-is.
The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command)
is a modern synonym for `command`
which stands for command substitution; it means run command
and put its output here. So
echo "Today is $(date). A fine day."
will run the date
command and include its output in the argument to echo
. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).
By contrast, ${variable}
is just a disambiguation mechanism, so you can say ${var}text
when you mean the contents of the variable var
, followed by text
(as opposed to $vartext
which means the contents of the variable vartext
).
The while
loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for
loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.
A for
loop like that can be rephrased as a while
loop. The expression
for ((init; check; step)); do
body
done
is equivalent to
init
while check; do
body
step
done
It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for
loop does quite a bit more than the while
loop.
Of course, this syntax is Bash-specific; classic Bourne shell only has
for variable in token1 token2 ...; do
(Somewhat more elegantly, you could avoid the echo
in the first example as long as you are sure that your argument string doesn't contain any %
format codes:
date +'Today is %c. A fine day.'
Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)
Either you're not including jquery toolkit/lib, as some have suggested, or there is a conflict of sorts. To test: include jQuery and test like this:
console.log($);
console.log($ === jQuery);
If $
is not undefined, and $ === jQuery
logs false, you definitely have a conflict on your hands. Replacing your $
with jQuery
solves that, but that can be quite tedious (all that extra typing...). Generally I start my scripts with $jq = _$ = jQuery;
to at least have a shorter reference to the jQuery object.
Of course, before you do that, check to see if you're not accidentally overriding variables that have been set beforehand: console.log($jq, _jQ, _$);
whichever is not undefined
should be left alone, of course
In addition to Chris B's answer, if you need to use echo
anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>
's, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo
with parameters is more effective than concatenating.
This specific issue may arise in localhost also. We cannot rule out this is because network issue or internet connectivity issue. This issue will come even though all the database connection properties are correct.
I have faced the same issue when i have used host name. Instead use ip address. It will get resolved.
text.Trim() is to be used
string txt = " i am a string ";
txt = txt.Trim();
In the "Window" menu, open "Open Perspective" -> "Debug".
click On the plus image icon(you see the below image at status bar), and then select "Logcat"....
Select the project, then File > ProjectStructure > ProjectSettings > Modules -> sources You probably have the Language Level set at 9:
Just change it to 8 (or whatever you need) and you're set to go.
Also, check the same Language Level settings mentioned above, under Project Settings > Project
As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :
echo !empty($address['street2']) ?? 'Empty';
The InstallUtil.exe
tool is simply a wrapper around some reflection calls against the installer component(s) in your service. As such, it really doesn't do much but exercise the functionality these installer components provide. Marc Gravell's solution simply provides a means to do this from the command line so that you no longer have to rely on having InstallUtil.exe
on the target machine.
Here's my step-by-step that based on Marc Gravell's solution.
How to make a .NET Windows Service start right after the installation?
From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
Console.ReadKey();
}
}
public static class Tools
{
public static string ToUpperCase(string str)
{
return str.ToUpper();
}
}
}
static variable stored in data segment or code segment as mentioned before.
You can be sure that it will not be allocated on stack or heap.
There is no risk for collision since static
keyword define the scope of the variable to be a file or function, in case of collision there is a compiler/linker to warn you about.
A nice example
For this there are two cases
Case 1: File already added to git repo.
Case 2: File newly created and its status still showing as untracked file when using
git status
If you have case 1:
STEP 1: Then run
git rm --cached filename
to remove it from git repo cache
if it is a directory then use
git rm -r --cached directory_name
STEP 2: If Case 1 is over then create new file named .gitignore
in your git repo
STEP 3: Use following to tell git to ignore / assume file is unchanged
git update-index --assume-unchanged path/to/file.txt
STEP 4: Now, check status using git status open .gitignore
in your editor nano, vim, geany etc... any one, add the path of the file / folder to ignore. If it is a folder then user folder_name/*
to ignore all file.
If you still do not understand read the article git ignore file link.
I use TINYINT(1) in order to store boolean values in Mysql.
I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)
http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html
If all you are wanting is to show and hide say a div, then this code will let you use jQuery animate. You can have jQuery animate the majority of the height you wish or you can trick animate by animating to 0px. jQuery just needs a height set by jQuery to convert it to auto. So the .animate adds the style="" to the element that .css(height:auto) converts.
The cleanest way I have seen this work is to animate to around the height you expect, then let it set auto and it can look very seamless when done right. You can even animate past what you expect and it will snap back. Animating to 0px at a duration of 0 just simply drops the element height to its auto height. To the human eye, it looks animated anyway. Enjoy..
jQuery("div").animate({
height: "0px"/*or height of your choice*/
}, {
duration: 0,/*or speed of your choice*/
queue: false,
specialEasing: {
height: "easeInCirc"
},
complete: function() {
jQuery(this).css({height:"auto"});
}
});
Sorry I know this is an old post, but I felt this would be relevant to users seeking this functionality still with jQuery who come across this post.
On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases
If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.
And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.
I just had this problem and wrapping each cell with the CLEAN
function fixed it for me. That should be relatively easy to do by doing =CLEAN(
, selecting your cell, and then autofilling the rest of the column. After I did this, pastes into Notepad or any other program no longer had duplicate quotes.
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)
As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.
use below code. it will work fine for me.
+(void) sendHttpRequestWithArrayContent:(NSMutableArray *) array
ToUrl:(NSString *) strUrl withHttpMethod:(NSString *) strMethod
withBlock:(dictionary)block
{
if (![Utility isConnectionAvailableWithAlert:TRUE])
{
[Utility showAlertWithTitle:@"" andMessage:@"No internet connection available"];
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:strUrl]];
[request setTimeoutInterval:120.0];
[request setHTTPMethod:strMethod];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body=[[NSMutableData alloc]init];
for (NSMutableDictionary *dict in array)
{
if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSString class]])
{
[body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
}
else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[UIImage class]])
{
[body appendData:[self contentDataFormImage:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
}
else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSMutableDictionary class]])
{
[body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
}
else
{
NSMutableData *dataBody = [NSMutableData data];
[dataBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",@"image"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[dataBody appendData:[dict valueForKey:[[dict allKeys]objectAtIndex:0]]];
[body appendData:dataBody];
}
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!data) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@"%@",SomethingWentWrong] forKey:@"error"];
block(dict);
return ;
}
NSError *error = nil;
// NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",dict);
if (!dict) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(dict);
return ;
}
block(dict);
}];
}
+(NSMutableData*) contentDataFormStringWithValue:(NSString*)strValue
withKey:(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *data=[[NSMutableData alloc]init];
[data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"%@",strValue] dataUsingEncoding:NSUTF8StringEncoding]]; // title
return data;
}
+(NSMutableData*) contentDataFormImage:(UIImage*)image withKey:
(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData=UIImageJPEGRepresentation(image, 0.40);
[body appendData:imageData];
return body;
}
FatJar can help you in this case.
In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects
This is useful if your final exported jar includes other external jars.
If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.
After Ganymede, you have:
MySQL has started deprecating SQL_CALC_FOUND_ROWS
functionality with version 8.0.17 onwards.
So, it is always preferred to consider executing your query with LIMIT
, and then a second query with COUNT(*)
and without LIMIT
to determine whether there are additional rows.
From docs:
The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated as of MySQL 8.0.17 and will be removed in a future MySQL version.
COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS causes some optimizations to be disabled.
Use these queries instead:
SELECT * FROM tbl_name WHERE id > 100 LIMIT 10; SELECT COUNT(*) WHERE id > 100;
Also, SQL_CALC_FOUND_ROWS
has been observed to having more issues generally, as explained in the MySQL WL# 12615 :
SQL_CALC_FOUND_ROWS has a number of problems. First of all, it's slow. Frequently, it would be cheaper to run the query with LIMIT and then a separate SELECT COUNT() for the same query, since COUNT() can make use of optimizations that can't be done when searching for the entire result set (e.g. filesort can be skipped for COUNT(*), whereas with CALC_FOUND_ROWS, we must disable some filesort optimizations to guarantee the right result)
More importantly, it has very unclear semantics in a number of situations. In particular, when a query has multiple query blocks (e.g. with UNION), there's simply no way to calculate the number of “would-have-been” rows at the same time as producing a valid query. As the iterator executor is progressing towards these kinds of queries, it is genuinely difficult to try to retain the same semantics. Furthermore, if there are multiple LIMITs in the query (e.g. for derived tables), it's not necessarily clear to which of them SQL_CALC_FOUND_ROWS should refer to. Thus, such nontrivial queries will necessarily get different semantics in the iterator executor compared to what they had before.
Finally, most of the use cases where SQL_CALC_FOUND_ROWS would seem useful should simply be solved by other mechanisms than LIMIT/OFFSET. E.g., a phone book should be paginated by letter (both in terms of UX and in terms of index use), not by record number. Discussions are increasingly infinite-scroll ordered by date (again allowing index use), not by paginated by post number. And so on.
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
public static string Encryption(string strText)
{
var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
// client encrypting data with public key issued by server
rsa.FromXmlString(publicKey.ToString());
var encryptedData = rsa.Encrypt(testData, true);
var base64Encrypted = Convert.ToBase64String(encryptedData);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
public static string Decryption(string strText)
{
var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
var base64Encrypted = strText;
// server decrypting data with private key
rsa.FromXmlString(privateKey);
var resultBytes = Convert.FromBase64String(base64Encrypted);
var decryptedBytes = rsa.Decrypt(resultBytes, true);
var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
return decryptedData.ToString();
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
Use LEFT combined with CHARINDEX:
UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
Note that the WHERE clause skips updating rows in which there is no semicolon.
Here is some code to verify the SQL above works:
declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself
UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
select * from @MyTable
I get the following results:
id MyText
-- -------------------------
1 some text
2 text again
3 text without a semicolon
4 NULL
5 (empty string)
6 test 3 semicolons
7 (empty string)
Because $newDate
is an object of type DateTime
, not a string. The documentation is explicit:
Returns new
DateTime
object formatted according to the specified format.
If you want to convert from a string to DateTime
back to string to change the format, call DateTime::format
at the end to get a formatted string out of your DateTime
.
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example
For those using jQuery there's a convenient method: http://api.jquery.com/change/
Right click on any word and select 'Find Selected Text in API Reference' to search the API for that word. This is very helpful if you need to look up the available properties and/or methods for a class. Instead of heading to Apple.com or Google you will get a popup window of what you were looking for (or what was found).
Use a iterator to loop through list and then delete the required object.
Iterator itr = a.iterator();
while(itr.hasNext()){
if(itr.next().equals("acbd"))
itr.remove();
}
BigDecimal
, not double
The Answer by adatapost is right about using String::split
but wrong about using double
to represent your longitude-latitude values. The float
/Float
and double
/Double
types use floating-point technology which trades away accuracy for speed of execution.
Instead use BigDecimal
to correctly represent your lat-long values.
Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.
Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split
for the writing. And the app uses BigDecimal
objects to represent your lat-long values.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class LatLong
{
//----------| Write |-----------------------------
public void write ( final Path path )
{
List < String > inputs =
List.of(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
// Use try-with-resources syntax to auto-close the `CSVPrinter`.
try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
{
for ( String input : inputs )
{
String[] fields = input.split( "," );
printer.printRecord( fields[ 0 ] , fields[ 1 ] );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Read |-----------------------------
public void read ( Path path )
{
// TODO: Add a check for valid file existing.
try
{
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records )
{
BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
System.out.println( "lat: " + latitude + " | long: " + longitude );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Main |-----------------------------
public static void main ( String[] args )
{
LatLong app = new LatLong();
// Write
Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.write( pathOutput );
System.out.println( "Writing file: " + pathOutput );
// Read
Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.read( pathInput );
System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
}
}
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
Now all clients allow to do it, but it's not pretty simple.
In any Telegram client:
Administrators
If you are using BookId as an combined primary key, then remember to change your interface from:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
to:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:
public class QueuedBook implements Serializable {
@EmbeddedId
@NotNull
private BookId bookId;
...
Edit: As pointed out in comments (Mario Awad & Brock Hensley), use .find
to get the children
$("form").each(function(){
$(this).find(':input') //<-- Should return all input elements in that specific form.
});
forms also have an elements collection, sometimes this differs from children such as when the form tag is in a table and is not closed.
var summary = [];_x000D_
$('form').each(function () {_x000D_
summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');_x000D_
summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');_x000D_
});_x000D_
_x000D_
$('#results').html(summary.join('<br />'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form id="A" style="display: none;">_x000D_
<input type="text" />_x000D_
<button>Submit</button>_x000D_
</form>_x000D_
<form id="B" style="display: none;">_x000D_
<select><option>A</option></select>_x000D_
<button>Submit</button>_x000D_
</form>_x000D_
_x000D_
<table bgcolor="white" cellpadding="12" border="1" style="display: none;">_x000D_
<tr><td colspan="2"><center><h1><i><b>Login_x000D_
Area</b></i></h1></center></td></tr>_x000D_
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input_x000D_
name="id" type="text"></td></tr>_x000D_
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"_x000D_
type="password"></td></tr>_x000D_
<tr><td><center><input type="button" value="Login"_x000D_
onClick="pasuser(this.form)"></center></td><td><center><br /><input_x000D_
type="Reset"></form></td></tr></table></center>_x000D_
<div id="results"></div>
_x000D_
May be :input selector is what you want
$("form").each(function(){
$(':input', this)//<-- Should return all input elements in that specific form.
});
As pointed out in docs
To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").
You can use like below,
$("form").each(function(){
$(this).filter(':input') //<-- Should return all input elements in that specific form.
});
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
Use :
gem sources --add http://rubygems.org/
Do you want to add this insecure source? [yn] [YES]
then use
gem install sass
and done
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT
to tell your web server what port to listen on.
So process.env.PORT || 3000
means: whatever is in the environment variable PORT, or 3000 if there's nothing there.
So you pass that to app.listen
, or to app.set('port', ...)
, and that makes your server able to accept a "what port to listen on" parameter from the environment.
If you pass 3000
hard-coded to app.listen()
, you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.
Across all browsers and simple. this did it for me
$(function () {_x000D_
$('input[type="file"]').change(function () {_x000D_
if ($(this).val() != "") {_x000D_
$(this).css('color', '#333');_x000D_
}else{_x000D_
$(this).css('color', 'transparent');_x000D_
}_x000D_
});_x000D_
})
_x000D_
input[type="file"]{_x000D_
color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" name="app_cvupload" class="fullwidth input rqd">
_x000D_
If you need the date part just for echoing purpose, then
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
this might help someone who had similar issue like me , i followed all naming and interface standards., But i was still facing issue.
My param name was --> update_datetime
I wanted to fetch my entities based on the update_datetime in the descending order, and i was getting the error
org.springframework.data.mapping.PropertyReferenceException: No property update found for type Release!
Somehow it was not reading the Underscore character --> ( _ )
so for workaround i changed the property name as --> updateDatetime
and then used the same for using JpaRepository methods.
It Worked !
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says
moment().valueOf()
or
+moment();
you can also get it through moment().format('x')
(or .format('X')
[capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.
Sometimes learning by example helps the most. Run this console application in three different console windows. You'll see that the application you ran first acquires the mutex first, while the other two are waiting their turn. Then press enter in the first application, you'll see that application 2 now continues running by acquiring the mutex, however application 3 is waiting its turn. After you press enter in application 2 you'll see that application 3 continues. This illustrates the concept of a mutex protecting a section of code to be executed only by one thread (in this case a process) like writing to a file as an example.
using System;
using System.Threading;
namespace MutexExample
{
class Program
{
static Mutex m = new Mutex(false, "myMutex");//create a new NAMED mutex, DO NOT OWN IT
static void Main(string[] args)
{
Console.WriteLine("Waiting to acquire Mutex");
m.WaitOne(); //ask to own the mutex, you'll be queued until it is released
Console.WriteLine("Mutex acquired.\nPress enter to release Mutex");
Console.ReadLine();
m.ReleaseMutex();//release the mutex so other processes can use it
}
}
}
Maybe .value_counts()
?
>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0 1
1 2
2 2
3 3
4 3
5 3
6 fred
7 1.8
8 1.8
>>> counts = my_series.value_counts()
>>> counts
3 3
2 2
1.8 2
fred 1
1 1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
Install:
pip install twisted
Then the code:
from twisted.protocols.ftp import FTPFactory, FTPRealm
from twisted.cred.portal import Portal
from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB
from twisted.internet import reactor
reactor.listenTCP(21, FTPFactory(Portal(FTPRealm('./'), [AllowAnonymousAccess()])))
reactor.run()
Get deeper:
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
If anyone is looking at how to do this in .net core I accomplished it by adding the controller in startup
services.AddTransient<MyControllerIwantToInject>();
Then Injecting it into the other controller
public class controllerBeingInjectedInto : ControllerBase
{
private readonly MyControllerIwantToInject _myControllerIwantToInject
public controllerBeingInjectedInto(MyControllerIwantToInject myControllerIwantToInject)
{
_myControllerIwantToInject = myControllerIwantToInject;
}
Then just call it like so _myControllerIwantToInject.MyMethodINeed();
In my case i had no problem at all, just forgot to start the mysql service...
sudo service mysqld start
~ specfices to minor version releases ^ specifies to major version releases
For example if package version is 4.5.2 ,on Update ~4.5.2 will install latest 4.5.x version (MINOR VERSION) ^4.5.2 will install latest 4.x.x version (MAJOR VERSION)
I needed to add a ParsePosition
expression to the parse method of class SimpleDateFormat
:
simpledateformat.parse(mydatestring, new ParsePosition(0));
If one want to attach a process, this process must have the same owner. The root is able to attach to any process.
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
It's very similar to
char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};
but gives you read-only memory.
For a discussion of the difference between a char[]
and a char *
, see comp.lang.c FAQ 1.32.
map is associative container. Hence, iterator is a pair of key,val. IF you need only keys, you can ignore the value part from the pair.
for(std::map<Key,Val>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
{
Key k = iter->first;
//ignore value
//Value v = iter->second;
}
EDIT:: In case you want to expose only the keys to outside then you can convert the map to vector or keys and expose.
(March 2012)
Beware: that default "matching
" policy might change soon
(sometimes after git1.7.10+):
See "Please discuss: what "git push" should do when you do not say what to push?"
In the current setting (i.e.
push.default=matching
),git push
without argument will push all branches that exist locally and remotely with the same name.
This is usually appropriate when a developer pushes to his own public repository, but may be confusing if not dangerous when using a shared repository.The proposal is to change the default to '
upstream
', i.e. push only the current branch, and push it to the branch git pull would pull from.
Another candidate is 'current
'; this pushes only the current branch to the remote branch of the same name.What has been discussed so far can be seen in this thread:
http://thread.gmane.org/gmane.comp.version-control.git/192547/focus=192694
Previous relevant discussions include:
To join the discussion, send your messages to: [email protected]
There is an interesting port of NetworkX to Javascript that might do what you want. See http://felix-kling.de/JSNetworkX/
mysql-python
NOT support Python3, you may need:
sudo pip3 install mysqlclient
Also, check this post for more alternatives.
If the column is of type char
then you need to append the value you are querying with spaces, please refer to this question here . This in addition to using COLLATE NOCASE
or one of the other solutions (upper(), etc).
You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial
You can disable/enable pagers for specific outputs in the global configuration as well:
git config --global pager.diff false
Or to set the core.pager option, just provide an empty string:
git config --global core.pager ''
This is better in my opinion than setting it to cat
as you say.
I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.
At first I just used a boolean var and IF statement:
Dim i as integer, bol as boolean
If bol = false then
i = ValueIWantToAssign
bol = True
End If
In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.
Like so:
Dim i as integer
ForLoopStart
If ConditionIsMet Then
i = ValueIWantToAssign
Exit For
End If
ForLoopEnd
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.map((myArr, index) => {
console.log(`your index is -> ${index} AND value is ${myArr}`);
})
_x000D_
> output will be
index is -> 0 AND value is 1
index is -> 1 AND value is 2
index is -> 2 AND value is 3
index is -> 3 AND value is 4
index is -> 4 AND value is 5
index is -> 5 AND value is 6
index is -> 6 AND value is 7
index is -> 7 AND value is 8
index is -> 8 AND value is 9
Another tricky solution is to name elements of list and attach
it:
list_name = list(
head(iris),
head(swiss),
head(airquality)
)
names(list_name) <- paste("orca", seq_along(list_name), sep="")
attach(list_name)
orca1
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
What's not mentioned here is that option 1 allows you arbitrarily deep nesting of lists.
This shouldn't matter if you control the content/css, but if you're making a rich text editor it comes in handy.
For example, gmail, inbox, and evernote all allow creating lists like this:
With option 2 you cannot due that (you'll have an extra list item), with option 1, you can.
the articles posted by Ricky are very good, but unfortunately they don't answer your question.
To solve your problem you should try this piece of code:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
If need to access a value within the config you can use the index operator:
config.AppSettings.Settings["test"].Value;
Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like
template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64
If you are using Python2.5 or older try
from operator import mul
def factorial(n):
return reduce(mul, range(1,n+1))
for newer Python, there is factorial in the math module as given in other answers here
No promises are just wrapper on callbacks
example You can use javascript native promises with node js
my cloud 9 code link : https://ide.c9.io/adx2803/native-promises-in-node
/**
* Created by dixit-lab on 20/6/16.
*/
var express = require('express');
var request = require('request'); //Simplified HTTP request client.
var app = express();
function promisify(url) {
return new Promise(function (resolve, reject) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
}
else {
reject(error);
}
})
});
}
//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
//get the post with post id 100
promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
var obj = JSON.parse(result);
return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
})
.catch(function (e) {
console.log(e);
})
.then(function (result) {
res.end(result);
}
)
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
//run webservice on browser : http://localhost:8081/listAlbums
There are two types of messages in FCM (Firebase Cloud Messaging):
onMessageReceived()
callback only when your app is in foregroundonMessageReceived()
callback even if your app is in foreground/background/killedNOTE: Firebase team have not developed a UI to send
data-messages
to your devices, yet. You should use your server for sending this type!
To achieve this, you have to perform a POST
request to the following URL:
Content-Type
, Value: application/json
Authorization
, Value: key=<your-server-key>
{
"to": "/topics/my_topic",
"data": {
"my_custom_key": "my_custom_value",
"my_custom_key2": true
}
}
{
"data": {
"my_custom_key": "my_custom_value",
"my_custom_key2": true
},
"registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
}
NOTE: Be sure you're not adding JSON key
notification
NOTE: To get your server key, you can find it in the firebase console:Your project -> settings -> Project settings -> Cloud messaging -> Server Key
This is how you handle the received message:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String myCustomKey = data.get("my_custom_key");
// Manage data
}
Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/
Well, you can stick one or more "soft hyphens" (­
) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.
Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Simple really create a long variable that represents a default start date for your program Get the date to another long variable. Then deduct the long start date and convert to a integer voila To read and convert back just add rather than subtract. obviously this is dependant on how large a date range you require.
Use VBA's already existing Join
function. VBA functions aren't exposed in Excel, so I wrap Join
in a user-defined function that exposes its functionality. The simplest form is:
Function JoinXL(arr As Variant, Optional delimiter As String = " ")
'arr must be a one-dimensional array.
JoinXL = Join(arr, delimiter)
End Function
Example usage:
=JoinXL(TRANSPOSE(A1:A4)," ")
entered as an array formula (using Ctrl-Shift-Enter).
Now, JoinXL
accepts only one-dimensional arrays as input. In Excel, ranges return two-dimensional arrays. In the above example, TRANSPOSE
converts the 4×1 two-dimensional array into a 4-element one-dimensional array (this is the documented behaviour of TRANSPOSE
when it is fed with a single-column two-dimensional array).
For a horizontal range, you would have to do a double TRANSPOSE
:
=JoinXL(TRANSPOSE(TRANSPOSE(A1:D1)))
The inner TRANSPOSE
converts the 1×4 two-dimensional array into a 4×1 two-dimensional array, which the outer TRANSPOSE
then converts into the expected 4-element one-dimensional array.
This usage of TRANSPOSE
is a well-known way of converting 2D arrays into 1D arrays in Excel, but it looks terrible. A more elegant solution would be to hide this away in the JoinXL
VBA function.
CREATE TABLE Employees
(
Id int,
Name varchar(50) not null,
Photo varbinary(max) not null
)
INSERT INTO Employees (Id, Name, Photo)
SELECT 10, 'John', BulkColumn
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture
An even simpler one liner. No lambda expressions or curly braces required for this example using Java 8 and JUnit 5
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
assertThrows(MyException.class, myStackObject::doStackAction, "custom message if assertion fails...");
// note, no parenthesis on doStackAction ex ::pop NOT ::pop()
}
Supplementary for option 4 by @fenton, using angularJS it is rather simple to do a deep copy of either an object or array using the following code:
var deepCopy = angular.copy(objectOrArrayToBeCopied)
More documentation can be found here: https://docs.angularjs.org/api/ng/function/angular.copy
From zip(1):
When given the name of an existing zip archive, zip will replace identically named entries in the zip archive or add entries for new names.
So just use the zip
command as you normally would to create a new .zip file containing only that one file, except the .zip filename you specify will be the existing archive.
CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.
This works fine in all newer browsers:
#container {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background-color: #cccccc;_x000D_
margin: 10px; _x000D_
}
_x000D_
<div id="container">_x000D_
<div class="block">1</div> _x000D_
<div class="block">2</div> _x000D_
<div class="block">3</div> _x000D_
<div class="block">4</div> _x000D_
<div class="block">5</div> _x000D_
</div>
_x000D_
Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.
@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"
I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally
GetFiles done 437834 in00:00:20.4812480
process files done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2) done 437834 in00:00:20.7412646
If you're just looking for a more concise syntax you can put the for loop on one line:
array = ['a', 'b']
for value in array: print(value)
Just separate additional statements with a semicolon.
array = ['a', 'b']
for value in array: print(value); print('hello')
This may not conform to your local style guide, but it could make sense to do it like this when you're playing around in the console.
As already said, your socket probably enter in TIME_WAIT
state. This issue is well described by Thomas A. Fine here.
To summary, socket closing process follow diagram below:
Thomas says:
Looking at the diagram above, it is clear that
TIME_WAIT
can be avoided if the remote end initiates the closure. So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.
Using SO_REUSEADDR
is commonly suggested on internet, but Thomas add:
Oddly, using
SO_REUSEADDR
can actually lead to more difficult "address already in use" errors.SO_REUSADDR
permits you to use a port that is stuck inTIME_WAIT
, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port inTIME_WAIT
. I can reuse local port 1010 right away to connect to anywhere except forfoobar.com
port 300.
I think the only way is by using internel PHP code like MANOJ and Fernando suggest.
curl post/get in php file on your server --> call this php file with ajax
The PHP file let say (fb.php):
$commentdata=$_GET['commentdata'];
$fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,
"message=".$commentdata);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
Than use AJAX GET to
fb.php?commentmeta=your comment goes here
from your server.
Or do this with simple HTML and JavaScript from externel server:
Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
<script>
function PostMessage() {
var comment = document.getElementById('message').value;
window.location.assign('http://yourdomain.tld/fb.php?commentmeta='+comment)
}
</script>
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
In general .Net collections do not support being enumerated and modified at the same time. If you try to modify the collection list during enumeration, it raises an exception. So the issue behind this error is, we can not modify the list/dictionary while we are looping through the same.
If we iterate a dictionary using a list of its keys, in parallel we can modify the dictionary object, as we are iterating through the key-collection and not the dictionary(and iterating its key collection).
//get key collection from dictionary into a list to loop through
List<int> keys = new List<int>(Dictionary.Keys);
// iterating key collection using a simple for-each loop
foreach (int key in keys)
{
// Now we can perform any modification with values of the dictionary.
Dictionary[key] = Dictionary[key] - 1;
}
Here is a blog post about this solution.
And for a deep dive in StackOverflow: Why this error occurs?
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
iText has more than one way of doing this. The PdfStamper
class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.
// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1);
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp"));
document.close();
This will read in a PDF from templateInputStream
and write it out to outputStream
. These might be file streams or memory streams or whatever suits your application.
You could use hashname.key(valuename)
Or, an inversion may be in order. new_hash = hashname.invert
will give you a new_hash
that lets you do things more traditionally.
Like it was saying previously - you can access any parameters by using injection container and use its parameter property.
"Symfony - Working with Container Service Definitions" is a good article about it.
Environment.getExternalStorageDirectory()
will NOT return path to micro SD card Storage.
how to get file path from sd card in android
By sd card, I am assuming that, you meant removable micro SD card.
In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type)
in Context
Class that allows apps to store data/files in micro SD cards.
Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.
Environment.getExternalStorageDirectory()
was there from API level 1
getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).
But note that,
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using
getExternalStorageState(File)
.There is no security enforced with these files. For example, any application holding
WRITE_EXTERNAL_STORAGE
can write to these files.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
The new Mavericks (10.9) showed me the "Requesting install", but nothing happened.
The solution was to manually download and install the official Java package for OS X, which is in Java for OS X 2013-005.
Update: As mentioned in the comments below, there is a newer version of this same package:
Java for OS X 2014-001 (Correcting dead line above)
Java for OS X 2014-001 includes installation improvements, and supersedes all previous versions of Java for OS X. This package installs the same version of Java 6 included in Java for OS X 2013-005.
You might be in formula view:
Hit Ctrl + ` to switch
You can follow uploaded images
Then select which database you want to delete
Use COALESCE. Instead of your_column
use COALESCE(your_column, '')
. This will return the empty string instead of NULL.
In Opera 9.62, Mozilla 3.0.4, Safari 3.2 (for Windows) it helps, if you put some text or at least a whitespace within the same line as the input field.
<div style="line-height: 60px; height: 60px; border: 1px solid black;">
<input type="text" value="foo" />
</div>
(imagine an   after the input-statement)
IE 7 ignores every CSS hack I tried. I would recommend using padding for IE only. Should make it easier for you to position it correctly if it only has to work within one specific browser.
You should have if row[2] != "0"
. Otherwise it's not checking to see if the string value is equal to 0.
matches();
does not buffer, but find()
buffers. find()
searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.
That is why when you have a code like
1:Pattern.compile("[a-z]");
2:Pattern.matcher("0a1b1c3d4");
3:int count = 0;
4:while(matcher.find()){
5:count++: }
At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character]
to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches()
; does not. The while statement would never execute since the first character of the matched string is not an alphabet.
if you are cloning the same repository, then run the following snippet through the existing repository
git pull origin master
If you want to ignore multiple API endpoints you can use as follow:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.antMatchers("api/v1/authenticate**").permitAll()
.antMatchers("**").permitAll()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that. I used a string as output, as implode can't add new line (new line is something I added, and should really be there).
Please note, this only works with single value arrays (key, value)
. but could easily be updated to handle multi-dimensional (key, array())
.
function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = '';
foreach ( $fields as $key => $field ) {
if ($field === null && $nullToMysqlNull) {
$output = '';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output .= $key;
$output .= $delimiter;
$output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
$output .= PHP_EOL;
}
else {
$output .= $key;
$output .= $delimiter;
$output .= $field;
$output .= PHP_EOL;
}
}
return $output ;
}