Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.
But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.
The Path class is very useful here.
You get two methods called
that could solve your issue
So for example you could write: (if you don't mind the exact file name)
using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
{
sw.WriteLine("Your error message");
}
Or if you need to set your file name
string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
using(StreamWriter sw = new StreamWriter(myTempFile))
{
sw.WriteLine("Your error message");
}
The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.
Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.
you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense you can do it like this
for (var i = 0; i < rows - 1; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i].push(0);
}
}
for (var i = r; i < rows - 1; i++)
{
for (var j = 0; j < cols; j++)
{
col.push(0);
}
}
you can also combine the two loops using an if condition, if row < r, else if row >= r
This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer
element in my case didn't show. I added a position: relative
which worked.
To the people complaining about the noise when doing git diff:
git diff -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'
What I did was use an alias:
alias gd="git diff --ignore-all-space --ignore-space-at-eol --ignore-space-change --ignore-blank-lines -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'"
To ignore package-lock.json in diffs for the entire repository (everyone using it), you can add this to .gitattributes
:
package-lock.json binary
yarn.lock binary
This will result in diffs that show "Binary files a/package-lock.json and b/package-lock.json differ whenever the package lock file was changed. Additionally, some Git services (notably GitLab, but not GitHub) will also exclude these files (no more 10k lines changed!) from the diffs when viewing online when doing this.
In vscode select folder and create WS and it will work fine
Trying http://0.0.0.0:3000/routes
on a Rails 5 API app (i.e.: JSON-only oriented) will (as of Rails beta 3) return
{"status":404,"error":"Not Found","exception":"#>
<ActionController::RoutingError:...
However, http://0.0.0.0:3000/rails/info/routes
will render a nice, simple HTML page with routes.
If the server only supports higher TLS version like TLS 1.2 only, it will still fail unless your client PC is configured to use higher TLS version by default. To overcome this problem add the following in your code.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Modifying your example code, it would be
HttpClient httpClient = new HttpClient();
//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
httpClient.BaseAddress = new Uri("https://foobar.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var task = httpClient.PostAsXmlAsync<DeviceRequest>("api/SaveData", request);
Try: "\r\n"
Java 7 example:
// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true)))
{
output.printf("%s\r\n", "NEWLINE");
}
catch (Exception e) {}
it worked for me
$(document).scroll(function() {
var y = $(document).scrollTop(), //get page y value
header = $("#myarea"); // your div id
if(y >= 400) {
header.css({position: "fixed", "top" : "0", "left" : "0"});
} else {
header.css("position", "static");
}
});
slice does not change original array it return new array but splice changes the original array.
example: var arr = [1,2,3,4,5,6,7,8];
arr.slice(1,3); // output [2,3] and original array remain same.
arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].
splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.
arr.splice(-3,-1); // output [] second argument value should be greater then
0.
arr.splice(-3,-1); // output [6,7] index in minus represent start from last.
-1 represent last element so it start from -3 to -1. Above are major difference between splice and slice method.
Help from @phil-frost was very helpful, was exactly what I was looking for.
I have made few tweaks after that so I'm would like to share it here:
def csv_as_dict(file, ref_header, delimiter=None):
import csv
if not delimiter:
delimiter = ';'
reader = csv.DictReader(open(file), delimiter=delimiter)
result = {}
for row in reader:
print(row)
key = row.pop(ref_header)
if key in result:
# implement your duplicate row handling here
pass
result[key] = row
return result
You can call it:
myvar = csv_as_dict(csv_file, 'ref_column')
Where ref_colum will be your main key for each row.
It depends whether you ListBox object of the System.Windows.Forms.ListBox
class, which does have the ListBox.IndexFromPoint()
method. But if the ListBox object is from the System.Windows.Control.Listbox
class, the answer from @dark-knight (marked as correct answer) does not work.
Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form
Suppose you have this function:
var Foo = function(){
this.A = 1;
this.B = 2;
};
If you call this as a standalone function like so:
Foo();
Executing this function will add two properties to the window
object (A
and B
). It adds it to the window
because window
is the object that called the function when you execute it like that, and this
in a function is the object that called the function. In Javascript at least.
Now, call it like this with new
:
var bar = new Foo();
What happens when you add new
to a function call is that a new object is created (just var bar = new Object()
) and that the this
within the function points to the new Object
you just created, instead of to the object that called the function. So bar
is now an object with the properties A
and B
. Any function can be a constructor, it just doesn't always make sense.
If you know you don't have any whitespace in the input:
xargs chmod 755 < file.txt
If there might be whitespace in the paths, and if you have GNU xargs:
tr '\n' '\0' < file.txt | xargs -0 chmod 755
I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.
1) Reference data in Vue Instance as an external object (data : dataObj)
2) Then in the data return function in the child component just return parentScope = dataObj
and voila. Now you cann do things like {{ parentScope.prop }}
and will work like a charm.
Good Luck!
Every time I refactor a view controller's name that's in my appDelegate I waste time on this. Refactoring doesn't change the nib name in initWithNibName:@"MYOldViewControllerName".
You want sys.exit()
. From Python's docs:
>>> import sys
>>> print sys.exit.__doc__
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
So, basically, you'll do something like this:
from sys import exit
# Code!
exit(0) # Successful exit
You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :
dbms_lob.substr(clob_value_column,4000,1)
Otherwise you will find ORA-22835 (buffer too small)
You can also use the other sql way :
SELECT * FROM your_table WHERE clob_value_column LIKE '%your string%';
Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:
https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html
use contentDocument
to achieve this
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
var ulObj = innerDoc.getElementById("ID_TO_SEARCH");
Newline inside a value seems to work if you use semicolon as separator, instead of comma or tab, and use quotes.
This works for me in both Excel 2010 and Excel 2000. However, surprisingly, it works only when you open the file as a new spreadsheet, not when you import it into an existing spreadsheet using the data import feature.
What everyone suggesting you to use _ isn't saying is that _ is frequently used as a shortcut to one of the gettext functions, so if you want your software to be available in more than one language then you're best off avoiding using it for other purposes.
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
echo STR is empty but should have a value.
fi
Create a cronjob like this to work on every minute
* * * * * /usr/bin/php path/to/cron.php &> /dev/null
Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)
But I would also suggest adding the DATEPART ( hour, insertDate) column for debug
SELECT idCustomer FROM reservations
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2
You can also generate source code from schema using jaxb2-maven-plugin plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/resources/your_schema.xsd</source>
</sources>
<xjbSources>
<xjbSource>src/main/resources/bindings.xjb</xjbSource>
</xjbSources>
<packageName>some_package</packageName>
<outputDirectory>src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
<generateEpisode>false</generateEpisode>
<noGeneratedHeaderComments>true</noGeneratedHeaderComments>
</configuration>
</plugin>
I assume the original question included how does Express use this environment variable.
Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error
, to avoid leaking implementation details to the world.
Simply said, if an image is a class, then a container is an instance of a class is a runtime object.
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
That is a binary operator in hibernate you should use
is not null
Have a look at 14.10. Expressions
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
This is just an indentation problem since Python is very strict when it comes to it.
If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.
If you have integer division of positive numbers which rounds toward zero, then you can add one less than the divisor to the dividend to make it round up.
That is to say, replace X / Y
with (X + Y - 1) / Y
.
Proof:
Case 1: X = k * Y
(X is integer multiple of Y): In this case, we have (k * Y + Y - 1) / Y
, which splits into (k * Y) / Y + (Y - 1) / Y
. The (Y - 1)/Y
part rounds to zero, and we are left with a quotient of k
. This is exactly what we want: when the inputs are divisible, we want the adjusted calculation to still produce the correct exact quotient.
Case 2: X = k * Y + m
where 0 < m < Y
(X is not a multiple of Y). In this case we have a numerator of k * Y + m + Y - 1
, or k * Y + Y + m - 1
, and we can write the division out as (k * Y)/Y + Y/Y + (m - 1)/Y
. Since 0 < m < Y
, 0 <= m - 1 < Y - 1
, and so the last term (m - 1)/Y
goes to zero. We are left with (k * Y)/Y + Y/Y
which work out to k + 1
. This shows that the behavior rounds up. If we have an X
which is a k
multiple of Y
, if we add just 1 to it, the division rounds up to k + 1
.
But this rounding is extremely opposite; all inexact divisions go away from zero. How about something in between?
That can be achieved by "priming" the numerator with Y/2
. Instead of X/Y
, calculate (X+Y/2)/Y
. Instead of proof, let's go empirical on this one:
$ round()
> {
> echo $((($1 + $2/2) / $2))
> }
$ round 4 10
0
$ round 5 10
1
$ round 6 10
1
$ round 9 10
1
$ round 10 10
1
$ round 14 10
1
$ round 15 10
2
Whenever the divisor is an even, positive number, if the numerator is congruent to half that number, it rounds up, and rounds down if it is one less than that.
For instance, round 6 12
goes to 1
, as do all values which are equal to 6
, modulo 12
, like 18
(which goes to 2) and so on. round 5 12
goes down to 0
.
For odd numbers, the behavior is correct. None of the exact rational numbers are midway between two consecutive multiples. For instance, with a denominator of 11
we have 5/11 < 5.5/11 (exact middle) < 6/11
; and round 5 11
rounds down, whereas round 6 11
rounds up.
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Such things are best answered by looking at the official specification:
go to the specification: https://www.w3.org/TR/html5/
search for "a
element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element
check "Content attributes", which lists all allowed attributes for the a
element:
- Global attributes
href
target
download
rel
hreflang
type
check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes
As you will see, the alt
attribute is not allowed on the a
element.
Also you’d notice that the src
attribute isn’t allowed either.
By validating your HTML, errors like these are reported to you.
Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a
element can have another attribute in HTML 5.1: rev
.
You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.
strncpy(otherString, someString, 5);
Don't forget to allocate memory for otherString.
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Go to Order and export from project properties and make sure you're including the required jars in the export, this did it for me
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
With SplFileInfo:
SplFileInfo The SplFileInfo class offers a high-level object oriented interface to information for an individual file.
Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
o/p: string(7) "foo.txt"
out
specifies that the parameter is an output parameters, i.e. it has no value until it is explicitly set by the method.
ref
specifies that the value is a reference that has a value, and whose value you can change inside the method.
According to this thread:
The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.
Parse the string into an integer using parseInt
:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Just append word native to your HADOOP_OPTS
like this:
export HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=$HADOOP_HOME/lib/native"
PS: Thank Searene
I wonder why no one added the alternative of using the function chr()
:
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
why not use good old PHP? for example, let us say we receive a GET parameter 'target':
function getTarget() {
var targetParam = "<?php echo $_GET['target']; ?>";
//alert(targetParam);
}
There are several Identity providers with SSO support out of the box, also third-party** products.
** The only problem with third party products is that they charge per user/month, and it can be quite expensive.
Some of the tools available and with APIs for .NET are:
If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.
C#
Javascript
Python
I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.
Decorate Components with the JLayer Class:
The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.
Strings in switch Statement:
In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Type Inference for Generic Instance:
We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());
In comparison, the following example compiles:
List<? extends String> list2 = new ArrayList<>();
l.addAll(list2);
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:
catch (IOException e) {
logger.log(e);
throw e;
}
catch (SQLException e) {
logger.log(e);
throw e;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException e) {
logger.log(e);
throw e;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
The java.nio.file package
The java.nio.file
package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.
Old question, but in my case i found using position:fixed
solved it for me.
My situation might have been a little different though. I had an overlayed semi transparent div
with a loading animation in it that I needed displayed while the page was loading. So using height:auto / 100%
or min-height: 100%
both filled the window but not the off-screen area. Using position:fixed
made this overlay scroll with the user, so it always covered the visible area and kept my preloading animation centred on the screen.
You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.
<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>
Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.
If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec()
approach. Here is a simple example:
<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql =
"SELECT AgentName FROM Agents " .
"WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);
// query parameter value(s)
$params = array(
5,
'Homer'
);
$sth->execute($params);
while ($row = $sth->fetch()) {
echo $row['AgentName'] . "\r\n";
}
NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF
. If you do need to support such characters then neither PDO_ODBC
nor the old odbc_
functions will work; you'll need to use the solution described in this answer.
What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.
If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.
I had this issue today, and for me the problem was that I had allocated too much memory:
-Xmx1024M -XX:MaxPermSize=1024m
Once I reduced the PermGen space, everything worked fine:
-Xmx1024M -XX:MaxPermSize=512m
I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.
Try this:
(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-3)
}).Count
If you know the string will be either "True"
or "False"
, you could just use eval(s)
.
>>> eval("True")
True
>>> eval("False")
False
Only use this if you are sure of the contents of the string though, as it will throw an exception if the string does not contain valid Python, and will also execute code contained in the string.
XCODE 10.1 / SWIFT 4.2 :
Add required permissions (others mentioned)
Add this class to your view:
import UIKit
import Photos
import Foundation
class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate {
@IBOutlet weak var imgView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
checkPermission()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
}
@IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) {
}
@IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) {
self.selectPhotoFromGallery()
}
func selectPhotoFromGallery() {
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imgView.contentMode = .scaleAspectFit
self.imgView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
print("cancel is clicked")
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
print("Access is granted by user")
case .notDetermined:
PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized {
/* do stuff here */
print("success")
}
})
print("It is not determined until now")
case .restricted:
// same same
print("User do not have access to photo album.")
case .denied:
// same same
print("User has denied the permission.")
}
}
}
In my scenario this was happening because I renamed a parameter in swagger.yaml
but did not reload the docs page.
Hence I was trying the API with an unexpected input parameter.
Long story short, F5 is my friend.
Don't use device-width/height anymore.
device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features
Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.
I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.
sudo apt-get install ia32-libs
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
IF...ELSE IF
constructs work very well in batch files, in particular when you use only one conditional expression on each IF line:
IF %F%==1 (
::copying the file c to d
copy "%sourceFile%1" "%destinationFile1%"
) ELSE IF %F%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%" )
In your example you use IF...AND...IF
type construct, where 2 conditions must be met simultaneously. In this case you can still use IF...ELSE IF
construct, but with extra parentheses to avoid uncertainty for the next ELSE condition:
IF %F%==1 (IF %C%==1 (
::copying the file c to d
copy "%sourceFile1%" "%destinationFile1%" )
) ELSE IF %F%==1 (IF %C%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%"))
The above construct is equivalent to:
IF %F%==1 (
IF %C%==1 (
::copying the file c to d
copy "%sourceFile1%" "%destinationFile1%"
) ELSE IF %C%==0 (
::moving the file e to f
move "%sourceFile2%" "%destinationFile2%"))
Processing sequence of batch commands depends on CMD.exe parsing order. Just make sure your construct follows that logical order, and as a rule it will work. If your batch script is processed by Cmd.exe without errors, it means this is the correct (i.e. supported by your OS Cmd.exe version) construct, even if someone said otherwise.
Changing the minSdkVersion in the manifest is not necessary. If you change it in the gradle build file, as seen below, you accomplish what you need to do.
defaultConfig {
applicationId "com.demo.myanswer"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
Many of the Python directory functions are in the os.path
module.
import os
os.path.isdir(d)
It's not possible using CSS, but using a CSS preprocessor like less or SASS.
If all of that did not work try this.
with open("hello.txt") as f:
with open("copy.txt", "w") as f1:
for line in f:
f1.write(line)
For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess
<IfModule php5_module>
php_flag session.cookie_httponly on
</IfModule>
This can also be set within a script, as long as it is called before session_start()
.
ini_set( 'session.cookie_httponly', 1 );
The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.
I think the main and biggest difference they have is that ListView
looks for the position of the item while creating or putting it, on the other hand RecyclerView
looks for the type of the item. if there is another item created with the same type RecyclerView
does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView
doesn't try to create same type. ListView
doesn't have a this kind of pooling mechanism.
Here's a simple example with no jQuery. Use URL.createObjectURL
, which
creates a DOMString containing a URL representing the object given in the parameter
Then, you can simply set the src
of the image to that url:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img');
img.onload = () => {
URL.revokeObjectURL(img.src); // no longer needed, free memory
}
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
}
});
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
Normal ways would be Integer.toString(i)
or String.valueOf(i)
.
int i = 5;
String strI = String.valueOf(i);
Or
int aInt = 1;
String aString = Integer.toString(aInt);
This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row">
with container
class. Cause container
class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.
So just start writing <div class="row">
without container class and you are ready to go with 100% width layout.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Basic 100% width Structure</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
<script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-3 red">Test content</div>
<div class="col-md-9 green">Another Content</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here
Reply me if you need more further assistance. Thanks.
Here's a human-readable time stamp that may be used in a file name, just in case someone needs the same thing that I needed:
package com.example.xyz;
import android.text.format.Time;
/**
* Clock utility.
*/
public class Clock {
/**
* Get current time in human-readable form.
* @return current time as a string.
*/
public static String getNow() {
Time now = new Time();
now.setToNow();
String sTime = now.format("%Y_%m_%d %T");
return sTime;
}
/**
* Get current time in human-readable form without spaces and special characters.
* The returned value may be used to compose a file name.
* @return current time as a string.
*/
public static String getTimeStamp() {
Time now = new Time();
now.setToNow();
String sTime = now.format("%Y_%m_%d_%H_%M_%S");
return sTime;
}
}
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
This should work, but is slower and feels wrong: System.arraycopy(new float[]{...}, 0, values, 0, 3);
Take a look at Rick Hightower's approach. His approach avoids configuring ObjectMapper as a singleton and allows you to filter the JSON response for the same object in different ways per each request method.
http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring
If you are struggling with authenticating to a site, and Maven is caching the results, simply removing the meta-data about the site from the meta-data stash will force Maven to revisit the site.
gvim <local-git-repository>/commons-codec/resolver-status.properties
I also got the error you mention:
CMake Error: CMake can not determine linker language for target:helloworld
CMake Error: Cannot determine link language for target "helloworld".
In my case this was due to having C++ files with the .cc
extension.
If CMake is unable to determine the language of the code correctly you can use the following:
set_target_properties(hello PROPERTIES LINKER_LANGUAGE CXX)
The accepted answer that suggests appending the language to the project()
statement simply adds more strict checking for what language is used (according to the documentation), but it wasn't helpful to me:
Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled. If a variable exists called CMAKE_PROJECT__INCLUDE_FILE, the file pointed to by that variable will be included as the last step of the project command.
With the recent version of nmap 6.40, it will automatically show you the MAC address. example:
nmap 192.168.0.1-255
this command will scan your network from 192.168.0.1 to 255 and will display the hosts with their MAC address on your network.
in case you want to display the mac address for a single client, use this command make sure you are on root or use "sudo"
sudo nmap -Pn 192.168.0.1
this command will display the host MAC address and the open ports.
hope that is helpful.
I had a similar issue with exceptions due to the connection state, then I realized I had my domain service class variable marked as static (by mistake).
My guess is that once the service library is loaded into memory, each new call ends up using the same static variable value (domain service instance), causing conflicts via the connection state.
I think also that each client call resulted in a new thread, so multiple threads accessing the same domain service instance equated to a train wreck.
this function limit decimal without round number
function limitDecimal(num,decimal){
return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}
Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:
http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.
Specifically for java web start set the environment variable:
JAVAWS_VM_ARGS
and for applets:
_JPI_VM_OPTIONS
e.g.
_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true
Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.
just type SET SQL_SAFE_UPDATES = 0; before the delete or update and set to 1 again SET SQL_SAFE_UPDATES = 1
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run
$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP = hello.py
$ python -m flask run
source: For more
The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.
Example:
<div style="width:400px; height:200px;">
<img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>
Notes:
-webkit-transform:scale(4); -webkit-transform-origin:left top;
in the style.This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal
There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
The challenge I see with the solution:
FROM(
SELECT top(100) *
FROM Customers
UNION
SELECT top(100) *
FROM CustomerEurope
UNION
SELECT top(100) *
FROM CustomerAsia
UNION
SELECT top(100) *
FROM CustomerAmericas
)
is that this creates a windowed data set that will reside in the RAM and on larger data sets this solution will create severe performance issues as it must first create the partition and then it will use the partition to write to the temp table.
A better solution would be the following:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
to select insert into the temp table and then add additional rows. However the draw back here is if there are any duplicate rows in the data.
The Best Solution would be the following:
Insert into #tmpFerdeen
SELECT top(100)*
FROM Customers
UNION
SELECT top(100)*
FROM CustomerEurope
UNION
SELECT top(100)*
FROM CustomerAsia
UNION
SELECT top(100)*
FROM CustomerAmericas
This method should work for all purposes that require distinct rows. If, however, you want the duplicate rows simply swap out the UNION for UNION ALL
Best of luck!
If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:
// in service
var deferred = $q.defer();
var scope = this;
$http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
//do something
deferred.resolve(dataUsage);
}).error(function(){
deferred.reject();
});
return deferred.promise;
// in UIrouter config
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//To cancel pending request when change state
angular.forEach($http.pendingRequests, function(request) {
if (request.cancel && request.timeout) {
request.cancel.resolve();
}
});
});
Use the P
format string. This will vary by culture:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
Implement __str__()
or __repr__()
in the class's metaclass.
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print C
Use __str__
if you mean a readable stringification, use __repr__
for unambiguous representations.
If you go to Windows, Preferences then select General, Editors, Text editors, you can set colors on that property page (and there's a link for setting MORE colors - General, Appearance, Colors and fonts).
That's with an Eclipse 3.3 build anyway.
After some search, I've found a cleaner solution wich use the %
operator.
In your YAML file :
key : 'This is the foobar var : %{foobar}'
In your ruby code :
require 'yaml'
file = YAML.load_file('your_file.yml')
foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }
puts modified_content
And the output is :
This is the foobar var : Hello World !
As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :
Yaml :
key : 'The foo var is %{foo} and the bar var is %{bar} !'
Ruby :
# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }
Output :
The foo var is FOO and the bar var is BAR !
I had to do something like this just now. I ended up doing:
function newWaitImg(id) {
var img = {
"id" : id,
"state" : "on",
"hide" : function () {
$(this.id).hide();
this.state = "off";
},
"show" : function () {
$(this.id).show();
this.state = "on";
},
"toggle" : function () {
if (this.state == "on") {
this.hide();
} else {
this.show();
}
}
};
};
.
.
.
var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();
Here i show you a snippet where your problem is solved (i know, it's been too long since you posted it, but i think this is cleaner than de "clear" fix)
#nav_x000D_
{_x000D_
float: left;_x000D_
width: 25%;_x000D_
height: 150px;_x000D_
background-color: #999;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
#content_x000D_
{_x000D_
float: left;_x000D_
margin-left: 1%;_x000D_
width: 65%;_x000D_
height: 150px;_x000D_
background-color: #999;_x000D_
margin-bottom: 10px;_x000D_
} _x000D_
#wrap_x000D_
{_x000D_
background-color:#DDD;_x000D_
overflow: hidden_x000D_
}
_x000D_
<div id="wrap">_x000D_
<h1>wrap1 </h1>_x000D_
<div id="nav"></div>_x000D_
<div id="content"><a href="index.htm">< Back to article</a></div>_x000D_
</div>
_x000D_
If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.
import static org.joou.Unsigned.*;
// and then...
UByte b = ubyte(1);
UShort s = ushort(1);
UInteger i = uint(1);
ULong l = ulong(1);
All of these types extend java.lang.Number
and can be converted into higher-order primitive types and BigInteger
.
(Disclaimer: I work for the company behind these libraries)
Below is how it's working for me on Python 3.6:
import requests
import urllib3
# Suppress InsecureRequestWarning: Unverified HTTPS
urllib3.disable_warnings()
I'm interested to see if this triggers any WTF reflexes. I have a process which creates and subsequently launches a PDF document from a console app. However, I was dealing with a frailty where if the user were to run the process multiple times, generating the same file without first closing the previously generated file, the app would throw an exception and die. This was a rather frequent occurrence because file names are based on sales quote numbers.
Rather than failing in such an ungraceful manner, I decided to rely on auto-incremented file versioning:
private static string WriteFileToDisk(byte[] data, string fileName, int version = 0)
{
try
{
var versionExtension = version > 0 ? $"_{version:000}" : string.Empty;
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{fileName}{versionExtension}.pdf");
using (var writer = new FileStream(filePath, FileMode.Create))
{
writer.Write(data, 0, data.Length);
}
return filePath;
}
catch (IOException)
{
return WriteFileToDisk(data, fileName, ++version);
}
}
Probably some more care can be given to the catch
block to ensure I'm catching the correct IOException(s). I'll probably also clear out the app storage on startup since these files are intended to be temporary anyways.
I realize this goes beyond the scope of the OP's question of simply checking if the file is in use but this was indeed the problem I was looking to solve when I arrived here so perhaps it will be useful to someone else.
Google Maps API v3:
I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".
var map = new GMaps({
div: '#map',
lat: 40.730610,
lng: -73.935242,
});
var myMarkers = map.markers;
You can loop over it and access all Marker methods listed at Google Maps Reference.
If
(1) you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
(2) you have Contacts.cshtml
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
(3) you have About.cshtml
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.
Twitter bootstrap is meant to give a baseline functionality, and provides only basic javascript plugins that do something on screen. Any additional content or functionality, you'll have to do yourself.
<div class="btn-group">
<button class="btn dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#" id="action-1">Action</a></li>
<li><a href="#" id="action-2">Another action</a></li>
<li><a href="#" id="action-3">Something else here</a></li>
</ul>
</div><!-- /btn-group -->
and then with jQuery
jQuery("#action-1").click(function(e){
//do something
e.preventDefault();
});
Using
<a href="foo.html"><div class="xyz"></div></a>
works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.
When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.
It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like
.xyz:before { content: "Hello world"; }
The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
yes the best way to see what is modified is to save in file like that:
git stash show -p stash@{0} > stash.txt
Check the HTTP headers that chrome is sending with the request (Using browser extension or proxy) then try sending the same headers with CURL - Possibly one at a time till you figure out which header(s) makes the request work.
curl -A [user-agent] -H [headers] "http://something.com/api"
This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:
https://pathcopycopy.github.io/
Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:
The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %
, like this:
@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF
Make sure "Use: Regular expressions" is selected in the Find and Replace dialog:
Note that for Visual Studio 2010, this doesn't work in the Visual Studio Productivity Power Tools' "Quick Find" extension (as of the July 2011 update); instead, you'll need to use the full Find and Replace dialog (use Ctrl+Shift+H, or Edit --> Find and Replace --> Replace in Files), and change the scope to "Current Document".
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
You can use the step attribute to the input type number:
<input type="number" id="totalAmt" step="0.1"></input>
step="any"
will allow any decimal.
step="1"
will allow no decimal.
step="0.5"
will allow 0.5; 1; 1.5; ...
step="0.1"
will allow 0.1; 0.2; 0.3; 0.4; ...
You have to put your code in the callback function you supply to setTimeout
:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
Any other code will execute immediately.
To close ajax fancybox window, use this:
onclick event -> $.fancybox.close();
return false;
Another important point
JAX-WS represents SOAP
JAX-RS represents REST
How to choose between JAX-RS and JAX-WS web services implementation?
Since I couldn't find confirmation of this anywhere, I tested if disposing of the MailMessage and/or the Attachment object would dispose of the stream loaded into them as I expected would happen.
It does appear with the following test that when the MailMessage is disposed, all streams used to create attachments will also be disposed. So as long as you dispose your MailMessage the streams that went into creating it do not need handling beyond that.
MailMessage mail = new MailMessage();
//Create a MemoryStream from a file for this test
MemoryStream ms = new MemoryStream(File.ReadAllBytes(@"C:\temp\test.gif"));
mail.Attachments.Add(new System.Net.Mail.Attachment(ms, "test.gif"));
if (mail.Attachments[0].ContentStream == ms) Console.WriteLine("Streams are referencing the same resource");
Console.WriteLine("Stream length: " + mail.Attachments[0].ContentStream.Length);
//Dispose the mail as you should after sending the email
mail.Dispose();
//--Or you can dispose the attachment itself
//mm.Attachments[0].Dispose();
Console.WriteLine("This will throw a 'Cannot access a closed Stream.' exception: " + ms.Length);
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:
int getInt() const;
It changes the this
pointer in the function from Foo * const
to Foo const * const
. See here.
You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.
Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.
This is what I'm using.
module.exports.getBookByName = function(name,callback){
var query = {
name: {$regex : name}
}
User.find(query,callback);
}
I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
Google used to recommend putting it just before the </body>
tag, because the original method they provided for loading ga.js
was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head>
tag.
<head>
will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js
is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.
As a matter of personal preference, I like to include it in the <head>
, but its really a matter of preference.
Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in
/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)
instead of the apacahe installation directory.
open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.
<user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>
restart the server . That's all
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
There are several ways to do this depending on the file format required.
I would use the standard configparser approach unless there were compelling reasons to use a different format.
Write a file like so:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')
with open('config.ini', 'w') as f:
config.write(f)
The file format is very simple with sections marked out in square brackets:
[main]
key1 = value1
key2 = value2
key3 = value3
Values can be extracted from the file like so:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"
# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')
# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')
JSON data can be very complex and has the advantage of being highly portable.
Write data to a file:
import json
config = {"key1": "value1", "key2": "value2"}
with open('config1.json', 'w') as f:
json.dump(config, f)
Read data from a file:
import json
with open('config.json', 'r') as f:
config = json.load(f)
#edit the data
config['key3'] = 'value3'
#write it back to the file
with open('config.json', 'w') as f:
json.dump(config, f)
A basic YAML example is provided in this answer. More details can be found on the pyYAML website.
I'm not sure what you're trying to achieve, but you may want to consider using jQuery, which allows you to put your code in the head tag or a separate script file and still have the code executed after the DOM has loaded.
You can then do something like:
$(document).ready(function() {
$(document).remove();
});
as well as selectively removing elements (all DIVs, only DIVs with certain classes, etc.)
There's also go-render, which handles pointer recursion and lots of key sorting for string and int maps.
Installation:
go get github.com/luci/go-render/render
Example:
type customType int
type testStruct struct {
S string
V *map[string]int
I interface{}
}
a := testStruct{
S: "hello",
V: &map[string]int{"foo": 0, "bar": 1},
I: customType(42),
}
fmt.Println("Render test:")
fmt.Printf("fmt.Printf: %#v\n", a)))
fmt.Printf("render.Render: %s\n", Render(a))
Which prints:
fmt.Printf: render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)}
I'd use popen() (++waqas).
But sometimes you need reading and writing...
It seems like nobody does things the hard way any more.
(Assuming a Unix/Linux/Mac environment, or perhaps Windows with a POSIX compatibility layer...)
enum PIPE_FILE_DESCRIPTERS
{
READ_FD = 0,
WRITE_FD = 1
};
enum CONSTANTS
{
BUFFER_SIZE = 100
};
int
main()
{
int parentToChild[2];
int childToParent[2];
pid_t pid;
string dataReadFromChild;
char buffer[BUFFER_SIZE + 1];
ssize_t readResult;
int status;
ASSERT_IS(0, pipe(parentToChild));
ASSERT_IS(0, pipe(childToParent));
switch (pid = fork())
{
case -1:
FAIL("Fork failed");
exit(-1);
case 0: /* Child */
ASSERT_NOT(-1, dup2(parentToChild[READ_FD], STDIN_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDOUT_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDERR_FILENO));
ASSERT_IS(0, close(parentToChild [WRITE_FD]));
ASSERT_IS(0, close(childToParent [READ_FD]));
/* file, arg0, arg1, arg2 */
execlp("ls", "ls", "-al", "--color");
FAIL("This line should never be reached!!!");
exit(-1);
default: /* Parent */
cout << "Child " << pid << " process running..." << endl;
ASSERT_IS(0, close(parentToChild [READ_FD]));
ASSERT_IS(0, close(childToParent [WRITE_FD]));
while (true)
{
switch (readResult = read(childToParent[READ_FD],
buffer, BUFFER_SIZE))
{
case 0: /* End-of-File, or non-blocking read. */
cout << "End of file reached..." << endl
<< "Data received was ("
<< dataReadFromChild.size() << "): " << endl
<< dataReadFromChild << endl;
ASSERT_IS(pid, waitpid(pid, & status, 0));
cout << endl
<< "Child exit staus is: " << WEXITSTATUS(status) << endl
<< endl;
exit(0);
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("read() failed");
exit(-1);
}
default:
dataReadFromChild . append(buffer, readResult);
break;
}
} /* while (true) */
} /* switch (pid = fork())*/
}
You also might want to play around with select() and non-blocking reads.
fd_set readfds;
struct timeval timeout;
timeout.tv_sec = 0; /* Seconds */
timeout.tv_usec = 1000; /* Microseconds */
FD_ZERO(&readfds);
FD_SET(childToParent[READ_FD], &readfds);
switch (select (1 + childToParent[READ_FD], &readfds, (fd_set*)NULL, (fd_set*)NULL, & timeout))
{
case 0: /* Timeout expired */
break;
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("Select() Failed");
exit(-1);
}
case 1: /* We have input */
readResult = read(childToParent[READ_FD], buffer, BUFFER_SIZE);
// However you want to handle it...
break;
default:
FAIL("How did we see input on more than one file descriptor?");
exit(-1);
}
This might be an old topic but in my case it was the layout
value of css contain
property of the parent element that was causing the issue. I am using a framework for hybrid mobile that use this contain
property in most of their component.
For example:
.parentEl {
contain: size style layout;
}
.parentEl .childEl {
position: fixed;
top: 0;
left: 0;
}
Just remove the layout
value of contain
property and the fixed content should work!
.parentEl {
contain: size style;
}
This is how I do it:
str(1).zfill(len(str(total)))
Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:
Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> total = 100 >>> print(str(1).zfill(len(str(total)))) 001 >>> total = 1000 >>> print(str(1).zfill(len(str(total)))) 0001 >>> total = 10000 >>> print(str(1).zfill(len(str(total)))) 00001 >>>
This happens because you trying to run service at the same port and there is an already running application.
This can happen because your service is not stopped in the process stack. Then you just have to kill this process.
There is no need to install anything here is the one line command to kill all running python processes.
for Linux based OS:
Bash:
kill -9 $(ps -A | grep python | awk '{print $1}')
Fish:
kill -9 (ps -A | grep python | awk '{print $1}')
a simple way to do this:
try {
list.get( index );
}
catch ( IndexOutOfBoundsException e ) {
if(list.isEmpty() || index >= list.size()){
// Adding new item to list.
}
}
Or use directly the InputStream
of the resource using the absolute CLASSPATH path (starting with the /
slash character):
getClass().getResourceAsStream("/com/path/to/file.txt");
Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to
):
getClass().getResourceAsStream("file.txt");
`My vbs file path :
D:\QTP Practice\Driver\Testany.vbs'
objShell = CreateObject("Shell.Application")
objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1
set x=createobject("wscript.shell")
wscript.sleep(2000)
x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"
--from google search and some tuning, working for me
Remove maven dependenices from build path
I have one strange problem. In fact when i plug my phone to my mac the time of the device change but not use the actual hour. For example on my computer I have this hour : 05:17 pm but on my phone when is unlocked time is frozen to 09:41 am so when i try to build my app on phone from xCode i have the next error message :
Please verify that your device’s clock is properly set
The strange thing is that when my phone is still pluged to the mac the time on lockScreen is good (05:17 pm)... And if i check on Date & Time on general settings I have this strange thing too (time of statusbar is wrong but time below is good) :
After few minutes i understood that it was because of QuickTime Player which was running on my mac with view of my iPhone (i was going to save a video demo of my app).
To resolve the problem I had to quit all applications and restart computer.
In plus at the end if problem persists do these steps :
Hope this can help.
Thank you,
The commands above didn't work for me but those were very helpful:
sudo apt purge python3-pip
sudo rm -rf '/usr/lib/python3/dist-packages/pip'
sudo apt install python3-pip
cd
cd .local/lib/python3/site-packages
sudo rm -rf pip*
cd
cd .local/lib/python3.5/site-packages
sudo rm -rf pip*
sudo pip3 install jupyter
I have encounter the same problem. my syntax has no problem. What I found is that I copied and pasted git commit -m "comments" from my note. I retype it, the command execute without issue. It turns out the - and " " are the problem when I copy paste to terminal.
[Windows] As already said, it looks like .bat -file tries to find java.exe from %JAVA_HOME%/bin/java.exe
so it doesn't find it since bin
is repeated twice in path.
Remov that extra /bin
from gradle.bat.
No solutions worked for me from here, so I found another one:
set +e
find "./csharp/Platform.$REPOSITORY_NAME/obj" -type f -iname "*.cs" -delete
find "./csharp/Platform.$REPOSITORY_NAME.Tests/obj" -type f -iname "*.cs" -delete
set -e
This is useful for CI & CD. This way the error messages are printed but the whole script continues to execute.
I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify()
on the textarea
that produced it and as a result, I know that I'm always going to have the "
s at each end of the string.
In this generalized example, response
is the JSON object my AJAX returns, and key
is the name of my JSON key.
response.key.slice(1, response.key.length-1)
I used it like this with a regex replace
to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));
In this case, $('#description')
is the paragraph tag I'm writing to. studyData
is my JSON object, and description
is my key with a multi-line value.
Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).
This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np
# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only
for i in circles[0, :]:
cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)
# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
# combine foreground+background
final = cv2.bitwise_or(fg, bk)
Note: It is better to use the opencv methods because they are optimized.
Depends on what they looked like. I use gitx which makes pictures like this one:
You can compare git log --graph
vs. gitk on a 24-way octopus merge (originally from http://clojure-log.n01se.net/date/2008-12-24.html):
Modify the background image of the <td> itself.
Or apply some css to the div:
.thatSetsABackgroundWithAnIcon{
height:100%;
}
For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this
to a Groovy method as parameter context
from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."
(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)
No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.
As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.
From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.
Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.
If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.
To run one project at a time in same solution
Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.
Imao put UIImageView on background is not the best idea . In my case i added on controller view other 2 views . First view has [UIColor clearColor]
on background, second - color which u want to be transparent (grey in my case).Note that order is important.Then for second view set alpha 0.5(alpha >=0 <=1).Added this to lines in prepareForSegue
infoVC.providesPresentationContextTransitionStyle = YES;
infoVC.definesPresentationContext = YES;
And thats all.
From Windows command-line, type:
SC \\server_name query | find /I "SQL Server ("
Where "server_name" is the name of any remote server on which you wish to display the SQL instances.
This requires enough permissions of course.
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
In my case the issue was that my default kit's Qt version
was None
.
Go to Tools -> Options... -> Build & Run -> Kits
tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version
. If it's None
, change it to one of the versions available to you in the Qt versions
tab which is just next to the Kits
tab.
I believe the simplest solution would be to use find
. I do not like to have multiple .gitignore
hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore
. To do so you could simply append the found files to your .gitignore
. Supposing that /public/static/
is your project/git home I would use something like:
find . -type f -name *.js | cut -c 3- >> .gitignore
I found that cutting out the ./
at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-
.
Use the in
operator: e.g. "key1" in a
.
It happens because with navbar-fixed-top
class the navbar gets the position:fixed
. This in turns take the navbar out of the document flow leaving the body to take up the space behind the navbar.
You need to apply padding-top
or margin-top
to your container
, based on your requirements with values >= 50px
. (or play around with different values)
The basic bootstrap navbar takes height around 40px
. So if you give a padding-top
or margin-top
of 50px
or more, you will always have that breathing space between your container and the navbar.
This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:
boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT
tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT
int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT
mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT
bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT
float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT
double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE
decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL
number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric
blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY
function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION
UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN
datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime
time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time
timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp
date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date
char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR
varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR
nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR
nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR
clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR
currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY
uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER
For reference, this is the groovy script I've used to generate this output:
@Grab('org.liquibase:liquibase-core:3.5.1')
import liquibase.database.core.*
import liquibase.datatype.core.*
def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
def datatype = it.newInstance()
datatype.finishInitialization("")
println datatype.name
databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
println ''
}
If you want to delete file first close all the connections and streams. after that delete the file.
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
Firebase Cloud Messaging (FCM) is the new version of GCM. FCM is a cross-platform messaging solution that allows you to send messages securely and for free. Inherits GCM's central infrastructure to deliver messages reliably on Android, iOS, Web (javascript), Unity and C ++.
As of April 10, 2018, Google has disapproved of GCM. The GCM server and client APIs are deprecated and will be removed on April 11, 2019. Google recommends migrating GCM applications to Firebase Cloud Messaging (FCM), which inherits the reliable and scalable GCM infrastructure.
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
e.g.: [null, "coconut", null, "apple", "strawberry"]
First sort: ["coconut", "apple", "strawberry", null, null]
Second sort: ["apple", "coconut", "strawberry", null, null]
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
In addition to all the other answers you received, I want to explain the unknown option -- o
error: Your command was
$ adb shell 'su -c mount -o rw,remount /system'
which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell
. However, su -c <cmd>
also needs you to quote the command with arguments it shall pass to the shell's -c
option. (YMMV depending on su
variants.) Therefore, you might want to try
$ adb shell 'su -c "mount -o rw,remount /system"'
(and potentially add the actual device listed in the output of mount | grep system
before the /system
arg – see the other answers.)
@Tony: You can even get rid of the type %file%
command.
for /f "tokens=2 delims=:" %%a in ('find /c /v "" %_file%') do set /a _Lines=%%a
For long files this should be even quicker.
For a Ruby on Rails application, I was able to prevent a layout from loading by specifying
render layout: false
in the controller action that I wanted to respond with ajax html.
This worked for me
Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
{ "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };
String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };
int noOfColumns = headers.length;
int rowCount = 0;
Row rowZero = sheet.createRow(rowCount++);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int col = 1; col <= noOfColumns; col++) {
Cell cell = rowZero.createCell(col);
cell.setCellValue(headers[col - 1]);
cell.setCellStyle(style);
}
If you were asking how to get the PID of a known command it would resemble something like this:
If you had issued the command below #The command issued was ***
dd if=/dev/diskx of=/dev/disky
Then you would use:
PIDs=$(ps | grep dd | grep if | cut -b 1-5)
What happens here is it pipes all needed unique characters to a field and that field can be echoed using
echo $PIDs
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
Try to change like this ..
firstStr = "<?xml version" 'my file always starts like this
Do until objInputFile.AtEndOfStream
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))
tmpStr = objInputFile.ReadLine
If InStr(tmpStr, substrToFind) <= 0 Then
If Instr(tmpStr, firstStr) > 0 Then
text = tmpStr 'to avoid the first empty line
Else
text = text & vbCrLf & tmpStr
End If
Else
text = text & vbCrLf & strToAdd & vbCrLf & tmpStr
End If
index = index + 1
Loop
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Time to contribute now. I am sysadmin role and worked on getting two public access users to execute xp_cmdshell. I am able to execute xp_cmdshell but not the two users.
I did the following steps:
create new role:
use master
CREATE ROLE [CmdShell_Executor] AUTHORIZATION [dbo]
GRANT EXEC ON xp_cmdshell TO [CmdShell_Executor]
add users in master database: Security --> Users. Membership checks only [CmdShell_Executor] that is just created
set up proxy account:
EXEC sp_xp_cmdshell_proxy_account 'domain\user1','users1 Windows password'
EXEC sp_xp_cmdshell_proxy_account 'domain\user2','users2 Windows password'
Then both users can execute the stored procedure that contains xp_cmdshell invoking a R script run. I let the users come to my PC to type in the password, execute the one line code, then delete the password.
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
You can also do it like this
public Map<Boolean, List<Student>> getpartitionMap(List<Student> studentsList) {
List<Predicate<Student>> allPredicates = getAllPredicates();
Predicate<Student> compositePredicate = allPredicates.stream()
.reduce(w -> true, Predicate::and)
Map<Boolean, List<Student>> studentsMap= studentsList
.stream()
.collect(Collectors.partitioningBy(compositePredicate));
return studentsMap;
}
public List<Student> getValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> validStudentsList = studentsMap.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.TRUE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return validStudentsList;
}
public List<Student> getInValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> invalidStudentsList =
partionedByPredicate.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.FALSE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return invalidStudentsList;
}
With flatMap
you will get just List<Student>
instead of List<List<Student>>
.
Thanks
When multiple threads need to check and change the boolean. For example:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
sp_help tablename in sql server -- sp_help [ [ @objname = ] 'name' ]
desc tablename in oracle -- DESCRIBE { table-Name | view-Name }
Get your response via a regular http-request, using:
URLConnection con = new URL("http://example.com").openConnection()
;The next step is parsing it. Take a look at this article for a choice of parser.
No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.
I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println
for example just adds a newline to what fmt.Print
would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.
Late to the party, but the tsbox package is designed to perform conversions like this. To convert your data into a ts
-object, you can do:
dta <- data.frame(
Dates = c("3/14/2013", "3/15/2013", "3/18/2013", "3/19/2013"),
Bajaj_close = c(1854.8, 1850.3, 1812.1, 1835.9),
Hero_close = c(1669.1, 1684.45, 1690.5, 1645.6)
)
dta
#> Dates Bajaj_close Hero_close
#> 1 3/14/2013 1854.8 1669.10
#> 2 3/15/2013 1850.3 1684.45
#> 3 3/18/2013 1812.1 1690.50
#> 4 3/19/2013 1835.9 1645.60
library(tsbox)
ts_ts(ts_long(dta))
#> Time Series:
#> Start = 2013.1971293045
#> End = 2013.21081883954
#> Frequency = 365.2425
#> Bajaj_close Hero_close
#> 2013.197 1854.8 1669.10
#> 2013.200 1850.3 1684.45
#> 2013.203 NA NA
#> 2013.205 NA NA
#> 2013.208 1812.1 1690.50
#> 2013.211 1835.9 1645.60
It automatically parses the dates, detects the frequency and makes the missing values at the weekends explicit. With ts_<class>
, you can convert the data to any other time series class.
XMLStarlet or another XPath engine is the correct tool for this job.
For instance, with data.xml
containing the following:
<root>
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
</root>
...you can extract only the first title with the following:
xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml
Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster & Jobs
to Brewster & Jobs
), and so forth.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
The data.table
package introduced the IDate
class some time ago and zoo
-package-like functions to retrieve months, days, etc (Check ?IDate
). so, you can extract the desired info now in the following ways:
require(data.table)
df <- data.frame(id = 1:3,
date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
setDT(df)
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]
You did not specify your operating system, so this is difficult to answer. If you are using a system based on gnu libc, you might be able to use the libc function backtrace()
.
GCC also has two builtins that can assist you, but which may or may not be implemented fully on your architecture, and those are __builtin_frame_address
and __builtin_return_address
. Both of which want an immediate integer level (by immediate, I mean it can't be a variable). If __builtin_frame_address
for a given level is non-zero, it should be safe to grab the return address of the same level.
It is better to use InputFilter interface. Much easier to handle any kind of inputs by using regex. My solution for currency input format:
public class CurrencyFormatInputFilter implements InputFilter {
Pattern mPattern = Pattern.compile("(0|[1-9]+[0-9]*)(\\.[0-9]{1,2})?");
@Override
public CharSequence filter(
CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {
String result =
dest.subSequence(0, dstart)
+ source.toString()
+ dest.subSequence(dend, dest.length());
Matcher matcher = mPattern.matcher(result);
if (!matcher.matches()) return dest.subSequence(dstart, dend);
return null;
}
}
Valid: 0.00, 0.0, 10.00, 111.1
Invalid: 0, 0.000, 111, 10, 010.00, 01.0
How to use:
editText.setFilters(new InputFilter[] {new CurrencyFormatInputFilter()});
public static T GetValueOrDefault<T>(this IDataRecord rdr, int index)
{
object val = rdr[index];
if (!(val is DBNull))
return (T)val;
return default(T);
}
Just use it like this:
decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1);
string Unit = rdr.GetValueOrDefault<string>(2);
(Adding to previous answers (hope that helps someone):)
Age is simpler but in case of string and with ignoring case:
@fathers.any? { |father| father[:name].casecmp("john") == 0 }
should work for any case in start or anywhere in the string i.e. for "John"
, "john"
or "JoHn"
and so on.
@fathers.find { |father| father[:name].casecmp("john") == 0 }
@fathers.select { |father| father[:name].casecmp("john") == 0 }
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
For Windows 8.1 Users.... there is a little note on the java download site which says:
"Downloading and installing Java will only work in Desktop mode on Windows 8 and Windows 8.1. See the Java on Windows 8 FAQ for more detailed information."
Unfortunately, "Desktop mode" is not the default mode in Windows 8.1. After installing java and wasting 2hours trying to get java working with IE11, I went back to oracles site...paid a bit more attention to that warning!! switched to Desktop mode, and reinstalled java... hey presto it worked.
Furious, that java download does not work with the default config of Windows 8.1, don't know who to be more angry with? Oracle or Microsoft? ( or me for skimming over the warning..)
Stored procedures are a batch of SQL statements that can be executed in a couple of ways. Most major DBMs support stored procedures; however, not all do. You will need to verify with your particular DBMS help documentation for specifics. As I am most familiar with SQL Server I will use that as my samples.
To create a stored procedure the syntax is fairly simple:
CREATE PROCEDURE <owner>.<procedure name>
<Param> <datatype>
AS
<Body>
So for example:
CREATE PROCEDURE Users_GetUserInfo
@login nvarchar(30)=null
AS
SELECT * from [Users]
WHERE ISNULL(@login,login)=login
A benefit of stored procedures is that you can centralize data access logic into a single place that is then easy for DBA's to optimize. Stored procedures also have a security benefit in that you can grant execute rights to a stored procedure but the user will not need to have read/write permissions on the underlying tables. This is a good first step against SQL injection.
Stored procedures do come with downsides, basically the maintenance associated with your basic CRUD operation. Let's say for each table you have an Insert, Update, Delete and at least one select based on the primary key, that means each table will have 4 procedures. Now take a decent size database of 400 tables, and you have 1600 procedures! And that's assuming you don't have duplicates which you probably will.
This is where using an ORM or some other method to auto generate your basic CRUD operations has a ton of merit.
I had the same error.
My filename was jpaContext.xml
and it was placed in src/main/resources
. I specified param value="classpath:/jpaContext.xml"
.
Finally I renamed the file to applicationContext.xml
and moved it to the WEB-INF directory and changed param value to /WEB-INF/applicationContext.xml
, then it worked!
For usages of Write-Host
, PSScriptAnalyzer
produces the following diagnostic:
Avoid using
Write-Host
because it might not work in all hosts, does not work when there is no host, and (prior to PS 5.0) cannot be suppressed, captured, or redirected. Instead, useWrite-Output
,Write-Verbose
, orWrite-Information
.
See the documentation behind that rule for more information. Excerpts for posterity:
The use of
Write-Host
is greatly discouraged unless in the use of commands with theShow
verb. TheShow
verb explicitly means "show on the screen, with no other possibilities".Commands with the
Show
verb do not have this check applied.
Jeffrey Snover has a blog post Write-Host Considered Harmful in which he claims Write-Host is almost always the wrong thing to do because it interferes with automation and provides more explanation behind the diagnostic, however the above is a good summary.
Let's define a list first:
lst=[1,2,3]
You can directly write your list to a file:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
To read your list from text file first you read the file and store in a variable:
f=open("filename.txt","r")
lst=f.read()
f.close()
The type of variable lst
is of course string. You can convert this string into array using eval
function.
lst=eval(lst)
You're missing the necessary class definition; typically caused by required JAR not being in classpath.
From J2SE API:
public class NoClassDefFoundError extends LinkageError
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.