In order to check if the value is a valid type of the standard JS-date object, you can make use of this predicate:
function isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
date
checks whether the parameter was not a falsy value (undefined
, null
, 0
, ""
, etc..)Object.prototype.toString.call(date)
returns a native string representation of the given object type - In our case "[object Date]"
. Because date.toString()
overrides its parent method, we need to .call
or .apply
the method from Object.prototype
directly which ..
instanceof
or Date.prototype.isPrototypeOf
.!isNaN(date)
finally checks whether the value was not an Invalid Date
.This is a modification of nate_weldon's answer with a few improvements:
application.DisplayAlerts = false;
before attempting to save to hide promptsAlso note that the application.Workbooks.Open
and ws.SaveAs
methods expect sourceFilePath
and targetFilePath
to be full paths (ie. directory path + filename)
private static void SaveAs(string sourceFilePath, string targetFilePath)
{
Application application = null;
Workbook wb = null;
Worksheet ws = null;
try
{
application = new Application();
application.DisplayAlerts = false;
wb = application.Workbooks.Open(sourceFilePath);
ws = (Worksheet)wb.Sheets[1];
ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
}
catch (Exception e)
{
// Handle exception
}
finally
{
if (application != null) application.Quit();
if (ws != null) Marshal.ReleaseComObject(ws);
if (wb != null) Marshal.ReleaseComObject(wb);
if (application != null) Marshal.ReleaseComObject(application);
}
}
Doing it the mathy way...
nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
If you have already included the CSRF token in your form. Then you are getting the error page possibly because of cache data in your form.
Open your terminal/command prompt and run these commands in your project root.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
,Also try to clear the browser cache along with running these commands.
If you have more than one button, then you can do the following.
<div class="center-block" style="max-width:400px">
<a href="#" class="btn btn-success">Accept</a>
<a href="#" class="btn btn-danger"> Reject</a>
</div>
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
According to this article application/xml is preferred.
EDIT
I did a little follow-up on the article.
The author claims that the encoding declared in XML processing instructions, like:
<?xml version="1.0" encoding="UTF-8"?>
can be ignored when text/xml
media type is used.
They support the thesis with the definition of text/*
MIME type family specification in RFC 2046, specifically the following fragment:
4.1.2. Charset Parameter
A critical parameter that may be specified in the Content-Type field
for "text/plain" data is the character set. This is specified with a
"charset" parameter, as in:
Content-type: text/plain; charset=iso-8859-1
Unlike some other parameter values, the values of the charset
parameter are NOT case sensitive. The default character set, which
must be assumed in the absence of a charset parameter, is US-ASCII.
The specification for any future subtypes of "text" must specify
whether or not they will also utilize a "charset" parameter, and may
possibly restrict its values as well. For other subtypes of "text"
than "text/plain", the semantics of the "charset" parameter should be
defined to be identical to those specified here for "text/plain",
i.e., the body consists entirely of characters in the given charset.
In particular, definers of future "text" subtypes should pay close
attention to the implications of multioctet character sets for their
subtype definitions.
According to them, such difficulties can be avoided when using application/xml
MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml
. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.
Use dynamic_cast
for converting pointers/references within an inheritance hierarchy.
Use static_cast
for ordinary type conversions.
Use reinterpret_cast
for low-level reinterpreting of bit patterns. Use with extreme caution.
Use const_cast
for casting away const/volatile
. Avoid this unless you are stuck using a const-incorrect API.
Simply add the classes to your form as follows.
class UserLoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(
attrs={
'class':'form-control',
'placeholder':'Username'
}
))
password = forms.CharField(widget=forms.PasswordInput(
attrs={
'class':'form-control',
'placeholder':'Password'
}
))
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
8B 5D 32
is machine code
mov ebx, [ebp+32h]
is assembly
lmylib.so
containing 8B 5D 32
is object code
If you want extract host from string http://google.com/dhasjkdas/sadsdds/sdda/sdads.html
, usage of parse_url() is acceptable solution for you.
But if you want extract domain or its parts, you need package that using Public Suffix List. Yes, you can use string functions arround parse_url(), but it will produce incorrect results sometimes.
I recomend TLDExtract for domain parsing, here is sample code that show diff:
$extract = new LayerShifter\TLDExtract\Extract();
# For 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
parse_url($url, PHP_URL_HOST); // will return google.com
$result = $extract->parse($url);
$result->getFullHost(); // will return 'google.com'
$result->getRegistrableDomain(); // will return 'google.com'
$result->getSuffix(); // will return 'com'
# For 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html'
$url = 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html';
parse_url($url, PHP_URL_HOST); // will return 'search.google.com'
$result = $extract->parse($url);
$result->getFullHost(); // will return 'search.google.com'
$result->getRegistrableDomain(); // will return 'google.com'
The user-agent
should be specified as a field in the header.
Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent
.
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]' # This is another valid field
}
response = requests.get(url, headers=headers)
Older versions of requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
Try using the not()
method instead of the :not()
selector.
$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
Swift 4+:
let myTableViewController = UITableViewController(style: .grouped)
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
To export the exact set of paths used by Anaconda, use the command echo %PATH%
in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.
Reference: https://stackoverflow.com/a/54240362/663028
Yes, you just forgot the quotes ...
$('<form/>').attr('action','form2.html').submit();
My error was:
duplicate output file
'/Users/home/Library/Developer/Xcode/DerivedData/myAppName-fawptgabysjowicvpeqydjniuovo/Build/Products/Debug-iphoneos/myAppName.app/GoogleMaps.bundle' on task: PhaseScriptExecution [CP] Copy Pods Resources /Users/home/Library/Developer/Xcode/DerivedData/myAppName-fawptgabysjowicvpeqydjniuovo/Build/Intermediates.noindex/myAppName.build/Debug-iphoneos/myAppName.build/Script-32CCC25BF727B592A1784900.sh
I focused on the problem file being GoogleMaps.bundle
and the location of that file being in [CP] Copy Pods Resources
, and the fact that it specified it’s a duplicate output file
(I highlighted them in black above), it's the 4th step below
Make sure you do the following steps on a Duplicate Project
1- In the project navigator I went to the blue project icon
2- I choose Build phases
3- Under Build Phases I choose [CP] Copy Pods Resources
4- Under [CP] Copy Pods Resources
I went to Output Files
and underneath there I found the file that ended with GoogleMaps.bundle
. I selected it and pressed the minus sign to delete it. Make sure you go to Output Files and NOT Input Files
5- I did a clean shift+cmmd+k
and afterwards when I built the project the error was gone
The odd thing was even though the red error went away the yellow warning was still there but it worked :)
If you need the functionality if a index for a column exists (here at first place in sequence) as a database function you can use/adopt this code. If you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part "AND SEQ_IN_INDEX = 1".
DELIMITER $$
CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
`IN_SCHEMA` VARCHAR(255),
`IN_TABLE` VARCHAR(255),
`IN_COLUMN` VARCHAR(255)
)
RETURNS tinyint(4)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
BEGIN
-- Check if index exists at first place in sequence for a given column in a given table in a given schema.
-- Returns -1 if schema does not exist.
-- Returns -2 if table does not exist.
-- Returns -3 if column does not exist.
-- If the index exists in first place it returns 1, otherwise 0.
-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');
-- check if schema exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.SCHEMATA
WHERE
SCHEMA_NAME = IN_SCHEMA
;
IF @COUNT_EXISTS = 0 THEN
RETURN -1;
END IF;
-- check if table exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
;
IF @COUNT_EXISTS = 0 THEN
RETURN -2;
END IF;
-- check if column exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
AND COLUMN_NAME = IN_COLUMN
;
IF @COUNT_EXISTS = 0 THEN
RETURN -3;
END IF;
-- check if index exists at first place in sequence
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
information_schema.statistics
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
AND SEQ_IN_INDEX = 1;
IF @COUNT_EXISTS > 0 THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
Here is a little research that explored RDBMS vs NoSQL using MySQL vs Mongo, the conclusions were inline with @Sean Reilly's response. In short, the benefit comes from the design, not some raw speed difference. Conclusion on page 35-36:
RDBMS vs NoSQL: Performance and Scaling Comparison
The project tested, analysed and compared the performance and scalability of the two database types. The experiments done included running different numbers and types of queries, some more complex than others, in order to analyse how the databases scaled with increased load. The most important factor in this case was the query type used as MongoDB could handle more complex queries faster due mainly to its simpler schema at the sacrifice of data duplication meaning that a NoSQL database may contain large amounts of data duplicates. Although a schema directly migrated from the RDBMS could be used this would eliminate the advantage of MongoDB’s underlying data representation of subdocuments which allowed the use of less queries towards the database as tables were combined. Despite the performance gain which MongoDB had over MySQL in these complex queries, when the benchmark modelled the MySQL query similarly to the MongoDB complex query by using nested SELECTs MySQL performed best although at higher numbers of connections the two behaved similarly. The last type of query benchmarked which was the complex query containing two JOINS and and a subquery showed the advantage MongoDB has over MySQL due to its use of subdocuments. This advantage comes at the cost of data duplication which causes an increase in the database size. If such queries are typical in an application then it is important to consider NoSQL databases as alternatives while taking in account the cost in storage and memory size resulting from the larger database size.
I was having a similar issue when I wanted to modify the array state while retaining the position of the element in the array
This is a function to toggle between like and unlike:
const liker = (index) =>
setData((prevState) => {
prevState[index].like = !prevState[index].like;
return [...prevState];
});
as we can say the function takes the index of the element in the array state, and we go ahead and modify the old state and rebuild the state tree
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.
javascript:location.href=%22googlechrome%22+location.href.substring(4);
Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.
Works for me.
import sys
sys.exit(1)
--pylab
no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py
file to get both pylab
as well as autoreload
functionalities.
c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']
Heres how this code looks:
Heres my drag and drop code:
var boxView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.blackColor()
addSavingPhotoView()
//Custom button to test this app
var button = UIButton(frame: CGRect(x: 20, y: 20, width: 20, height: 20))
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
}
func addSavingPhotoView() {
// You only need to adjust this frame to move it anywhere you want
boxView = UIView(frame: CGRect(x: view.frame.midX - 90, y: view.frame.midY - 25, width: 180, height: 50))
boxView.backgroundColor = UIColor.whiteColor()
boxView.alpha = 0.8
boxView.layer.cornerRadius = 10
//Here the spinnier is initialized
var activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
activityView.startAnimating()
var textLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
textLabel.textColor = UIColor.grayColor()
textLabel.text = "Saving Photo"
boxView.addSubview(activityView)
boxView.addSubview(textLabel)
view.addSubview(boxView)
}
func buttonAction(sender:UIButton!) {
//When button is pressed it removes the boxView from screen
boxView.removeFromSuperview()
}
Here is an open source version of this: https://github.com/goktugyil/CozyLoadingActivity
Assuming the second window is defined as public partial class Window2 : Window
, you can do it by:
Window2 win2 = new Window2();
win2.Show();
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better use the nullptr
value to check:
char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr
if (array[4] == nullptr)
// do something
You can try simpleBootstrapDialog. Here you can pass title, message, callback options for cancel and submit etc...
To use this plugin include simpleBootstrapDialog.js file like below
<script type="text/javascript" src="/simpleDialog.js"></script>
Basic Usage
<script type="text/javascript>
$.simpleDialog();
</script>
Custom Title and description
$.simpleDialog({
title:"Alert Dialog",
message:"Alert Message"
});
With Callback
<script type="text/javascript>
$.simpleDialog({
onSuccess:function(){
alert("You confirmed");
},
onCancel:function(){
alert("You cancelled");
}
});
</script>
I just ran into this and was noticing that the documentation had my answer:
"This function will never be called with a null state."
In my case, I was wondering why the onRestoreInstanceState wasn't being called on initial instantiation. This also means that if you don't store anything, it'll not be called when you go to reconstruct your view.
in this approach , you can check if there is only 1 set bit in the integer and the integer is > 0 (c++).
bool is_pow_of_2(int n){
int count = 0;
for(int i = 0; i < 32; i++){
count += (n>>i & 1);
}
return count == 1 && n > 0;
}
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
You can use Task.WhenAll
function that you can pass n tasks; Task.WhenAll
will return a task which runs to completion when all the tasks that you passed to Task.WhenAll
complete. You have to wait asynchronously on Task.WhenAll
so that you'll not block your UI thread:
public async Task DoSomeThing() {
var Task[] tasks = new Task[numTasks];
for(int i = 0; i < numTask; i++)
{
tasks[i] = CallSomeAsync();
}
await Task.WhenAll(tasks);
// code that'll execute on UI thread
}
Git clone is the command you're looking for:
git clone [email protected]:username/repo.git
Update: And this is the official guide: https://help.github.com/articles/fork-a-repo
Take a look at: https://help.github.com/
It has really useful content
import os
path = 'C:/Users/Shashank/Desktop/'
os.chdir(path)
for p,n,f in os.walk(os.getcwd()):
for a in f:
a = str(a)
if a.endswith('.csv'):
print(a)
print(p)
This will help to identify path also of these csv files
Here is my answer
private fun openFolder() {
val location = "/storage/emulated/0/Download/";
val intent = Intent(Intent.ACTION_VIEW)
val myDir: Uri = FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", File(location))
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
intent.setDataAndType(myDir, DocumentsContract.Document.MIME_TYPE_DIR)
else intent.setDataAndType(myDir, "*/*")
if (intent.resolveActivityInfo(context.packageManager, 0) != null)
{
context.startActivity(intent)
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
CustomToast.toastIt(context,context.getString(R.string.there_is_no_file_explorer_app_present_text))
}
}
Here why I used FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
I tested on this device
Devices: Samsung SM-G950F (dreamltexx), Os API Level: 28
I had tried various things, including "Clean Up" on lower subdirectories. Finally, I tried updating the top level folder. Nothing. Then I read the "Clean up top level" tip. I tried that. The clean up part succeeded, but the lock remained. My solution was to go back to the top level, clean up, then clean up each red (!) folder I could drill down to. After all was "Cleaned up", the update worked perfectly. The "break lock" tip looks good, too, with the exception that someone on your team might have a legitimate lock on things.
An alternative to Ctrl+A, Ctrl+K is Ctrl+E, Ctrl+U.
SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()
That said, everybody seems to come to this page for the more general answer to your question:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
SELECT TOP 1 column FROM table
ORDER BY NEWID()
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
SELECT column FROM table
ORDER BY RANDOM() LIMIT 1
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
mvn install
(or mvn package
) will always work.
You can use mvn compile
to download compile time dependencies or mvn test
for compile time and test dependencies but I prefer something that always works.
Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.
Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:
LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);
LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );
long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS );
tempDateTime = tempDateTime.plusYears( years );
long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS );
tempDateTime = tempDateTime.plusMonths( months );
long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS );
tempDateTime = tempDateTime.plusDays( days );
long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS );
tempDateTime = tempDateTime.plusHours( hours );
long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES );
tempDateTime = tempDateTime.plusMinutes( minutes );
long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS );
System.out.println( years + " years " +
months + " months " +
days + " days " +
hours + " hours " +
minutes + " minutes " +
seconds + " seconds.");
//prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.
The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.
Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
<input type="number" class="dec-number" min="0" step="0.01" />
Event handler:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.
div.style
yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:
div.style["top"] = "200px";
div.style["left"] = "200px";
This is useful, for example, if you need to access a "variable" property:
div.style[prop] = "200px";
This will probably solve your problem: https://help.ubuntu.com/community/EnvironmentVariables
Session-wide environment variables
In order to set environment variables in a way that affects a particular user's environment, one should not place commands to set their values in particular shell script files in the user's home directory, but use:
~/.pam_environment - This file is specifically meant for setting a user's environment. It is not a script file, but rather consists of assignment expressions, one per line.
Not recommended:
~/.profile - This is probably the best file for placing environment variable assignments in, since it gets executed automatically by the DisplayManager during the startup process desktop session as well as by the login shell when one logs-in from the textual console.
thanks Paul Wardrip in my case I use required.
@RequestMapping(value={ "/calificacion-usuario/{idUsuario}/{annio}/{mes}", "/calificacion-usuario/{idUsuario}" }, method=RequestMethod.GET)
public List<Calificacion> getCalificacionByUsuario(@PathVariable String idUsuario
, @PathVariable(required = false) Integer annio
, @PathVariable(required = false) Integer mes) throws Exception {
return repositoryCalificacion.findCalificacionByName(idUsuario, annio, mes);
}
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
Two of them always produce the same answer:
COUNT(*)
counts the number of rowsCOUNT(1)
also counts the number of rowsAssuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rowsHowever, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).
Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool
(and set the value to true
for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key]
to check for presence.
You should configure the sonar-runner to use your existing SonarQube server. To do so, you need to update its conf/sonar-runner.properties
file and specify the SonarQube server URL, username, password, and JDBC URL as well. See https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner for details.
If you don't yet have an up and running SonarQube server, then you can launch one locally (with the default configuration) - it will bind to http://localhost:9000 and work with the default sonar-runner configuration. See https://docs.sonarqube.org/latest/setup/get-started-2-minutes/ for details on how to get started with the SonarQube server.
The easiest way I've tackled this is with CSS:
<style>
.redUnderline {
color: #ff0000;
border-bottom: 1px solid #000000;
}
</style>
<span class="redUnderline">$username</span>
Also, for an actual underline, if your item is a link, this works:
<style>
a.blackUnderline {
color: #000000;
text-decoration: underline;
}
.red {
color: #ff0000;
}
</style>
<a href="" class="blackUnderline"><span class="red">$username</span></a>
In addition to remove ugly cast warnings as most mentioned ,Class.cast is run-time cast mostly used with generic casting ,due to generic info will be erased at run time and some how each generic will be considered Object , this leads to not to throw an early ClassCastException.
for example serviceLoder use this trick when creating the objects,check S p = service.cast(c.newInstance()); this will throw a class cast exception when S P =(S) c.newInstance(); won't and may show a warning 'Type safety: Unchecked cast from Object to S'.(same as Object P =(Object) c.newInstance();)
-simply it checks that the casted object is instance of casting class then it will use the cast operator to cast and hide the warning by suppressing it.
java implementation for dynamic cast:
@SuppressWarnings("unchecked")
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
S p = service.cast(c.newInstance());
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
How to get the size of a list?
To find the size of a list, use the builtin function, len
:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
And now:
len(items)
returns 3.
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size
, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you're checking if list size is zero or not, don't use len
- instead, put the list in a boolean context - it treated as False if empty, True otherwise.
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
len
is implemented with __len__
, from the data model docs:
object.__len__(self)
Called to implement the built-in function
len()
. Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a__nonzero__()
[in Python 2 or__bool__()
in Python 3] method and whose__len__()
method returns zero is considered to be false in a Boolean context.
And we can also see that __len__
is a method of lists:
items.__len__()
returns 3.
len
(length) ofAnd in fact we see we can get this information for all of the described types:
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,
range, dict, set, frozenset))
True
len
to test for an empty or nonempty listTo test for a specific length, of course, simply test for equality:
if len(items) == required_length:
...
But there's a special case for testing for a zero length list or the inverse. In that case, do not test for equality.
Also, do not do:
if len(items):
...
Instead, simply do:
if items: # Then we have some items, not empty!
...
or
if not items: # Then we have an empty list!
...
I explain why here but in short, if items
or if not items
is both more readable and more performant.
This requires adding a .targets
file to your project and setting it to be included in the project's includes section.
See my answer here for the procedure.
I believe the default color integer value is 16711935 (0x00FF00FF).
When you say
val map = scala.collection.mutable.Map
you are not creating a map instance, but instead aliasing the Map type.
map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
Try instead the following:
scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()
scala> map("asdf") = 9
scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
The previous answers did not fix my issue, because they don't include blob: data: gap:
keywords at the same time; so here is a string that does:
<meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;">
Warning: This exposes the document to many exploits. Be sure to prevent users from executing code in the console or to be in a closed environment like a Cordova application.
You can do it simply.
var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this
First create the project from the following link to create larave 7 project: Create Project
Now you need to enter your project folder using the following command:
cd myproject
Now try to run artisan
command, such as, php artisan
.
Or it may happen if you didn't install compose. So if you didn't install composer then run composer install
and try again artisan
command.
You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.
Try:
git branch --set-upstream downloadmanager origin/DownloadManager
git pull
UPDATE:
'--set-upstream' option is no longer supported.
git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull
Windows
python -c "import pandas as pd; print(pd.__version__)"
conda list | findstr pandas # Anaconda / Conda
pip freeze | findstr pandas
pip show pandas | findstr Version
Linux
python -c "import pandas as pd; print(pd.__version__)"
conda list | grep numpy # Anaconda / Conda
pip freeze | grep numpy # pip
Use common sense really. If you have something like:
public class ScreenCoord2D{
public int x;
public int y;
}
Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down.
On the other hand, with:
public class BankAccount{
public int balance;
}
You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters.
It's always preferable to know why you're applying good practice, so that you know when it's ok to bend the rules.
I found this article at digital bazaar really interesting. Quoting their quotations from Norm:
About JSON pros:
If all you want to pass around are atomic values or lists or hashes of atomic values, JSON has many of the advantages of XML: it’s straightforwardly usable over the Internet, supports a wide variety of applications, it’s easy to write programs to process JSON, it has few optional features, it’s human-legible and reasonably clear, its design is formal and concise, JSON documents are easy to create, and it uses Unicode. ...
About XML pros:
XML deals remarkably well with the full richness of unstructured data. I’m not worried about the future of XML at all even if its death is gleefully celebrated by a cadre of web API designers.
And I can’t resist tucking an "I told you so!" token away in my desk. I look forward to seeing what the JSON folks do when they are asked to develop richer APIs. When they want to exchange less well strucured data, will they shoehorn it into JSON? I see occasional mentions of a schema language for JSON, will other languages follow? ...
I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)
You need something along the lines of this:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
Then you call expr.evaluate()
passing in the document defined in that code and the return type you are expecting, and cast the result to the object type of the result.
If you need help with a specific XPath expressions, you should probably ask it as separate questions (unless that was your question in the first place here - I understood your question to be how to use the API in Java).
Edit: (Response to comment): This XPath expression will get you the text of the first URL element under PowerBuilder:
/howto/topic[@name='PowerBuilder']/url/text()
This will get you the second:
/howto/topic[@name='PowerBuilder']/url[2]/text()
You get that with this code:
expr.evaluate(doc, XPathConstants.STRING);
If you don't know how many URLs are in a given node, then you should rather do something like this:
XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
And then loop over the NodeList.
I believe that the correct answer has already been posted and accepted, yet there is an issue that I have experienced myself and that some others have mentioned here.
On certain platforms, various properties such as window dimensions (window.innerWidth
, window.innerHeight
) and the window.orientation
property will not be updated by the time that the event "orientationchange"
has fired. Many times, the property window.orientation
is undefined
for a few milliseconds after the firing of "orientationchange"
(at least it is in Chrome on iOS).
The best way that I found to handle this issue was:
var handleOrientationChange = (function() {
var struct = function(){
struct.parse();
};
struct.showPortraitView = function(){
alert("Portrait Orientation: " + window.orientation);
};
struct.showLandscapeView = function(){
alert("Landscape Orientation: " + window.orientation);
};
struct.parse = function(){
switch(window.orientation){
case 0:
//Portrait Orientation
this.showPortraitView();
break;
default:
//Landscape Orientation
if(!parseInt(window.orientation)
|| window.orientation === this.lastOrientation)
setTimeout(this, 10);
else
{
this.lastOrientation = window.orientation;
this.showLandscapeView();
}
break;
}
};
struct.lastOrientation = window.orientation;
return struct;
})();
window.addEventListener("orientationchange", handleOrientationChange, false);
I am checking to see if the orientation is either undefined or if the orientation is equal to the last orientation detected. If either is true, I wait ten milliseconds and then parse the orientation again. If the orientation is a proper value, I call the showXOrientation
functions. If the orientation is invalid, I continue to loop my checking function, waiting ten milliseconds each time, until it is valid.
Now, I would make a JSFiddle for this, as I usually did, but JSFiddle has not been working for me and my support bug for it was closed as no one else is reporting the same problem. If anyone else wants to turn this into a JSFiddle, please go ahead.
Thanks! I hope this helps!
I believe this can help you:
$(document).ready(function(){
var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
for (var key in temp) {
alert('<option value=' + key + '>' + temp[key] + '</option>');
}
});
Using a free certificate is a better idea if your developers use Firefox 3. Firefox 3 complains loudly about self-signed certificates, and it is a major annoyance.
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
You should use this:
>mysql -u user -h 192.168.1.2 -P 3306 -ppassword
or this:
>mysql -u user -h 192.168.1.2 -ppassword
...because 3306 is a default port number.
Clearly there are lots of scenarios, however, I had same domain for document and iframe and I was able to tack this on to the end of my iframe content:
var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';
This 'finds' the parent container and then sets the length adding on a fudge factor of 50 pixels to remove the scroll bar.
There is nothing there to 'observe' the document height changing, this I did not need for my use case. In my answer I do bring a means of referencing the parent container without using ids baked into the parent/iframe content.
For other circumstances in which you want the number string to be consistent, I made a function.
Someone may find this useful:
idnamer<-function(x,y){#Alphabetical designation and number of integers required
id<-c(1:y)
for (i in 1:length(id)){
if(nchar(id[i])<2){
id[i]<-paste("0",id[i],sep="")
}
}
id<-paste(x,id,sep="")
return(id)
}
idnamer("EF",28)
Sorry about the formatting.
Select Custom Structure in permalinks and add /%category%/%postname%/ after your domain. Adding "/" to the category base doesn't work, you have to add a period/dot. I wrote a tutorial for this here: remove category from URL tutorial
Copy code using clone and appendTo function :
Here is also working example jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
$(function(){
$('#copy').clone().appendTo('#copied');
});
</script>
</body>
</html>
More generally, I think you might want to get "top" of the rows that are sorted within a given group.
For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).
# Answering the question of getting row with max "value".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in descending order by "value" column.
arrange( desc(value) ) %>%
# Pick the top 1 value
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
# Answering an extension of the question of
# getting row with the max value of the lowest "C".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in ascending order by C, and then within that by
# descending order by "value" column.
arrange( C, desc(value) ) %>%
# Pick the one top row based on the sort
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.
The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.
Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).
This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.
Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications
Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)
I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.
Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
No data in plot
gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
I've just came across the same problem and found the chrome extension Open IE.
That's the only one what works for me (Chrome V46 & V52). The only disadvantefge is, that you need to install an additional program, means you need admin rights.
Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.
THen, send your ip + port to the person who will use it.
I failed even if I tried to update the SDK tools as mentioned here.
Here is how I solved the problem (for the library projects imported).
In File -> Project Structure -> Modules, I removed the problematic projects, and added them again by selecting New Module -> Android Library Module.
After rebuilding the project, I got all the R.java
files back.
If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js
Check out the documentation on boundary conditions:
http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html
Check out this sample:
public static void main(final String[] args)
{
String x = "I found the value -12 in my string.";
System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
}
When you print it out, notice that the output is this:
[I found the value -, in my string.]
This means that the "-" character is not being picked up as being on the boundary of a word because it's not considered a word character. Looks like @brianary kinda beat me to the punch, so he gets an up-vote.
The problems is that dropboxes don't work the same as listboxes, at least the way ASP.NET MVC2 design expects: A dropbox allows only zero or one values, as listboxes can have a multiple value selection. So, being strict with HTML, that value shouldn't be in the option list as "selected" flag, but in the input itself.
See the following example:
<select id="combo" name="combo" value="id2">
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
<select id="listbox" name="listbox" multiple>
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
The combo has the option selected, but also has its value attribute set. So, if you want ASP.NET MVC2 to render a dropbox and also have a specific value selected (i.e., default values, etc.), you should give it a value in the rendering, like this:
// in my view
<%=Html.DropDownList("UserId", selectListItems /* (SelectList)ViewData["UserId"]*/, new { @Value = selectedUser.Id } /* Your selected value as an additional HTML attribute */)%>
This can be done using:
plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)
Take a look at the ListBox control to allow multi-select.
<asp:ListBox runat="server" ID="lblMultiSelect" SelectionMode="multiple">
<asp:ListItem Text="opt1" Value="opt1" />
<asp:ListItem Text="opt2" Value="opt2" />
<asp:ListItem Text="opt3" Value="opt3" />
</asp:ListBox>
in the code behind
foreach(ListItem listItem in lblMultiSelect.Items)
{
if (listItem.Selected)
{
var val = listItem.Value;
var txt = listItem.Text;
}
}
Just to add an example with parameters:
class B(A):
def __init__(self, x, y, z):
A.__init__(self, x, y)
Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.
This needs bash 4.1 if you use
{fd}
orlocal -n
.The rest should work in bash 3.x I hope. I am not completely sure due to
printf %q
- this might be a bash 4 feature.
Your example can be modified as follows to archive the desired effect:
# Add following 4 lines:
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
e=2
# Add following line, called "Annotation"
function test1_() { passback e; }
function test1() {
e=4
echo "hello"
}
# Change following line to:
capture ret test1
echo "$ret"
echo "$e"
prints as desired:
hello
4
Note that this solution:
e=1000
, too.$?
if you need $?
The only bad sideffects are:
bash
._
)_capture
just replace all occurances of 3
with another (higher) number.The following (which is quite long, sorry for that) hopefully explains, how to adpot this recipe to other scripts, too.
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
d1=$(d)
d2=$(d)
d3=$(d)
d4=$(d)
echo $x $d1 $d2 $d3 $d4
outputs
0 20171129-123521 20171129-123521 20171129-123521 20171129-123521
while the wanted output is
4 20171129-123521 20171129-123521 20171129-123521 20171129-123521
Shell variables (or generally speaking, the environment) is passed from parental processes to child processes, but not vice versa.
If you do output capturing, this usually is run in a subshell, so passing back variables is difficult.
Some even tell you, that it is impossible to fix. This is wrong, but it is a long known difficult to solve problem.
There are several ways on how to solve it best, this depends on your needs.
Here is a step by step guide on how to do it.
There is a way to pass back variables to a parental shell. However this is a dangerous path, because this uses eval
. If done improperly, you risk many evil things. But if done properly, this is perfectly safe, provided that there is no bug in bash
.
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; d=$(date +%Y%m%d-%H%M%S); _passback x d; }
x=0
eval `d`
d1=$d
eval `d`
d2=$d
eval `d`
d3=$d
eval `d`
d4=$d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-124945 20171129-124945 20171129-124945 20171129-124945
Note that this works for dangerous things, too:
danger() { danger="$*"; passback danger; }
eval `danger '; /bin/echo *'`
echo "$danger"
prints
; /bin/echo *
This is due to printf '%q'
, which quotes everything such, that you can re-use it in a shell context safely.
This does not only look ugly, it also is much to type, so it is error prone. Just one single mistake and you are doomed, right?
Well, we are at shell level, so you can improve it. Just think about an interface you want to see, and then you can implement it.
Let's go a step back and think about some API which allows us to easily express, what we want to do.
Well, what do we want do do with the d()
function?
We want to capture the output into a variable. OK, then let's implement an API for exactly this:
# This needs a modern bash 4.3 (see "help declare" if "-n" is present,
# we get rid of it below anyway).
: capture VARIABLE command args..
capture()
{
local -n output="$1"
shift
output="$("$@")"
}
Now, instead of writing
d1=$(d)
we can write
capture d1 d
Well, this looks like we haven't changed much, as, again, the variables are not passed back from d
into the parent shell, and we need to type a bit more.
However now we can throw the full power of the shell at it, as it is nicely wrapped in a function.
A second thing is, that we want to be DRY (Don't Repeat Yourself). So we definitively do not want to type something like
x=0
capture1 x d1 d
capture1 x d2 d
capture1 x d3 d
capture1 x d4 d
echo $x $d1 $d2 $d3 $d4
The x
here is not only redundant, it's error prone to always repeate in the correct context. What if you use it 1000 times in a script and then add a variable? You definitively do not want to alter all the 1000 locations where a call to d
is involved.
So leave the x
away, so we can write:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; output=$(date +%Y%m%d-%H%M%S); _passback output x; }
xcapture() { local -n output="$1"; eval "$("${@:2}")"; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
This already looks very good. (But there still is the local -n
which does not work in oder common bash
3.x)
d()
The last solution has some big flaws:
d()
needs to be alteredxcapture
to pass the output.
output
,
so we can never pass this one back._passback
Can we get rid of this, too?
Of course, we can! We are in a shell, so there is everything we need to get this done.
If you look a bit closer to the call to eval
you can see, that we have 100% control at this location. "Inside" the eval
we are in a subshell,
so we can do everything we want without fear of doing something bad to the parental shell.
Yeah, nice, so let's add another wrapper, now directly inside the eval
:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
# !DO NOT USE!
_xcapture() { "${@:2}" > >(printf "%q=%q;" "$1" "$(cat)"); _passback x; } # !DO NOT USE!
# !DO NOT USE!
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
However, this, again, has some major drawback:
!DO NOT USE!
markers are there,
because there is a very bad race condition in this,
which you cannot see easily:
>(printf ..)
is a background job. So it might still
execute while the _passback x
is running.sleep 1;
before printf
or _passback
.
_xcapture a d; echo
then outputs x
or a
first, respectively._passback x
should not be part of _xcapture
,
because this makes it difficult to reuse that recipe.$(cat)
),
but as this solution is !DO NOT USE!
I took the shortest route.However, this shows, that we can do it, without modification to d()
(and without local -n
)!
Please note that we not neccessarily need _xcapture
at all,
as we could have written everyting right in the eval
.
However doing this usually isn't very readable. And if you come back to your script in a few years, you probably want to be able to read it again without much trouble.
Now let's fix the race condition.
The trick could be to wait until printf
has closed it's STDOUT, and then output x
.
There are many ways to archive this:
Following the last path could look like (note that it does the printf
last because this works better here):
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_xcapture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; _passback x >&3)"; } 3>&1; }
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-144845 20171129-144845 20171129-144845 20171129-144845
Why is this correct?
_passback x
directly talks to STDOUT.>&3
.$("${@:2}" 3<&-; _passback x >&3)
finishes after the _passback
,
when the subshell closes STDOUT.printf
cannot happen before the _passback
,
regardless how long _passback
takes.printf
command is not executed before the complete
commandline is assembled, so we cannot see artefacts from printf
,
independently how printf
is implemented.Hence first _passback
executes, then the printf
.
This resolves the race, sacrificing one fixed file descriptor 3. You can, of course, choose another file descriptor in the case, that FD3 is not free in your shellscript.
Please also note the 3<&-
which protects FD3 to be passed to the function.
_capture
contains parts, which belong to d()
, which is bad,
from a reusability perspective. How to solve this?
Well, do it the desparate way by introducing one more thing,
an additional function, which must return the right things,
which is named after the original function with _
attached.
This function is called after the real function, and can augment things. This way, this can be read as some annotation, so it is very readable:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_capture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; "$2_" >&3)"; } 3>&1; }
capture() { eval "$(_capture "$@")"; }
d_() { _passback x; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
capture d1 d
capture d2 d
capture d3 d
capture d4 d
echo $x $d1 $d2 $d3 $d4
still prints
4 20171129-151954 20171129-151954 20171129-151954 20171129-151954
There is only on bit missing:
v=$(fn)
sets $?
to what fn
returned. So you probably want this, too.
It needs some bigger tweaking, though:
# This is all the interface you need.
# Remember, that this burns FD=3!
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
# Here is your function, annotated with which sideffects it has.
fails_() { passback x y; }
fails() { x=$1; y=69; echo FAIL; return 23; }
# And now the code which uses it all
x=0
y=0
capture wtf fails 42
echo $? $x $y $wtf
prints
23 42 69 FAIL
_passback()
can be elmininated with passback() { set -- "$@" "$?"; while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
_capture()
can be eliminated with capture() { eval "$({ out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)")"; }
The solution pollutes a file descriptor (here 3) by using it internally.
You need to keep that in mind if you happen to pass FDs.
Note thatbash
4.1 and above has {fd}
to use some unused FD.
(Perhaps I will add a solution here when I come around.)
Note that this is why I use to put it in separate functions like _capture
, because stuffing this all into one line is possible, but makes it increasingly harder to read and understand
Perhaps you want to capture STDERR of the called function, too.
Or you want to even pass in and out more than one filedescriptor
from and to variables.
I have no solution yet, however here is a way to catch more than one FD, so we can probably pass back the variables this way, too.
Also do not forget:
This must call a shell function, not an external command.
There is no easy way to pass environment variables out of external commands. (With
LD_PRELOAD=
it should be possible, though!) But this then is something completely different.
This is not the only possible solution. It is one example to a solution.
As always you have many ways to express things in the shell. So feel free to improve and find something better.
The solution presented here is quite far from being perfect:
bash
, so probably is hard to port to other shells.However I think it is quite easy to use:
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.
Shorter version for those who like short code:
// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)
function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {
// $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age
foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) {
if (is_writable($f) && filemtime($f) < (time() - $timeout))
unlink($f);
}
}
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
string literals are non-modifiable in C
Sometimes storage not available is also should be mention because I face this issue because that the device that needs to be installed doesn't have enough space and also the system is not alert to the user. You can just find out because of debugging
Add a background Drawable like res/drawables/background.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white" />
<stroke android:width="1dp" android:color="@android:color/black" />
</shape>
Update the ImageView background in res/layout/foo.xml:
...
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dp"
android:background="@drawable/background"
android:src="@drawable/bar" />
...
Exclude the ImageView padding if you want the src to draw over the background.
you can use the collector like this
Stream<String> io = Stream.of("foo" , "lan" , "mql");
io.collect(Collectors.toCollection(ArrayList<String>::new));
in the first you should make form like this :
<form method="post" enctype="multipart/form-data" >
<input type="file" name="file[]" multiple id="file"/>
<input type="submit" name="ok" />
</form>
that is right . now add this code under your form code or on the any page you like
<?php
if(isset($_POST['ok']))
foreach ($_FILES['file']['name'] as $filename) {
echo $filename.'<br/>';
}
?>
it's easy... finish
This question is some years old but i came via a duplicate to it. I want to suggest a more general solution too. If you know you always have a fixed number of ancestors you can use some self joins as already suggested in the answers. If you want a generic approach go on reading.
What you need here is called Quotient in relational Algebra. The Quotient is more or less the reversal of the Cartesian Product (or Cross Join in SQL).
Let's say your ancestor set A
is (i use a table notation here, i think this is better for understanding)
ancestry
-----------
'England'
'France'
'Germany'
and your user set U
is
user_id
--------
1
2
3
The cartesian product C=AxU
is then:
user_id | ancestry
---------+-----------
1 | 'England'
1 | 'France'
1 | 'Germany'
2 | 'England'
2 | 'France'
2 | 'Germany'
3 | 'England'
3 | 'France'
3 | 'Germany'
If you calculate the set quotient U=C/A
then you get
user_id
--------
1
2
3
If you redo the cartesian product UXA
you will get C
again. But note that for a set T
, (T/A)xA
will not necessarily reproduce T
. For example, if T
is
user_id | ancestry
---------+-----------
1 | 'England'
1 | 'France'
1 | 'Germany'
2 | 'England'
2 | 'France'
then (T/A)
is
user_id
--------
1
(T/A)xA
will then be
user_id | ancestry
---------+------------
1 | 'England'
1 | 'France'
1 | 'Germany'
Note that the records for user_id=2
have been eliminated by the Quotient and Cartesian Product operations.
Your question is: Which user_id has ancestors from all countries in your ancestor set? In other words you want U=T/A
where T
is your original set (or your table).
To implement the quotient in SQL you have to do 4 steps:
So let's do it step by step. I will use TSQL syntax (Microsoft SQL server) but it should easily be adaptable to other DBMS. As a name for the table (user_id, ancestry)
i choose ancestor
CREATE TABLE ancestry_set (ancestry nvarchar(25))
INSERT INTO ancestry_set (ancestry) VALUES ('England')
INSERT INTO ancestry_set (ancestry) VALUES ('France')
INSERT INTO ancestry_set (ancestry) VALUES ('Germany')
CREATE TABLE ancestor ([user_id] int, ancestry nvarchar(25))
INSERT INTO ancestor ([user_id],ancestry) VALUES (1,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(1,'Ireland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(2,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Poland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'Germany')
1) Create the Cartesian Product of your ancestry set and the set of all user_ids.
SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry
2) Find all records in the Cartesian Product which have no partner in the original set (Left Join) and
3) Extract the user_ids from the resultset of 2)
SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry) cp
LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null
4) Return all user_ids from the original set which are not included in the result set of 3)
SELECT DISTINCT [user_id]
FROM ancestor
WHERE [user_id] NOT IN (
SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry) cp
LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null
)
You cannot - a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
These are really two separate, distinctive parts of the equation. For simplicity's sake you would often import your XSD definitions into the WSDL in the <wsdl:types>
tag.
(thanks to Cheeso for pointing out my inaccurate usage of terms)
You can do this with plain js by using
location.host
, same as document.location.hostname
The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow
is deprecated since Tomcat 8.5: tomcat official doc.
You can use relaxedQueryChars / relaxedPathChars
in the connectors definition to allow these chars: tomcat official doc.
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
Simplistically malloc
and free
work like this:
malloc
provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.
Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.
When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.
When one calls malloc
, memory is taken from the large heap cell, which is returned by malloc
. The rest is formed into a new heap cell that consists of all the rest of the memory.
When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc
's walk the free list looking for a cell of suitable size.
As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.
When there is no memory left on the free list for a desired allocation, malloc
calls brk
or sbrk
which are the system calls requesting more memory pages from the operating system.
Now there are a few modification to optimize heap operations.
On Mac you need cmd + / to comment and uncomment.
I think my code (tested) is more "educated", assuming the simpler the better.
Option Base 1
'Function to sort an array decscending
Function SORT(Rango As Range) As Variant
Dim check As Boolean
check = True
If IsNull(Rango) Then
check = False
End If
If check Then
Application.Volatile
Dim x() As Variant, n As Double, m As Double, i As Double, j As Double, k As Double
n = Rango.Rows.Count: m = Rango.Columns.Count: k = n * m
ReDim x(n, m)
For i = 1 To n Step 1
For j = 1 To m Step 1
x(i, j) = Application.Large(Rango, k)
k = k - 1
Next j
Next i
SORT = x
Else
Exit Function
End If
End Function
const Console = prop => (
console[Object.keys(prop)[0]](...Object.values(prop))
,null // ? React components must return something
)
// Some component with JSX and a logger inside
const App = () =>
<div>
<p>imagine this is some component</p>
<Console log='foo' />
<p>imagine another component</p>
<Console warn='bar' />
</div>
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Ok - I thought this was going to work for me. However, if you use it to add a day to the 31st March 2013, it'll return a date that has only 23 hours added to it. It may well actually have the 24, but using in calculations has only 23:00 hours added.
Similarly, if you blast forward to 28th Oct 2013, the code adds 25 hours resulting in a date time of 2013-10-28 01:00:00.
In order to add a day I was doing the thing at the top, adding the:
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
Complicated, principally due to daylight saving.
Intellij IDEA 2017.3.4 - 2018.2 (Ultimate) on OSX
CMD + fn + F12
will show all members of the current class in a popup window, then you can search method in that class.
BUT, this answer is depends on your Keyboard setting. If your keyboard setting in
System Preferences > Keyboard > Use all F1, F2, etc. keys as standard function keys
is selected, then the shortcut becomes
CMD + F12
Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.
SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
AND CompletedDate in
(Select Max(CompletedDate) from HR_EmployeeTrainings B
where B.TrainingID = ET.TrainingID)
If you also want to match by AntiRecID you should include that in the subselect as well.
I just want to present a more recent alternative. There is an online tool that generates .gitignore
files based on operating systems, IDEs and programming languages that you might be using.
EDIT Disclaimer: Do not copy this file, copy the file generated by the website instead, they do a good job on keeping it updated. This is just an example.
The file generated for IntelliJ
contains the following
# Created by https://www.gitignore.io/api/intellij
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
I've found String.fromCharCode(13, 10)
helpful when using view engines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:
viewHelper.js
exports.replaceNewline = function(input) {
var newline = String.fromCharCode(13, 10);
return input.replaceAll('\\n', newline);
}
EJS
<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>
Renders
<textarea>Blah
blah
blah</textarea>
replaceAll:
String.prototype.replaceAll = function (find, replace) {
var result = this;
do {
var split = result.split(find);
result = split.join(replace);
} while (split.length > 1);
return result;
};
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
As an alternate to adding a comma for each item you could just using String.Join:
var strgroupids = String.Join(",", groupIds);
This will add the seperator ("," in this instance) between each element in the array.
I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.
Mates,
I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this
try{
foo();
}
catch (exception $e)
{
echo "$e->getMessage()";
}
function foo(){
echo "blah blah blah";
}
so php was throwing me error "call to undefined function ".
This kinda seem classic programming error but may help someone in need of clue.
I liked @KyleMit's answer on how to make an unstyled input group, but in my case, I only wanted the right side unstyled - I still wanted to use an input-group-addon on the left side and have it look like normal bootstrap. So, I did this:
css
.input-group.input-group-unstyled-right input.form-control {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.input-group-unstyled-right .input-group-addon.input-group-addon-unstyled {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
html
<div class="input-group input-group-unstyled-right">
<span class="input-group-addon">
<i class="fa fa-envelope-o"></i>
</span>
<input type="text" class="form-control">
<span class="input-group-addon input-group-addon-unstyled">
<i class="fa fa-check"></i>
</span>
</div>
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
$sess = session_status();
if ($sess == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
Actually, it is now too late to explain it here anyway as its been solved. This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order. The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.
With ssh key based authentication enabled, the following script would work.
for x in `ssh user@remotehost 'find /usr/some -type f -name *.class'`; do y=$(echo $x|sed 's/.[^/]*$//'|sed "s/^\/usr//"); mkdir -p /usr/project/backup$y; scp $(echo 'user@remotehost:'$x) /usr/project/backup$y/; done
It's very simple. Use numpy slicing.
import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
Press Ctrl+,
Then you will see a docked window under name of "Go to all"
This a picture of the "Go to all" in my IDE
This one was perfect for me. Keeps aspect ratio and takes a maxLength
. Width or Height will not be more than maxLength
-(UIImage*)imageWithImage: (UIImage*) sourceImage maxLength: (float) maxLength
{
CGFloat scaleFactor = maxLength / MAX(sourceImage.size.width, sourceImage.size.height);
float newHeight = sourceImage.size.height * scaleFactor;
float newWidth = sourceImage.size.width * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Suppose we have a API Controller ProductsController : ApiController
There is a Get function which returns some value and expects some input header (for eg. UserName & Password)
[HttpGet]
public IHttpActionResult GetProduct(int id)
{
System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
string token = string.Empty;
string pwd = string.Empty;
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
if (headers.Contains("password"))
{
pwd = headers.GetValues("password").First();
}
//code to authenticate and return some thing
if (!Authenticated(token, pwd)
return Unauthorized();
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
Now we can send the request from page using JQuery:
$.ajax({
url: 'api/products/10',
type: 'GET',
headers: { 'username': 'test','password':'123' },
success: function (data) {
alert(data);
},
failure: function (result) {
alert('Error: ' + result);
}
});
Hope this helps someone ...
An ftl file could just have a series of html tags just as a JSP page or it can have freemarker template coding for representing the objects passed on from a controller java file.
But, its actual ability is to combine the contents of a java class and view/client side stuff(html/ JQuery/ javascript etc). It is quite similar to velocity. You could map a method or object of a class to a freemarker (.ftl) page and use it as if it is a variable or a functionality created in the very page.
The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.
However the first approach should work just fine, if and only if getAllTasks return an ArrayList.
It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.
If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.
public class VcareSharedPreference {
private static VcareSharedPreference sharePref = new VcareSharedPreference();
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private VcareSharedPreference() {
}
public static VcareSharedPreference getInstance(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
return sharePref;
}
public void save(String KEY, String text) {
editor.putString(KEY, text);
editor.commit();
}
public String getValue(String PREFKEY) {
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
text = sharedPreferences.getString(PREFKEY, null);
return text;
}
public void removeValue(String KEY) {
editor.remove(KEY);
editor.commit();
}
public void clearAll() {
editor.clear();
editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
Gson gson = new Gson();
String json = gson.toJson(modelCourses);
editor.putString(key, json);
editor.apply();
}
public ArrayList<ModelWelcome> getArray(String key) {
Gson gson = new Gson();
String json = sharedPreferences.getString(key, null);
Type type = new TypeToken<ArrayList<ModelWelcome>>() {
}.getType();
return gson.fromJson(json, type);}}
You should NOT use jQuery('selector').attr("tagName").toLowerCase()
, because it only works in older versions of Jquery.
You could use $('selector').prop("tagName").toLowerCase()
if you're certain that you're using a version of jQuery thats >= version 1.6.
You may think that EVERYONE is using jQuery 1.10+ or something by now (January 2016), but unfortunately that isn't really the case. For example, many people today are still using Drupal 7, and every official release of Drupal 7 to this day includes jQuery 1.4.4 by default.
So if do not know for certain if your project will be using jQuery 1.6+, consider using one of the options that work for ALL versions of jQuery :
Option 1 :
jQuery('selector')[0].tagName.toLowerCase()
Option 2
jQuery('selector')[0].nodeName.toLowerCase()
well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)
lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents
(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )
If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.
String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}
Google have new maven repo
https://android-developers.googleblog.com/2017/10/android-studio-30.html > section Google's Maven Repository
https://developer.android.com/studio/preview/features/new-android-plugin-migration.html https://developer.android.com/studio/build/dependencies.html#google-maven
So add the dependency on maven repo:
buildscript {
repositories {
...
// You need to add the following repository to download the
// new plugin.
google() // new which replace https://maven.google.com
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3' //Minimum supported Gradle version is 4.6.
}
}
Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See this page for a handy table of access level modifiers...
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
Here is the simple code snippet to upload a single file with additional parameters using requests:
url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'
files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}
response = requests.put(url, files=files, data=payload, verify=False)
Please note that you don't need to explicitly specify any content type.
NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.
just had this problem, but for mobile devices, mainly mobile firefox. The trick for me was to define a height, padding, line height, and finally box sizing, all on the select element. Not using your example numbers here, but for the sake of an example:
padding: 20px;
height: 60px;
line-height: 1;
-webkit-box-sizing: padding-box;
-moz-box-sizing: padding-box;
box-sizing: padding-box;
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
You must group both columns, group and sub-group, then use the aggregate function COUNT()
.
SELECT
group, subgroup, COUNT(*)
FROM
groups
GROUP BY
group, subgroup
jQuery(function ($) {
$('li#linkss').find('a').on('click', function (e) {
var
link_href = $(this).attr('href')
, $linkElem = $(link_href)
, $linkElem_scroll = $linkElem.get(0) && $linkElem.position().top - 115;
$('html, body')
.animate({
scrollTop: $linkElem_scroll
}, 'slow');
e.preventDefault();
});
});
You can go with option 3 if you modify your abstract base class to require the property value in the constructor, you won't miss any paths. I'd really consider this option.
abstract class Aunt
{
protected int MyInt;
protected Aunt(int myInt)
{
MyInt = myInt;
}
}
Of course, you then still have the option of making the field private and then, depending on the need, exposing a protected or public property getter.
Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
on the p element, add 3 styling rules.
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
As long as UITableView is not the first subview of the view controller, the empty space will not appear.
Solution: Add a hidden/clear view object (views, labels, button, etc.) as the first subview of the view controller (at the same level as the UITableView but before it).
You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python - for good reason!
The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! ;-)
And if you would tell us what your real problem is, you might even get a pythonic answer. "Getting something in one line" us usually not a programming problem.
This will require Node.js 7 or later with a support for Promises and Async/Await.
Create a wrapper function that leverage promises to control the behavior of the child_process.exec
command.
Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await
keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec
done.
const childProcess = require("child_process");
/**
* @param {string} command A shell command to execute
* @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
* @example const output = await execute("ls -alh");
*/
function execute(command) {
/**
* @param {Function} resolve A function that resolves the promise
* @param {Function} reject A function that fails the promise
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
*/
return new Promise(function(resolve, reject) {
/**
* @param {Error} error An error triggered during the execution of the childProcess.exec command
* @param {string|Buffer} standardOutput The result of the shell command execution
* @param {string|Buffer} standardError The error resulting of the shell command execution
* @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
*/
childProcess.exec(command, function(error, standardOutput, standardError) {
if (error) {
reject();
return;
}
if (standardError) {
reject(standardError);
return;
}
resolve(standardOutput);
});
});
}
async function main() {
try {
const passwdContent = await execute("cat /etc/passwd");
console.log(passwdContent);
} catch (error) {
console.error(error.toString());
}
try {
const shadowContent = await execute("cat /etc/shadow");
console.log(shadowContent);
} catch (error) {
console.error(error.toString());
}
}
main();
root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]
Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
$ pip install django-tables2
settings.py
INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'
models.py
class hotel(models.Model):
name = models.CharField(max_length=20)
views.py
from django.shortcuts import render
def people(request):
istekler = hotel.objects.all()
return render(request, 'list.html', locals())
list.html
{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{% static
'ticket/static/css/screen.css' %}" />
</head>
<body>
{% render_table istekler %}
</body>
</html>
The error message is completely correct. I tried all the tricks and none worked. The project (simple MVC Web App test) moved from Windows 8.1 VS 2015 Community to my new test box on Windows 10. All the latest updates to VS 2015 applied. I could not even install any newer version of the compilers package.
Loop:
<LOOP>This seems to be a Ground Hog Day phenomena.</LOOP>
GoTo Loop
I finally just copied Microsoft.Net.Compilers.1.0.0 from the old project into the new one and it worked. I could then start to update other packages to newer version. Looks like a nuget project upgrade process bug to me.
NOTE: The original project was created in VS 2015 and does not have any legacy nuget methodologies.
You can also create a new document from MongoDB compass or using command and set the specific _id
value that you want.
Use Directly like this
.bg-div{
background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}
or call CSS separately like
.bg-div{
background-image: url(../img/beach.jpg);
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
In case none of the aforementioned solutions works for you, then simply do the under changes. Change this
$cfg['Servers'][$i]['host'] = '127.0.0.1';
to
$cfg['Servers'][$i]['host'] = 'localhost';
and
$cfg['Servers'][$i]['auth_type'] = 'config';
to
$cfg['Servers'][$I]['auth_type'] ='cookies';
It works in my situation, possibly works on your situation also.
I noticed creation of 'appcompat' library while creating new android project with ADT 22.6.2 version, even when the minSDK was set to 11 and targetSDK was set 19
This was happening because, in the new project template android is using some attributes that are from the support library. For instance if a new project was created with actionbar then in the menu's main.xml one could find app:showAsAction="never"
which is from support library.
android:showAsAction
in menu's main.xmlAlso the default theme set could be "Theme.AppCompat.Light.DarkActionBar" as shown below (styles.xml)
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
In this case the parent theme in style.xml has to be changed to "android:style/Theme.Holo.Light.DarkActionBar"
data.reindex(index=data.index[::-1])
or simply:
data.iloc[::-1]
will reverse your data frame, if you want to have a for
loop which goes from down to up you may do:
for idx in reversed(data.index):
print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
or
for idx in reversed(data.index):
print(idx, data.Even[idx], data.Odd[idx])
You are getting an error because reversed
first calls data.__len__()
which returns 6. Then it tries to call data[j - 1]
for j
in range(6, 0, -1)
, and the first call would be data[5]
; but in pandas dataframe data[5]
means column 5, and there is no column 5 so it will throw an exception. ( see docs )
For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
Depends on what your are doing.
If you have SPA (Single-Page Application) the you can use:
<input id="txtName" type="text" />
Otherwise using Html helpers is recommended, to get your controls bound with your model.
Check that the version of php you're running matches your codebase. For example, your local environment may be running php 5.4 (and things run fine) and maybe you're testing your code on a new machine that has php 5.3 installed. If you are using 5.4 syntax such as [] for array() then you'll get the situation you described above.
I ended up with a custom extension method. Its worth noting, when trying to place HTML inside of an Anchor object, the link text can be either to the left, or to the right of the inner HTML. For this reason, I opted to provide parameters for left and right inner HTML - the link text is in the middle. Both left and right inner HTML are optional.
Extension Method ActionLinkInnerHtml:
public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
{
// CONSTRUCT THE URL
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);
// CREATE AN ANCHOR TAG BUILDER
var builder = new TagBuilder("a");
builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
builder.MergeAttribute(key: "href", value: url);
// ADD HTML ATTRIBUTES
builder.MergeAttributes(htmlAttributes, replaceExisting: true);
// BUILD THE STRING AND RETURN IT
var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
return mvcHtmlString;
}
Example of Usage:
Here is an example of usage. For this example I only wanted the inner html on the right side of the link text...
@Html.ActionLinkInnerHtml(
linkText: "Hello World"
, actionName: "SomethingOtherThanIndex"
, controllerName: "SomethingOtherThanHome"
, rightInnerHtml: "<span class=\"caret\" />"
)
Results:
this results in the following HTML...
<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>
ruby-dev
is installedmake
is installedgem install pg
you will also need to install the lib libpq-dev
(sudo apt-get install libpq-dev
).(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)
This will mach all images from this string:
background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;
<div id="divbg" style="background-color:#ff0000"><img id="bg" src="../res/img/temp/634043/original/cc3d8715eed0c.jpg" width="100%" height="100%" /></div>
background-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);
background: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3 _d8715eed0c.jpg) repeat fixed left top; cursor: auto;
background: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;
Test your regex here: https://regex101.com/r/l2Zt7S/1
There are 3 ways to that, i mention them in order of being the better way...
1-HTML way:
<input type="text" autocomplete="false" />
2-Javascript way:
document.getElementById("input-id").getAttribute("autocomplete") = "off";
3-jQuery way:
$('input').attr('autocomplete','off');
The pythonic way.
print "".join([ c if c.isalnum() else "*" for c in s ])
This doesn't deal with grouping multiple consecutive non-matching characters though, i.e.
"h^&i => "h**i
not "h*i"
as in the regex solutions.
Based on the inputs provided by @equiman
class _Scheduler {
timeoutIDs;
constructor() {
this.timeoutIDs = new Map();
}
addCallback = (callback, timeLapseMS, autoRemove) => {
if (!this.timeoutIDs.has(timeLapseMS + callback)) {
let timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
}
if (autoRemove !== false) {
setTimeout(
this.removeIdleTimeCallback, // Remove
10000 + timeLapseMS, // 10 secs after
callback, // the callback
timeLapseMS, // is invoked.
);
}
};
removeCallback = (callback, timeLapseMS) => {
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
if (timeoutID) {
clearTimeout(timeoutID);
this.timeoutIDs.delete(timeLapseMS + callback);
}
};
}
class _IdleTimeScheduler extends _Scheduler {
events = [
'load',
'mousedown',
'mousemove',
'keydown',
'keyup',
'input',
'scroll',
'touchstart',
'touchend',
'touchcancel',
'touchmove',
];
callbacks;
constructor() {
super();
this.events.forEach(name => {
document.addEventListener(name, this.resetTimer, true);
});
this.callbacks = new Map();
}
addIdleTimeCallback = (callback, timeLapseMS) => {
this.addCallback(callback, timeLapseMS, false);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (!callbacksArr) {
this.callbacks.set(timeLapseMS, [callback]);
} else {
if (!callbacksArr.includes(callback)) {
callbacksArr.push(callback);
}
}
};
removeIdleTimeCallback = (callback, timeLapseMS) => {
this.removeCallback(callback, timeLapseMS);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (callbacksArr) {
let index = callbacksArr.indexOf(callback);
if (index !== -1) {
callbacksArr.splice(index, 1);
}
}
};
resetTimer = () => {
for (let [timeLapseMS, callbacksArr] of this.callbacks) {
callbacksArr.forEach(callback => {
// Clear the previous IDs
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
clearTimeout(timeoutID);
// Create new timeout IDs.
timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
});
}
};
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();
I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}
An example of how you might use this:
var test = JoinDataTables(transactionInfo, transactionItems,
(row1, row2) =>
row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));
One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.
Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.
At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.
If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....
var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');
if(startDate > endDate){
// do your stuff here...
}
You can use tail
:
$ foo="1234567890"
$ echo -n $foo | tail -c 3
890
A somewhat roundabout way to get the last three characters would be to say:
echo $foo | rev | cut -c1-3 | rev
Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
Another variant:
private String getCharForNumber(int i) {
if (i > 25 || i < 0) {
return null;
}
return new Character((char) (i + 65)).toString();
}
New class ViewPager2 from androidx allows to disable scrolling with method setUserInputEnabled(false)
private val pager: ViewPager2 by bindView(R.id.pager)
override fun onCreate(savedInstanceState: Bundle?) {
pager.isUserInputEnabled = false
}
If you put this on onDestroy or onStop method. I think that when the activity has been created again the MessageReciver wasn't being created.
@Override
public void onDestroy (){
super.onDestroy();
LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);
}
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.
Check this:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
If you are using jQuery library, it can be even easier:
http://api.jquery.com/jQuery.ajax/
Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.
Hope that helps.
Tuples will be (are) in .Net 4.0 Until then, you can also use a
Dictionary<key1, Dictionary<key2, TypeObject>>
or, creating a custom collection class to represent this...
public class TwoKeyDictionary<K1, K2, T>:
Dictionary<K1, Dictionary<K2, T>> { }
or, with three keys...
public class ThreeKeyDictionary<K1, K2, K3, T> :
Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }
You need to git push -f
assuming that nobody has pulled the other commit before. Beware, you're changing history.
Just put the following below your form. Make sure your input fields are required
.
<script>
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
forms[i].noValidate = true;
forms[i].addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
alert("Please complete all fields and accept the terms.");
}
}, false);
}
</script>
As of jQuery 1.7, the .live()
method is deprecated. Use .on()
to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
In an easy language,
1. A description of an Intent and Target action to perform. First you have to create an intent and then you have to pass an specific java class which you want to execute, to the Intent.
2. You can call those java class which is your class action class by PendingIntent.getActivity, PendingIntent.getActivities(Context, int, Intent[], int), PendingIntent.getBroadcast(Context, int, Intent, int), and PendingIntent.getService(Context, int, Intent, int);
Here you see that Intent which is comes from the step 1
3. You should keep in mind that...By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified.
That is what I learned after a long reading.
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
You may need to install ATL if your COM objects use ATL, as described by this KB article:
http://support.microsoft.com/kb/201191
These libraries will probably have to be supplied by developers to ensure the correct version.
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Since Java 7 you can use java.util.Objects.equals(Object a, Object b):
These utilities include null-safe or null-tolerant methods
Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));
>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'
To get the specific values you've listed:
>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')
See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.
Run this in your browser console of choice.
if(jQuery().pluginName){console.log('bonjour');}
If the plugin exists it will print out "bonjour" as a response in your console.
Symfony 2.7 has a new absolute_url which can be used to generate the absolute url. http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes
It will work on those both cases or a path string:
<a href="{{ absolute_url(path('route_name', {'param' : value})) }}">A link</a>
and for assets:
<img src="{{ absolute_url(asset('bundle/myname/img/image.gif')) }}" alt="Title"/>
Or for any string path
<img src="{{ absolute_url('my/absolute/path') }}" alt="Title"/>
on those tree cases you will end up with an absolute URL like
http://www.example.com/my/absolute/path
leak prone
I've decided to chime in. The performance impact includes: disk operation + unzip (for jar), class verification, perm-gen space (for Sun's Hotspot JVM). However, worst of all: it's leak prone. You can't simply return.
Set<String> getFlavors(){
return Collections.unmodifiableSet(flavors)
}
So if the set escapes to any other part loaded by a different classloader and a reference is kept there, the entire tree of classes+classloader will be leaked. To avoid that, a copy to HashMap is necessary, new LinkedHashSet(new ArrayList(){{add("xxx);add("yyy");}})
. Not so cute any more.
I don't use the idiom, myself, instead it is like new LinkedHashSet(Arrays.asList("xxx","YYY"));