This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
This happened to me as well. For me, Postfix was located at the same server as the PHP script, and the error was happening when I would be using SMTP authentication and smtp.domain.com instead of localhost.
So when I commented out these lines:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
and set the host to
$mail->Host = "localhost";
instead
$mail->Host = 'smtp.mydomainiuse.com'
and it worked :)
Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.
PowerShell - List local user accounts
Fast way
Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | select name, fullname
Slow way
Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
I know this is an older question, but none of the above answers worked for me. In my case, the issue turned out to be that I had absolute include paths but without drive letters. Compilation was fine, but Visual Studio couldn't find an include file when I right-clicked and tried to open it. Adding the drive letters to my include paths corrected the problem.
I would never recommend hard-coding drive letters in any aspect of your project files; either use relative paths, macros, environment variables, or some mix of the tree for any permanent situation. However, in this case, I'm working in some temporary projects where absolute paths were necessary in the short term. Not being able to right-click to open the files was extremely frustrating, and hopefully this will help others.
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
Here's extension method to convert DataTable to object list:
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
if(row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
}
usage:
List<Employee> lst = ds.Tables[0].ToList<Employee>();
@itay.b
CODE EXPLAINED:
We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.
The property values are picked from the row's matching column cell.
PS: class property name and table column names must be same
I use this for government fiscal years where Q4 starts October 1st. Note I convert the date into quarters and undo it as well.
import pandas as pd
df['Date'] = '1/1/2020'
df['Date'] = pd.to_datetime(df['Date']) #returns 2020-01-01
df['NewDate'] = df.Date - pd.DateOffset(months=3) #returns 2019-10-01 <---- answer
# For fun, change it to FY Quarter '2019Q4'
df['NewDate'] = df['NewDate'].dt.year.astype(str) + 'Q' + df['NewDate'].dt.quarter.astype(str)
# Convert '2019Q4' back to 2019-10-01
df['NewDate'] = pd.to_datetime(df.NewDate)
You can accomplish it with INSERT as below:
INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);
This insert new values into table, but if primary key is duplicated (already inserted into table) that values you specify would be updated and same record would not be inserted second time.
new Chart('idName', {
type: 'typeChar',
data: data,
options: {
legend: {
display: false
}
}
});
As it is written in the documentation you have to change the cell type to a markdown.
img {
max-width: 100%;
}
Should set the image to take up 100% of its containing element.
MongoDB 3.6 include $expr https://docs.mongodb.com/manual/reference/operator/query/expr/
You can use $expr in order to evaluate an expression inside a $match, or find.
{ $match: {
$expr: {$gt: [{$size: "$yourArrayField"}, 0]}
}
}
or find
collection.find({$expr: {$gte: [{$size: "$yourArrayField"}, 0]}});
An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view
Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'
The best way to do this:
ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
I'm not really a fan of the most-upvoted answer here (in part because it seems like it isn't correct since it should continue
if it reads a null terminator in either string--but not both strings at once--and it doesn't do this), so I wrote my own.
strncmp()
, and has been tested with numerous test cases, as shown below.It is identical to strncmp()
except:
strncmp()
has undefined behavior if either string is a null ptr (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).INT_MIN
as a special sentinel error value if either input string is a NULL
ptr.LIMITATIONS: Note that this code works on the original 7-bit ASCII character set only (decimal values 0 to 127, inclusive), NOT on unicode characters, such as unicode character encodings UTF-8 (the most popular), UTF-16, and UTF-32.
Here is the code only (no comments):
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Fully-commented version:
/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`, so
// long as 1st: we have not yet compared the requested number of chars, and 2nd: the next char
// of at least *one* of the strings is not zero (the null terminator for a C-string), meaning
// that string still has more characters in it.
// Note: you MUST check `(chars_compared < num)` FIRST or else dereferencing (reading) `str1` or
// `str2` via `*str1` and `*str2`, respectively, is undefined behavior if you are reading one or
// both of these C-strings outside of their array bounds.
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Download the entire sample code, with unit tests, from my eRCaGuy_hello_world repository here: "strncmpci.c":
(this is just a snippet)
int main()
{
printf("-----------------------\n"
"String Comparison Tests\n"
"-----------------------\n\n");
int num_failures_expected = 0;
printf("INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!\n");
EXPECT_EQUALS(strncmpci("hey", "HEY", 3), 'h' - 'H');
num_failures_expected++;
printf("------ beginning ------\n\n");
const char * str1;
const char * str2;
size_t n;
// NULL ptr checks
EXPECT_EQUALS(strncmpci(NULL, "", 0), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, "", 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", "", 0), 0);
EXPECT_EQUALS(strncmp("", "", 0), 0);
str1 = "";
str2 = "";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "HeY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "hey";
str2 = "HEdY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'y' - 'd');
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "hEYd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'e' - 'E');
str1 = "heY";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), 'Y' - 'y');
str1 = "hey";
str2 = "hey";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), -'d');
str1 = "hey";
str2 = "heyd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hEY";
str2 = "heyYOU";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEY";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEYHowAre";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'h' - 'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 'n' - 'N');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to meet you.,;", 100), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO UEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to uEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to UEET YOU.,;", 100), 'm' - 'U');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 'n' - 'N');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
if (globals.error_count == num_failures_expected)
{
printf(ANSI_COLOR_GRN "All unit tests passed!" ANSI_COLOR_OFF "\n");
}
else
{
printf(ANSI_COLOR_RED "FAILED UNIT TESTS! NUMBER OF UNEXPECTED FAILURES = %i"
ANSI_COLOR_OFF "\n", globals.error_count - num_failures_expected);
}
assert(globals.error_count == num_failures_expected);
return globals.error_count;
}
$ gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp ----------------------- String Comparison Tests ----------------------- INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like! FAILED at line 250 in function main! strncmpci("hey", "HEY", 3) != 'h' - 'H' a: strncmpci("hey", "HEY", 3) is 0 b: 'h' - 'H' is 32 ------ beginning ------ All unit tests passed!
I usually create these two helper functions when using date inputs:
// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
`${date.getFullYear()
}-${('0' + (date.getMonth() + 1)).slice(-2)
}-${('0' + date.getDate()).slice(-2)
}`;
// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));
You can then set the date input value as:
$('#datePicker').val(dateToInput(new Date()));
And retrieve the selected value like so
const dateVal = inputToDate($('#datePicker').val())
I guess you looking for CURDATE()
or NOW()
.
SELECT name, datum
FROM tasks
WHERE datum >= CURDATE()
LooK the rsult of NOW and CURDATE
NOW() CURDATE()
2008-11-11 12:45:34 2008-11-11
After some years with node, I can say that there are no conventions for the directory/file structure. However most (professional) express applications use a setup like:
/
/bin - scripts, helpers, binaries
/lib - your application
/config - your configuration
/public - your public files
/test - your tests
An example which uses this setup is nodejs-starter.
I personally changed this setup to:
/
/etc - contains configuration
/app - front-end javascript files
/config - loads config
/models - loads models
/bin - helper scripts
/lib - back-end express files
/config - loads config to app.settings
/models - loads mongoose models
/routes - sets up app.get('..')...
/srv - contains public files
/usr - contains templates
/test - contains test files
In my opinion, the latter matches better with the Unix-style directory structure (whereas the former mixes this up a bit).
I also like this pattern to separate files:
lib/index.js
var http = require('http');
var express = require('express');
var app = express();
app.server = http.createServer(app);
require('./config')(app);
require('./models')(app);
require('./routes')(app);
app.server.listen(app.settings.port);
module.exports = app;
lib/static/index.js
var express = require('express');
module.exports = function(app) {
app.use(express.static(app.settings.static.path));
};
This allows decoupling neatly all source code without having to bother dependencies. A really good solution for fighting nasty Javascript. A real-world example is nearby which uses this setup.
Update (filenames):
Regarding filenames most common are short, lowercase filenames. If your file can only be described with two words most JavaScript projects use an underscore as the delimiter.
Update (variables):
Regarding variables, the same "rules" apply as for filenames. Prototypes or classes, however, should use camelCase.
Update (styleguides):
It would be something like:
document.getElementById("username").value="Username";
document.forms[0].submit()
Or similar edit: you guys are too fast ;)
Unless you are writing very small files, you should probably use templates.
Example:
- name: copy upstart script
template:
src: myCompany-service.conf.j2
dest: "/etc/init/myCompany-service.conf"
The tutorial is cheating because it is starting with a greyscale image encoded in RGB, so they are just slicing a single color channel and treating it as greyscale. The basic steps you need to do are to transform from the RGB colorspace to a colorspace that encodes with something approximating the luma/chroma model, such as YUV/YIQ or HSL/HSV, then slice off the luma-like channel and use that as your greyscale image. matplotlib
does not appear to provide a mechanism to convert to YUV/YIQ, but it does let you convert to HSV.
Try using matplotlib.colors.rgb_to_hsv(img)
then slicing the last value (V) from the array for your grayscale. It's not quite the same as a luma value, but it means you can do it all in matplotlib
.
Background:
Alternatively, you could use PIL or the builtin colorsys.rgb_to_yiq()
to convert to a colorspace with a true luma value. You could also go all in and roll your own luma-only converter, though that's probably overkill.
Basically, don't use DateTime.MinValue
to represent a missing value. You can't use DateTime.MinValue
in a SQL Server DateTime field, as SQL Server has a minimum value of the start of 1753.
Instead, make your BirthDate
property a Nullable<DateTime>
(aka DateTime?
), and set it to null
when you don't have a value. Also make sure your database field is nullable. Then you just need to make sure that that null
ends up as a NULL
value in the database. Exactly how you do that will depend on your data access, which you haven't told us anything about.
It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.
Assuming there is a column named business:
SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business
To fix this issue you would have to download the file locally and run a cron job to keep updating. Note: this doesn't make your website any faster at all so its best to just ignore it.
For demonstration purposes however, follow this guide: http://diywpblog.com/leverage-browser-cache-optimize-google-analytics/
There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:
>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438
Yet it doesn't break the dictionary:
>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'
Sanity check:
>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438
Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.
(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8)
.)
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:
git branch --set-upstream-to origin/master
or with the short option:
git branch -u origin/master
This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.
Once you have set this option; git status
will show you something like:
# Your branch is ahead of 'origin/master' by 1 commit.
From WikiAnswers:
Furthermore, a user can access objects in schemas other than their own, if they have permission to do so.
The precise way to do this is it to use .project()
cursor method with the new mongodb
and nodejs
driver.
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
You can get it by using document.getElementById();
var fileVal=document.getElementById("some Id");
alert(fileVal.value);
will give the value of file,but it gives with fakepath as follows
c:\fakepath\filename
You can unbind your handler with .off
, but there's a caveat; if you're doing this just prevent the handler from being triggered again while it's already running, you need to defer rebinding the handler.
For example, consider this code, which uses a 5-second hot sleep to simulate something synchronous and computationally expensive being done from within the handler (like heavy DOM manipulation, say):
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
// BAD CODE, DON'T COPY AND PASTE ME!
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
$('#foo').click(handler);
});
</script>
This won't work. As you can see if you try it out in this JSFiddle, if you click the button while the handler is already executing, the handler will execute a second time once the first execution finishes. What's more, at least in Chrome and Firefox, this would be true even if you didn't use jQuery and used addEventListener
and removeEventListener
to add and remove the handler instead. The browser executes the handler after the first click, unbinding and rebinding the handler, and then handles the second click and checks whether there's a click handler to execute.
To get around this, you need to defer rebinding of the handler using setTimeout
, so that clicks that happen while the first handler is executing will be processed before you reattach the handler.
<button id="foo">Click Me!</div>
<script>
function waitForFiveSeconds() {
var startTime = new Date();
while (new Date() - startTime < 5000) {}
}
$('#foo').click(function handler() {
$('#foo').off('click');
console.log('Hello, World!');
waitForFiveSeconds();
// Defer rebinding the handler, so that any clicks that happened while
// it was unbound get processed first.
setTimeout(function () {
$('#foo').click(handler);
}, 0);
});
</script>
You can see this in action at this modified JSFiddle.
Naturally, this is unnecessary if what you're doing in your handler is already asynchronous, since then you're already yielding control to the browser and letting it flush all the click events before you rebind your handler. For instance, code like this will work fine without a setTimeout
call:
<button id="foo">Save Stuff</div>
<script>
$('#foo').click(function handler() {
$('#foo').off('click');
$.post( "/some_api/save_stuff", function() {
$('#foo').click(handler);
});
});
</script>
There was auto generated Copyright message in XML
and a blank line before <resources>
tag, once I removed it my build was successful.
Another helper to delay your code that is 100% Swift in usage and optionally allows for choosing a different thread to run your delayed code from:
public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
let dispatchTime = DispatchTime.now() + seconds
dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}
public enum DispatchLevel {
case main, userInteractive, userInitiated, utility, background
var dispatchQueue: DispatchQueue {
switch self {
case .main: return DispatchQueue.main
case .userInteractive: return DispatchQueue.global(qos: .userInteractive)
case .userInitiated: return DispatchQueue.global(qos: .userInitiated)
case .utility: return DispatchQueue.global(qos: .utility)
case .background: return DispatchQueue.global(qos: .background)
}
}
}
Now you simply delay your code on the Main thread like this:
delay(bySeconds: 1.5) {
// delayed code
}
If you want to delay your code to a different thread:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the examples above, e.g.:
import HandySwift
delay(bySeconds: 1.5) {
// delayed code
}
Set a transparent border and then change it:
.default{
border: 2px solid transparent;
}
.new{
border: 2px solid red;
}
Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing
You need to open the file again using open()
, but this time passing 'w'
to indicate that you want to write to the file. I would also recommend using with
to ensure that the file will be closed when you are finished writing to it.
with open('Failed.txt', 'w') as f:
for ip in [k for k, v in ips.iteritems() if v >=5]:
f.write(ip)
Naturally you may want to include newlines or other formatting in your output, but the basics are as above.
The same issue with closing your file applies to the reading code. That should look like this:
ips = {}
with open('today','r') as myFile:
for line in myFile:
parts = line.split(' ')
if parts[1] == 'Failure':
if parts[0] in ips:
ips[pars[0]] += 1
else:
ips[parts[0]] = 0
The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).
There is a tutorial here*, but it doesn't explain too much more than the above paragraph.
For what it's worth, the nested curly braces around a[15:0]
are superfluous.
*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}}
should be a {2{2}}
.
If your vector look like this std::vector<MyClass*> vecType_pt
you have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj
, constructor will be called by vector.Please execute example given below , and understand the difference :
class MyClass
{
public:
MyClass()
{
cout<<"MyClass"<<endl;
}
~MyClass()
{
cout<<"~MyClass"<<endl;
}
};
int main()
{
typedef std::vector<MyClass*> vecType_ptr;
typedef std::vector<MyClass> vecType_obj;
vecType_ptr myVec_ptr;
vecType_obj myVec_obj;
MyClass obj;
for(int i=0;i<5;i++)
{
MyClass *ptr=new MyClass();
myVec_ptr.push_back(ptr);
myVec_obj.push_back(obj);
}
cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
cout<<"\n\n---------------------If object stored---------------------"<<endl;
myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
return 0;
}
You can now use In app review API provided by Google out of the box.
First, in your build.gradle(app)
file, add following dependencies (full setup can be found here)
dependencies {
// This dependency is downloaded from the Google’s Maven repository.
// So, make sure you also include that repository in your project's build.gradle file.
implementation 'com.google.android.play:core:1.8.0'
implementation 'com.google.android.play:core-ktx:1.8.1'
}
Create a method and put this code inside:
val manager = ReviewManagerFactory.create(context)
val request = manager.requestReviewFlow()
request.addOnCompleteListener { request ->
if (request.isSuccessful) {
// We got the ReviewInfo object
val reviewInfo = request.result
val flow = manager.launchReviewFlow(activity, reviewInfo)
flow.addOnCompleteListener { _ ->
// The flow has finished. The API does not indicate whether the user
// reviewed or not, or even whether the review dialog was shown. Thus, no
// matter the result, we continue our app flow.
}
} else {
// There was some problem, continue regardless of the result.
}
}
Use forward slashes to specify the UNC Path:
open('//HOST/share/path/to/file')
(if your Python client code is also running under Windows)
The easiest way I have found to do this is to just use require
and the path to your JSON file.
For example, suppose you have the following JSON file.
test.json
{
"firstName": "Joe",
"lastName": "Smith"
}
You can then easily load this in your node.js application using require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
Like this:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
In Java 9+, if unmodifiable set is ok:
Set<T> mySet = Set.of(someArray);
In Java 10+, the generic type parameter can be inferred from the arrays component type:
var mySet = Set.of(someArray);
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Although other answers prove the requirement, they don't explain why the requirement exists.
The JLS mentions why in §15.27.2:
The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.
To lower risk of bugs, they decided to ensure captured variables are never mutated.
Other answers are great. This is another way it can be done.
SizedBox.expand()
to fill available space and for passing tight constraints for its children (Container).BoxFit.cover
enum to Zoom the image and cover whole screen Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand( // -> 01
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
fit: BoxFit.cover, // -> 02
),
),
),
),
);
}
Different languages do different things with different levels of efficiency.
The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.
After reading this post some time ago I was wondering if it was safe to use domains for exception handling on an api / function level. I wanted to use them to simplify exception handling code in each async function I wrote. My concern was that using a new domain for each function would introduce significant overhead. My homework seems to indicate that there is minimal overhead and that performance is actually better with domains than with try catch in some situations.
http://www.lighthouselogic.com/#/using-a-new-domain-for-each-async-function-in-node/
Adding the data-position="fixed" and adding the below style in the css will fix the issue z-index: 1;
I never faced such an issue with any device as I've had one codebase for all, without any hardcoded values. What I do is to have the maximum sized image as resource instead of one for each device. For example, I would have one for retina display and show it as aspect fit so it will be views as is on every device. Coming to deciding the frame of button, for instance, at run time. For this I use the % value of the patent view, example , if I want the width to be half of parent view take 50 % of parent and same applies for height and center.
With this I don't even need the xibs.
Here is a complete jquery plugin that solves this problem:
https://github.com/bigspotteddog/ScrollToFixed
The description of this plugin is as follows:
This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically; however, it does allow the element to continue to move left or right with the horizontal scroll.
Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position; but, the element will still move horizontally as the page is scrolled left or right. Once the page has been scrolled back down past the target position, the element will be restored to its original position on the page.
This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9.
Usage for your particular case:
<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery-scrolltofixed-min.js" type="text/javascript"></script>
$(document).ready(function() {
$('#mydiv').scrollToFixed({ marginTop: 250 });
});
Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.
If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.
This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).
It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)
import matplotlib
from matplotlib.colors import ListedColormap
# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)
# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
2:"red",
13:"orange",
7:"green"}
# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])
# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)
# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])
# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)
diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()
Putting simple, Androids Context
is a mess that you won't love until you stop worrying about.
Android Context
s are:
God-objects.
Thing that you want to pass around all your application when you are starting developing for Android, but will avoid doing it when you get a little bit closer to programming, testing and Android itself.
Unclear dependency.
Common source of memory leaks.
PITA for testing.
Actual context used by Android system to dispatch permissions, resources, preferences, services, broadcasts, styles, showing dialogs and inflating layout. And you need different Context
instances for some separate things (obviously, you can't show a dialog from an application or service context; layouts inflated from application and activity contexts may differ).
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
The following code will work:
private WebView mWebView;
final Activity activity = this;
// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}
I've rearranged the selected answer, used pointers for arrays and user input for number count is not pre-defined.
#include <iostream>
using namespace std;
void merge(int*, int*, int, int, int);
void mergesort(int *a, int*b, int start, int end) {
int halfpoint;
if (start < end) {
halfpoint = (start + end) / 2;
mergesort(a, b, start, halfpoint);
mergesort(a, b, halfpoint + 1, end);
merge(a, b, start, halfpoint, end);
}
}
void merge(int *a, int *b, int start, int halfpoint, int end) {
int h, i, j, k;
h = start;
i = start;
j = halfpoint + 1;
while ((h <= halfpoint) && (j <= end)) {
if (a[h] <= a[j]) {
b[i] = a[h];
h++;
} else {
b[i] = a[j];
j++;
}
i++;
}
if (h > halfpoint) {
for (k = j; k <= end; k++) {
b[i] = a[k];
i++;
}
} else {
for (k = h; k <= halfpoint; k++) {
b[i] = a[k];
i++;
}
}
// Write the final sorted array to our original one
for (k = start; k <= end; k++) {
a[k] = b[k];
}
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
int b[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergesort(a, b, 0, num - 1);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
I also struggled finding articles on how to just generate the token part. I never found one and wrote my own. So if it helps:
The things to do are:
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.Identity.Owin
startup
classThen create a HTML and a JavaScript (index.js
) file with these contents:
var loginData = 'grant_type=password&[email protected]&password=test123';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
The OWIN startup
class should have this content:
using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace OAuth20
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/token"),
Provider = new OAuthAuthorizationServerProvider()
{
OnValidateClientAuthentication = async (context) =>
{
context.Validated();
},
OnGrantResourceOwnerCredentials = async (context) =>
{
if (context.UserName == "[email protected]" && context.Password == "test123")
{
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
context.Validated(oAuthIdentity);
}
}
},
AllowInsecureHttp = true,
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
};
app.UseOAuthBearerTokens(OAuthOptions);
}
}
}
Run your project. The token should be displayed in the pop-up.
<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
you could get just the first row like:
with open('some.csv', newline='') as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
first_line = next(csv_reader)
I have several version of JDK (not JRE) instaled and I launch Eclipse with:
C:\eclipse\eclipse.exe -vm "%JAVA_HOME%\bin\javaw.exe" -data f:\dev\java\2013
As you can see, I set JAVA_HOME
to point to the version of JDK I want to use.
I NEVER add javaw.exe in the PATH.
-data
is used to choose a workspace for a particular job/client/context.
If you want a single value for all rows:
df.insert(0,'name_of_column','')
df['name_of_column'] = value
Edit:
You can also:
df.insert(0,'name_of_column',value)
For simple case (one currency) it'is enough int
/long
.
Keep money in cents (...) or hundredth / thousandth of cents (any precision you need with fixed divider)
It's too late to answer this question, but it could help for new readers,
It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody
and @RequestParam
doesn't matter.
body= "name=abc"
, and name = "abc"
body ="name=abc"
, name = "xyz,abc"
Here you are another general solution for any data type.
int offset = 0;
byte[] buffer = new byte[8192];
try {
do {
int b = inputStream.read();
if (b == -1)
break;
buffer[offset++] = (byte) b;
//check offset with buffer length and reallocate array if needed
} while (inputStream.available() > 0);
} catch (SocketException e) {
//connection was lost
}
//process buffer
Use the following regular expression:
^\d{4}-\d{2}-\d{2}$
as in
if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
...
}
With the matches
method, the anchors ^
and $
(beginning and end of string, respectively) are present implicitly.
Here is a solution using history
Read more
import { createBrowserHistory } from "history";
const history = createBrowserHistory()
inside Router
<Router>
{history.location.pathname}
</Router>
use ng-bind-html-unsafe
it will apply html with text inside like below:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
Here is my solution:
SELECT
DISTINCT NAME,
MAX(MESSAGES) OVER(PARTITION BY NAME) MESSAGES
FROM MESSAGE;
You can also use this command on the command line:
mvn dependency:purge-local-repository clean install
I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:
Why are you using editors to just look at a (large) file?
Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.
There is a Win32 port of GNU less. See the "less" section of the answer above.
Perl is good for quick scripts, and its ..
(range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.
For example:
$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less
This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.
Another example:
$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less
This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...
This is another useful tool you can use. To quote the Wikipedia article:
logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.
Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.
Example usage:
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"
100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.
Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...
npm uninstal @angular/material
and also clear file custom-theme.scss
At the application level, the application uses TCP as a stream oriented protocol. TCP in turn has segments and abstracts away the details of working with unreliable IP packets.
TCP deals with segments instead of packets. Each TCP segment has a sequence number which is contained inside a TCP header. The actual data sent in a TCP segment is variable.
There is a value for getsockopt that is supported on some OS that you can use called TCP_MAXSEG which retrieves the maximum TCP segment size (MSS). It is not supported on all OS though.
I'm not sure exactly what you're trying to do but if you want to reduce the buffer size that's used you could also look into: SO_SNDBUF and SO_RCVBUF.
And here is the non jQuery answer.
Fiddle: http://jsfiddle.net/J7m7m/7/
function changeText(value) {
document.getElementById('count').value = 500 * value;
}
HTML slight modification:
Product price: $500
<br>
Total price: $500
<br>
<input type="button" onclick="changeText(2)" value="2
Qty">
<input type="button" class="mnozstvi_sleva" value="4
Qty" onClick="changeText(4)">
<br>
Total <input type="text" id="count" value="1"/>
EDIT: It is very clear that this is a non-desired way as pointed out below (I had it coming). So in essence, this is how you would do it in plain old javascript. Most people would suggest you to use jQuery (other answer has the jQuery version) for good reason.
its work for me set the User-Agent in the addRequestProperty.
URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
I know that there has been a long time since this topic has been created but I saw a little mistake within this solution (I can call it like that, because it's a detail). I agree that the better solution is probably this solution:
if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['Hello']);
unset($_COOKIE['HelloTest1']);
setcookie('Hello', null, -1, '/');
setcookie('HelloTest1', null, -1, '/');
return true;
} else {
return false;
}
But, in the present case, you delete the cookies in every case where the unset function works and immediately you create new expired cookies in case that the unset function doesn't work.
That means that even if the unset function works, it will still have 2 cookies on the computer. The asked goal, in a logical point of view, is to delete the cookies if it is possible and if it really isn't, make it expire; to get "the cleanest" result.
So, I think we better should do:
if (isset($_COOKIE['remember_user'])) {
setcookie('Hello', null, -1, '/');
setcookie('HelloTest1', null, -1, '/');
unset($_COOKIE['Hello']);
unset($_COOKIE['HelloTest1']);
return true;
} else {
return false;
}
Thanks and have a nice day :)
Just use the select query to display the table varialble, where ever you want to check.
http://www.simple-talk.com/sql/learn-sql-server/management-studio-improvements-in-sql-server-2008/
requests package works really well for simple ui as @Andrew Mao suggested
import requests
response = requests.get('http://lib.stat.cmu.edu/datasets/boston')
data = response.text
for i, line in enumerate(data.split('\n')):
print(f'{i} {line}')
o/p:
0 The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic
1 prices and the demand for clean air', J. Environ. Economics & Management,
2 vol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics
3 ...', Wiley, 1980. N.B. Various transformations are used in the table on
4 pages 244-261 of the latter.
5
6 Variables in order:
Checkout kaggle notebook on how to extract dataset/dataframe from URL
You cannot disable linker warning 4099, as said @John Weldon.
You should rebuild library with some project configuration changes. You have several options:
GLM has good example of rotation : http://glm.g-truc.net/code.html
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
glm::mat4(1.0f),
glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
ViewTranslate,
Rotate.y,
glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
ViewRotateX,
Rotate.x,
glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
glm::mat4(1.0f),
glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
Here is what I did: I check the body y position , then make the body fixed and adjust the top to the negative of that position. On reverse, I make the body static and set the scroll to the value I recorded before.
var body_x_position = 0;
function disable_bk_scrl(){
var elb = document.querySelector('body');
body_x_position = elb.scrollTop;
// get scroll position in px
var body_x_position_m = body_x_position*(-1);
console.log(body_x_position);
document.body.style.position = "fixed";
$('body').css({ top: body_x_position_m });
}
function enable_bk_scrl(){
document.body.style.position = "static";
document.body.scrollTo(0, body_x_position);
console.log(body_x_position);
}
String fname = "Sam\u0025";
PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
ps.setString(1, fname);
update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
Probably I have found myself:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
I think thats correct. RTSP may use RTP internally.
The static
keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.
Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.
If my understanding from reading the above answers is correct, Runtime is basically 'background processes' such as garbage collection, memory-allocation, basically any processes that are invoked indirectly, by the libraries / frameworks that your code is written in, and specifically those processes that occur after compilation, while the application is running.
UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!
Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.
Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.
Thanks!
I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version
for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.
Sourced from a combination of places:
https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx
# First we obtain de timezone info o some datatime variable
tz_info = your_timezone_aware_variable.tzinfo
# Now we can subtract two variables using the same time zone info
# For instance
# Lets obtain the Now() datetime but for the tz_info we got before
diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable
Conclusion: You must mange your datetime variables with the same time info
Simply call
print(unknownDataType.runtimeType)
on the data.
This won't get rid of the close button, but it will stop someone closing the window.
Put this in your code behind file:
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
e.Cancel = true;
}
You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation
You could try Dozer.
Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.
You have an array that is the "hash table".
In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.
In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
declare @dt datetime
set @dt = '09-22-2007 15:07:38.850'
select dateadd(mi, datediff(mi, 0, @dt), 0)
select dateadd(hour, datediff(hour, 0, @dt), 0)
will return
2007-09-22 15:07:00.000
2007-09-22 15:00:00.000
The above just truncates the seconds and minutes, producing the results asked for in the question. As @OMG Ponies pointed out, if you want to round up/down, then you can add half a minute or half an hour respectively, then truncate:
select dateadd(mi, datediff(mi, 0, dateadd(s, 30, @dt)), 0)
select dateadd(hour, datediff(hour, 0, dateadd(mi, 30, @dt)), 0)
and you'll get:
2007-09-22 15:08:00.000
2007-09-22 15:00:00.000
Before the date data type was added in SQL Server 2008, I would use the above method to truncate the time portion from a datetime to get only the date. The idea is to determine the number of days between the datetime in question and a fixed point in time (0
, which implicitly casts to 1900-01-01 00:00:00.000
):
declare @days int
set @days = datediff(day, 0, @dt)
and then add that number of days to the fixed point in time, which gives you the original date with the time set to 00:00:00.000
:
select dateadd(day, @days, 0)
or more succinctly:
select dateadd(day, datediff(day, 0, @dt), 0)
Using a different datepart (e.g. hour
, mi
) will work accordingly.
Of course, you will get a fatal error for authenticating, because you do not include a user name...
Try this one, it is OK for me :)
psql -U username -d myDataBase -a -f myInsertFile
If the database is remote, use the same command with host
psql -h host -U username -d myDataBase -a -f myInsertFile
This may be a little late; but someone will find it useful.
There's a Nuget Package for integrating AdminLTE - a popular Bootstrap template - to MVC5
Simply run this command in your Visual Studio Package Manager console
Install-Package AdminLteMvc
NB: It may take a while to install because it downloads all necessary files as well as create sample full and partial views (.cshtml files) that can guide you as you develop. A sample layout file _AdminLteLayout.cshtml
is also provided.
You'll find the files in ~/Views/Shared/
folder
It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:
The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.
How about this: https://commons.apache.org/proper/commons-jcs/ (updated to new address, as JCS is now in Apache Commons)
Yes. Use the ternary operator.
condition ? true_expression : false_expression;
This is a simple html file "demo.htm" stored in the same folder as the node.js file.
<!DOCTYPE html>
<html>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
</body>
</html>
Below is the node.js file to call this html file.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, resp){
// Print the name of the file for which request is made.
console.log("Request for demo file received.");
fs.readFile("Documents/nodejs/demo.html",function(error, data){
if (error) {
resp.writeHead(404);
resp.write('Contents you are looking for-not found');
resp.end();
} else {
resp.writeHead(200, {
'Content-Type': 'text/html'
});
resp.write(data.toString());
resp.end();
}
});
});
server.listen(8081, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8081/');
Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".
This one was not included:
System.Windows.Forms.Application.ExecutablePath;
~Joe
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
You can use this IE HTML5 shim script to gain a basic level of support for the new semantic elements in HTML5 such as <article>
.
I had this issue when running ng test
, so to fix it, I added to my xyz.component.spec.ts
file:
import { MatTableModule } from '@angular/material';
And added it to imports
section in TestBed.configureTestingModule({})
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
declarations: [ BookComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
Technically, all Java objects are pointers. All primitive types are values though. There is no way to take manual control of those pointers. Java just internally uses pass-by-reference.
Since the accepted BufferedInputStream#read
isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
Blocks until a full read is complete, and doesn't require extra imports.
a profanity filtering system will never be perfect, even if the programmer is cocksure and keeps abreast of all nude developments
that said, any list of 'naughty words' is likely to perform as well as any other list, since the underlying problem is language understanding which is pretty much intractable with current technology
so, the only practical solution is twofold:
This can easily be done by using the Linq extension method Union. For example:
var mergedList = list1.Union(list2).ToList();
This will return a List in which the two lists are merged and doubles are removed. If you don't specify a comparer in the Union extension method like in my example, it will use the default Equals and GetHashCode methods in your Person class. If you for example want to compare persons by comparing their Name property, you must override these methods to perform the comparison yourself. Check the following code sample to accomplish that. You must add this code to your Person class.
/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
{
// Try to cast the object to compare to to be a Person
var person = obj as Person;
return Equals(person);
}
/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
{
// Check if person is being compared to a non person. In that case always return false.
if (personToCompareTo == null) return false;
// If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
if (string.IsNullOrEmpty(personToCompareTo.Name) return false;
// Check if both person objects contain the same Name. In that case they're assumed equal.
return Name.Equals(personToCompareTo.Name);
}
If you don't want to set the default Equals method of your Person class to always use the Name to compare two objects, you can also write a comparer class which uses the IEqualityComparer interface. You can then provide this comparer as the second parameter in the Linq extension Union method. More information on how to write such a comparer method can be found on http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx
DECLARE @IDQuery VARCHAR(MAX)
SET @IDQuery = 'SELECT ID FROM SomeTable WHERE Condition=Something'
DECLARE @ExcludedList TABLE(ID VARCHAR(MAX))
INSERT INTO @ExcludedList EXEC(@IDQuery)
SELECT * FROM A WHERE Id NOT IN (@ExcludedList)
I know I'm responding to an old post but I wanted to share an example of how to use Variable Tables when one wants to avoid using dynamic SQL. I'm not sure if its the most efficient way, however this has worked in the past for me when dynamic SQL was not an option.
Here's a version that uses lodash.
const _ = require('lodash');
sortedArr.splice(_.sortedIndex(sortedArr,valueToInsert) ,0,valueToInsert);
note: sortedIndex does a binary search.
generateRandomComplementaryColor = function(r, g, b){
//--- JavaScript code
var red = Math.floor((Math.random() * 256));
var green = Math.floor((Math.random() * 256));
var blue = Math.floor((Math.random() * 256));
//---
//--- Extra check for Internet Explorers, its Math.random is not random enough.
if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){
red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
};
//---
//--- nodejs code
/*
crypto = Npm.require('crypto');
red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
*/
//---
red = (red + r)/2;
green = (green + g)/2;
blue = (blue + b)/2;
return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';
}
Run the function using:
generateRandomComplementaryColor(240, 240, 240);
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you are using Jersey 2.x use following dependency:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.XX</version>
</dependency>
Where XX
could be any particular version you look for. Jersey Containers.
Why am I unable to use a string for a newline in write() but I can use it in writelines()?
The idea is the following: if you want to write a single string you can do this with write()
. If you have a sequence of strings you can write them all using writelines()
.
write(arg)
expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).
writelines(arg)
expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.
The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines()
does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence)
.
What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
f.write('\n'.join(lines))
This takes care of closing the file for you. The construct '\n'.join(lines)
concatenates (connects) the strings in the list lines
and uses the character '\n' as glue. It is more efficient than using the +
operator.
Starting from the same lines
sequence, ending up with the same output, but using writelines()
:
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
f.writelines("%s\n" % l for l in lines)
This makes use of a generator expression and dynamically creates newline-terminated strings. writelines()
iterates over this sequence of strings and writes every item.
Edit: Another point you should be aware of:
write()
and readlines()
existed before writelines()
was introduced. writelines()
was introduced later as a counterpart of readlines()
, so that one could easily write the file content that was just read via readlines()
:
outfile.writelines(infile.readlines())
Really, this is the main reason why writelines
has such a confusing name. Also, today, we do not really want to use this method anymore. readlines()
reads the entire file to the memory of your machine before writelines()
starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:
with open('inputfile') as infile:
with open('outputfile') as outfile:
for line in infile:
outfile.write(line)
This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).
The final
keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
The final
keyword can be applied with the variables, a final
variable that has no value, is called blank final
variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static
also which will be initialized in the static
block only.
Java final variable:
If you make any variable as final
, you cannot change the value of final
variable(It will be constant).
Example of final
variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // this will make error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Java final class:
If you make any class as final
, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{ //cannot inherit from final Bike,this will make error
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Java final method:
If you make any method as final, you cannot override it.
Example of final
method
(run() in Honda cannot override run() in Bike)
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
shared from: http://www.javatpoint.com/final-keyword
I find this particularly useful for when you want to 'store' a function call.
For example, suppose I have some unit tests for a function 'add':
def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
print 'test: adding', test, '==', result, '---', add(*test) == result
There is no other way to call add, other than manually doing something like add(test[0], test[1])
, which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.
Another place this is useful is for defining Factory objects (objects that create objects for you).
Suppose you have some class Factory, that makes Car objects and returns them.
You could make it so that myFactory.make_car('red', 'bmw', '335ix')
creates Car('red', 'bmw', '335ix')
, then returns it.
def make_car(*args):
return Car(*args)
This is also useful when you want to call a superclass' constructor.
In my case I had a solution with VB Web Forms project that referenced a C# UserControl. Both the VB project and the CS project had a Service Reference to the same service. The reference appeared under Service References in the VB project and under the Connected Services grouping in the CS (framework) project.
In order to update the service reference (ie, get the Reference.vb file to not be empty) in the VB web forms project, I needed to REMOVE THE CS PROJECT, then update the VB Service Reference, then add the CS project back into the solution.
This should get your sorted:
Ctrl + H
to bring up the 'Find and Replace' window.\r\n
Here's how it should look:
REST vs. SOAP
SOAP:
? SOAP is simple object access protocol that run on TCP/UDP/SMTP.
? SOAP read and write request response messages in XML format.
? SOAP uses interface in order to define the services.
? SOAP is more secure as it has its own security and well defined standards.
? SOAP follows RPC and Document style to define web services.
? SOAP uses SOAP-UI as client tools for testing.
REST
? REST is representational state transfer that uses underlying HTTP protocols.
? REST is stateless.
? REST is an architectural style that is used to describe and define web services.
? REST can read and write request response messages in JSON/XML/Plain HTML.
? REST uses URI for each resource that is used in web service.A resource can be image text method etc.
? REST uses set of verbs, like HTTP's GET, POST, PUT, DELETE.
? REST is easy to develop and easy to manage as compared to SOAP UI.
? REST has light-weight client tools or plugins that can easily be integrated inside a browser.
? REST services are cacheable.
I am sharing my understanding of Monads, which may not be theoretically perfect. Monads are about Context propagation. Monad is, you define some context for some data (or data type(s)), and then define how that context will be carried with the data throughout its processing pipeline. And defining context propagation is mostly about defining how to merge multiple contexts (of same type). Using Monads also means ensuring these contexts are not accidentally stripped off from the data. On the other hand, other context-less data can be brought into a new or existing context. Then this simple concept can be used to ensure compile time correctness of a program.
You’re looking for urllib.parse.urlencode
import urllib.parse
params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'
the order of registering routes is important . register 404
routes after static files.
correct order:
app.use("/admin", admin);
...
app.use(express.static(join(__dirname, "public")));
app.use((req, res) => {
res.status(404);
res.send("404");
});
otherwise everything which is not in routes , like css files etc.. , will become 404 .
Make half of the image transparent so the background colour is seen through it.
Else simply add another div taking up 50% up the container div and float it either left or right. Then apply either the image or the colour to it.
The way to use expr:
i=0
i=`expr $i + 1`
the way to use i++
((i++)); echo $i;
Tested in gnu bash
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.
For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.
There is a link to downloadable code at the end of the article. Hope that helps.
The real problem is how Netbeans JARs its projects. The "Class-Path:" in the Manifest file is unnecessary when actually publishing your program for others to use. If you have an external Library added in Netbeans it acts as a package. I suggest you use a program like WINRAR to view the files within the jar and add your libraries as packages directly into the jar file.
How the inside of the jar file should look:
MyProject.jar
Manifest.MF
Main-Class: mainClassFolder.Mainclass
mainClassFolder
Mainclass.class
packageFolder
IamUselessWithoutMain.class
/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk
Define the following function (not mine, not sure where I found it long ago):
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then:
String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
InputStream response = conn.getInputStream();
jsonReply = convertStreamToString(response);
// Do JSON handling here....
}
Ok I finally worked this out. This is using TortoiseHg on Windows. If you're not using that you can do it on the command line.
hggit
:Open a command line, enter an empty directory.
git init --bare .git
(If you don't use a bare repo you'll get an error like abort: git remote error: refs/heads/master failed to update
cd
to your Mercurial repository.
hg bookmarks hg
hg push c:/path/to/your/git/repo
In the Git directory: git config --bool core.bare false
(Don't ask me why. Something about "work trees". Git is seriously unfriendly. I swear writing the actual code is easier than using Git.)
Hopefully it will work and then you can push from that new git repo to a non-bare one.
hey you can try this
ColorStateList colorStateList = textView.getTextColors();
String hexColor = String.format("#%06X", (0xFFFFFF & colorStateList.getDefaultColor()));
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
Assuming you're running on a Windows machine...
F12
keyScripts
, or Sources
, tab in the developer toolsThen during execution debugging you can do a handful of stepping motions...
F8
Continue: Will continue until the next breakpointF10
Step over: Steps over next function call (won't enter the
library)F11
Step into: Steps into the next function call (will
enter the library)Shift + F11
Step out: Steps out of the current
functionUpdate
After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.
I use numpy.size() to do the same:
import numpy as np
import cv2
image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)
I had a similar problem, trying to capture a 'shift+click' but since I was using a third party control with a callback rather than the standard click
handler, I didn't have access to the event object and its associated e.shiftKey
.
I ended up handling the mouse down event to record the shift-ness and then using it later in my callback.
var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });
Posted just in case someone else ends up here searching for a solution to this problem.
Since the above answers clearly explains how to play safely with Optionals. I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D Happy Swfting All.
In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.
In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.
Example:
//Define a functional object to hold persons in JavaScript_x000D_
var Person = function(name) {_x000D_
this.name = name;_x000D_
};_x000D_
_x000D_
//Add dynamically to the already defined object a new getter_x000D_
Person.prototype.getName = function() {_x000D_
return this.name;_x000D_
};_x000D_
_x000D_
//Create a new object of type Person_x000D_
var john = new Person("John");_x000D_
_x000D_
//Try the getter_x000D_
alert(john.getName());_x000D_
_x000D_
//If now I modify person, also John gets the updates_x000D_
Person.prototype.sayMyName = function() {_x000D_
alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
_x000D_
//Call the new method on john_x000D_
john.sayMyName();
_x000D_
Until now I've been extending the base object, now I create another object and then inheriting from Person.
//Create a new object of type Customer by defining its constructor. It's not
//related to Person for now.
var Customer = function(name) {
this.name = name;
};
//Now I link the objects and to do so, we link the prototype of Customer to
//a new instance of Person. The prototype is the base that will be used to
//construct all new instances and also, will modify dynamically all already
//constructed objects because in JavaScript objects retain a pointer to the
//prototype
Customer.prototype = new Person();
//Now I can call the methods of Person on the Customer, let's try, first
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
return this.amountDue;
};
//Let's try:
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
var Person = function (name) {_x000D_
this.name = name;_x000D_
};_x000D_
Person.prototype.getName = function () {_x000D_
return this.name;_x000D_
};_x000D_
var john = new Person("John");_x000D_
alert(john.getName());_x000D_
Person.prototype.sayMyName = function () {_x000D_
alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
john.sayMyName();_x000D_
var Customer = function (name) {_x000D_
this.name = name;_x000D_
};_x000D_
Customer.prototype = new Person();_x000D_
_x000D_
var myCustomer = new Customer('Dream Inc.');_x000D_
myCustomer.sayMyName();_x000D_
Customer.prototype.setAmountDue = function (amountDue) {_x000D_
this.amountDue = amountDue;_x000D_
};_x000D_
Customer.prototype.getAmountDue = function () {_x000D_
return this.amountDue;_x000D_
};_x000D_
myCustomer.setAmountDue(2000);_x000D_
alert(myCustomer.getAmountDue());
_x000D_
While as said I can't call setAmountDue(), getAmountDue() on a Person.
//The following statement generates an error.
john.setAmountDue(1000);
When I have a Store Procedure name, and do not know which database it belongs to, I use the following -
Use [master]
GO
DECLARE @dbname VARCHAR(50)
DECLARE @statement NVARCHAR(max)
DECLARE db_cursor CURSOR
LOCAL FAST_FORWARD
FOR
--Status 48 (mirrored db)
SELECT name FROM MASTER.dbo.sysdatabases WHERE STATUS NOT LIKE 48 AND name NOT IN ('master','model','msdb','tempdb','distribution')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @statement = 'SELECT * FROM ['+@dbname+'].INFORMATION_SCHEMA.ROUTINES WHERE [ROUTINE_NAME] LIKE ''%name_of_proc%'''+';'
print @statement
EXEC sp_executesql @statement
FETCH NEXT FROM db_cursor INTO @dbname
END
CLOSE db_cursor
DEALLOCATE db_cursor
Now google maps is free for development only.
If you want to use map free like earlier, then create an account with valid details (billing, payment, etc.) google gives $200 MONTHLY CREDIT Which is EQUIVALENT To FREE USAGE
For more details please see Googles new price details: google map new pricing
Also see the old price details: Old one
I don't know if this works but I made the variable names
public abstract class beep implements ActionListener {
public static void main(String[] args) {
JFrame f = new JFrame("beeper");
JButton button = new JButton("Beep me");
f.setVisible(true);
f.setSize(300, 200);
f.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert code here
}
});
}
}
<style type="text/css">
#warning-message { display: none; }
@media only screen and (orientation:portrait){
#wrapper { display:none; }
#warning-message { display:block; }
}
@media only screen and (orientation:landscape){
#warning-message { display:none; }
}
</style>
....
<div id="wrapper">
<!-- your html for your website -->
</div>
<div id="warning-message">
this website is only viewable in landscape mode
</div>
You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.
I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.
Update
I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.
Another Update
So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.
You can add a guard condition to the method to ensure books
is not null and then check for null when iterating the array:
public static double calculateInventoryTotal(Book[] books)
{
if(books == null){
throw new IllegalArgumentException("Books cannot be null");
}
double total = 0;
for (int i = 0; i < books.length; i++)
{
if(books[i] != null){
total += books[i].getPrice();
}
}
return total;
}
You could also do this:
#!/usr/bin/perl
use strict;
use warnings;
$^I = '.bak'; # create a backup copy
while (<>) {
s/<PREF>/ABCD/g; # do the replacement
print; # print to the modified file
}
Invoke the script with by
./script.pl input_file
You will get a file named input_file
, containing your changes, and a file named input_file.bak
, which is simply a copy of the original file.
The best way to use selenium.webdriver.support.ui.Select
class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.
In this type of situation you can also prefer as alternate solution using execute_script()
as below :-
option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")
#now use this to select option from dropdown by visible text
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);
Vim is a nice upgrade for Vi, offering decent features and a more usable set of keybindings and default behaviour. However, graphical versions like GVim, KVim and even Cream are extremely lacking in my opinion. I've been using Geany a lot lately, but it also has its shortcomings.
I just can't find something in the league of Programmers Notepad, Smultron or TextMate on Linux. A shame, since I want to live in an all open source cyberworld, I'm stuck hopping from one almost-right editor to another.
If you are using Bootstrap version < 3...
With sass/scss
$baseBorderRadius: 0;
With less
@baseBorderRadius: 0;
You will need to set this variable before importing the bootstrap. This will affect all wells and navbars.
Update
If you are using Bootstrap 3 baseBorderRadius should be border-radius-base
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
Have a look at Pig Vs Hive Comparison in a nut shell from a "dezyre" article
Hive is better than PIG in: Partitions, Server, Web interface & JDBC/ODBC support.
Some differences:
Hive is best for structured Data & PIG is best for semi structured data
Hive is used for reporting & PIG for programming
Hive is used as a declarative SQL & PIG as a procedural language
Hive supports partitions & PIG does not
Hive can start an optional thrift based server & PIG cannot
Hive defines tables beforehand (schema) + stores schema information in a database & PIG doesn't have a dedicated metadata of database
Hive does not support Avro but PIG does. EDIT: Hive supports Avro, specify the serde as org.apache.hadoop.hive.serde2.avro
Pig also supports additional COGROUP feature for performing outer joins but hive does not. But both Hive & PIG can join, order & sort dynamically.
$(this).value
is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val()
.
Do not use Class.newInstance()
; see this thread: Why is Class.newInstance() evil?
Like other answers say, use Constructor.newInstance()
instead.
stub and fake are objects in that they can vary their response based on input parameters. the main difference between them is that a Fake is closer to a real-world implementation than a stub. Stubs contain basically hard-coded responses to an expected request. Let see an example:
public class MyUnitTest {
@Test
public void testConcatenate() {
StubDependency stubDependency = new StubDependency();
int result = stubDependency.toNumber("one", "two");
assertEquals("onetwo", result);
}
}
public class StubDependency() {
public int toNumber(string param) {
if (param == “one”) {
return 1;
}
if (param == “two”) {
return 2;
}
}
}
A mock is a step up from fakes and stubs. Mocks provide the same functionality as stubs but are more complex. They can have rules defined for them that dictate in what order methods on their API must be called. Most mocks can track how many times a method was called and can react based on that information. Mocks generally know the context of each call and can react differently in different situations. Because of this, mocks require some knowledge of the class they are mocking. a stub generally cannot track how many times a method was called or in what order a sequence of methods was called. A mock looks like:
public class MockADependency {
private int ShouldCallTwice;
private boolean ShouldCallAtEnd;
private boolean ShouldCallFirst;
public int StringToInteger(String s) {
if (s == "abc") {
return 1;
}
if (s == "xyz") {
return 2;
}
return 0;
}
public void ShouldCallFirst() {
if ((ShouldCallTwice > 0) || ShouldCallAtEnd)
throw new AssertionException("ShouldCallFirst not first thod called");
ShouldCallFirst = true;
}
public int ShouldCallTwice(string s) {
if (!ShouldCallFirst)
throw new AssertionException("ShouldCallTwice called before ShouldCallFirst");
if (ShouldCallAtEnd)
throw new AssertionException("ShouldCallTwice called after ShouldCallAtEnd");
if (ShouldCallTwice >= 2)
throw new AssertionException("ShouldCallTwice called more than twice");
ShouldCallTwice++;
return StringToInteger(s);
}
public void ShouldCallAtEnd() {
if (!ShouldCallFirst)
throw new AssertionException("ShouldCallAtEnd called before ShouldCallFirst");
if (ShouldCallTwice != 2) throw new AssertionException("ShouldCallTwice not called twice");
ShouldCallAtEnd = true;
}
}
Creating a data.table
with key=V1
automatically does this for you. Using Stephan's data foo
> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
V1 V2
1: 1 349
2: 1 393
3: 1 392
4: 2 94
5: 3 49
6: 3 32
7: 4 459
I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition()
was fully ignored, for an evident reason.
What I was using?
recyclerView.scrollToPosition(items.size());
... what WORKED?
recyclerView.scrollToPosition(items.size() - 1);
Easy, simply wrap a MemoryStream
around it:
Stream stream = new MemoryStream(buffer);
android:hint="Enter your question" or something like this must work. I am using Relative layout with EditText as If you want to use password,say android:inputType="textPassword" for hiding characters and "textVisiblePassword" for showing what you enter as password.
System variables usually require a restart to become effective. Does it still not work after a restart?
JavaScript has built in to it a function called setInterval
, which takes two arguments - a function, callback
and an integer, timeout
. When called, setInterval
will call the function you give it every timeout
milliseconds.
For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.
function makeAlert(){
alert("Popup window!");
};
setInterval(makeAlert, 500);
However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.
setInterval(function(){ alert("Popup window!"); }, 500);
Once setInterval
is called, it will run until you call clearInterval
on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
if(timeleft <= 0){_x000D_
clearInterval(downloadTimer);_x000D_
}_x000D_
document.getElementById("progressBar").value = 10 - timeleft;_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
Alternatively, this will create a text countdown.
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
if(timeleft <= 0){_x000D_
clearInterval(downloadTimer);_x000D_
document.getElementById("countdown").innerHTML = "Finished";_x000D_
} else {_x000D_
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
}_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_
Tilde ~ matches minor version, if you have installed a package that has 1.4.2 and after your installation, versions 1.4.3 and 1.4.4 are also available if in your package.json it is used as ~1.4.2 then npm install in your project after upgrade will install 1.4.4 in your project. But there is 1.5.0 available for that package then it will not be installed by ~. It is called minor version.
Caret ^ matches major version, if 1.4.2 package is installed in your project and after your installation 1.5.0 is released then ^ will install major version. It will not allow to install 2.1.0 if you have ^1.4.2.
Fixed version if you don't want to change version of package on each installation then used fixed version with out any special character e.g "1.4.2"
Latest Version * If you want to install latest version then only use * in front of package name.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
Modern browsers support native querySelectorAll
so you can do:
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
Details about browser compatibility:
You can use jQuery to support obsolete browsers (IE9 and older):
$('[data-foo="value"]');
I'd say this is a (windows)python bug.
Why bug?
I think this statement should be True
os.path.join(*os.path.dirname(os.path.abspath(__file__)).split(os.path.sep))==os.path.dirname(os.path.abspath(__file__))
But it is False
on windows machines.
I ran into this error after my client PC crashed, the jest --watch
command I was running on the server persisted, and I tried to run jest --watch
again.
The addition to /etc/sysctl.conf
described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node
and kill
it.
The problem with solutions using OnFocusChangeListener is that they interpret any focus gain as a click. This is not 100% correct: your EditText might gain focus from something else than a click.
If you strictly care about click and want to detect click consistently (regardless of focus), you can use a GestureDetector
:
editText.setOnConsistentClickListener { /* do something */ }
fun EditText.setOnConsistentClickListener(doOnClick: (View) -> Unit) {
val gestureDetector = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(event: MotionEvent?): Boolean {
doOnClick(this@setOnConsistentClickListener)
return false
}
})
this.setOnTouchListener { _, motionEvent -> gestureDetector.onTouchEvent(motionEvent) }
}
I met the same problem as you.
I push two tables
result
into t1
object and group t1
.
from p in Products
join bp in BaseProducts on p.BaseProductId equals bp.Id
select new {
p,
bp
} into t1
group t1 by t1.p.SomeId into g
select new ProductPriceMinMax {
SomeId = g.FirstOrDefault().p.SomeId,
CountryCode = g.FirstOrDefault().p.CountryCode,
MinPrice = g.Min(m => m.bp.Price),
MaxPrice = g.Max(m => m.bp.Price),
BaseProductName = g.FirstOrDefault().bp.Name
};
XAML
<Popup Name="myPopup">
<TextBlock Name="myPopupText"
Background="LightBlue"
Foreground="Blue">
Popup Text
</TextBlock>
</Popup>
c#
Popup codePopup = new Popup();
TextBlock popupText = new TextBlock();
popupText.Text = "Popup Text";
popupText.Background = Brushes.LightBlue;
popupText.Foreground = Brushes.Blue;
codePopup.Child = popupText;
you can find more details about the Popup Control from MSDN documentation.
Could use IgnoreAttribute on the property which needs to be ignored
Make sure that your ORACLE_HOME and ORACLE_SID are correct To see the current values in windows, at the command prompt type
echo %ORACLE_HOME%
Then
echo %ORACLE_SID%
If the values are not your current oracle home and SID you need to correct them. This can be done in Windows environment variables.
Check out this page for more info
A simple PHP function I created for the YouTube thumbnail and the types are
function get_youtube_thumb($link,$type){
$video_id = explode("?v=", $link);
if (empty($video_id[1])){
$video_id = explode("/v/", $link);
$video_id = explode("&", $video_id[1]);
$video_id = $video_id[0];
}
$thumb_link = "";
if($type == 'default' || $type == 'hqdefault' ||
$type == 'mqdefault' || $type == 'sddefault' ||
$type == 'maxresdefault'){
$thumb_link = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg';
}elseif($type == "id"){
$thumb_link = $video_id;
}
return $thumb_link;}
If you're explaining the concept to a beginner, it might be helpful to use an analogy. The use of void in all these cases is analogous in meaning to a page in a book which has the following words, "This page left intentionally blank." It is to differentiate to the compiler between something which should be flagged as an error, versus a type which is intentionally to be left blank because that is the behavior you want.
It always appears in code where normally you would expect to see a type appear, such as a return type or a pointer type. This is why in C#, void maps to an actual CLR type, System.Void because it is a type in itself.
Some programming languages never developed the concept of void, just like some human cultures never invented the concept of the number zero. Void represents the same advancement in a programming language as the concept of zero represents to human language.
function supportFullCss3()
{
var div = document.createElement("div");
div.style.display = 'flex';
var s1 = div.style.display == 'flex';
var s2 = 'perspective' in div.style;
return (s1 && s2);
};
function getZoomLevel()
{
var screenPixelRatio = 0, zoomLevel = 0;
if(window.devicePixelRatio && supportFullCss3())
screenPixelRatio = window.devicePixelRatio;
else if(window.screenX == '0')
screenPixelRatio = (window.outerWidth - 8) / window.innerWidth;
else
{
var scr = window.frames.screen;
screenPixelRatio = scr.deviceXDPI / scr.systemXDPI;
}
//---------------------------------------
if (screenPixelRatio <= .11){ //screenPixelRatio >= .01 &&
zoomLevel = "-7";
} else if (screenPixelRatio <= .25) {
zoomLevel = "-6";
}else if (screenPixelRatio <= .33) {
zoomLevel = "-5.5";
} else if (screenPixelRatio <= .40) {
zoomLevel = "-5";
} else if (screenPixelRatio <= .50) {
zoomLevel = "-4";
} else if (screenPixelRatio <= .67) {
zoomLevel = "-3";
} else if (screenPixelRatio <= .75) {
zoomLevel = "-2";
} else if (screenPixelRatio <= .85) {
zoomLevel = "-1.5";
} else if (screenPixelRatio <= .98) {
zoomLevel = "-1";
} else if (screenPixelRatio <= 1.03) {
zoomLevel = "0";
} else if (screenPixelRatio <= 1.12) {
zoomLevel = "1";
} else if (screenPixelRatio <= 1.2) {
zoomLevel = "1.5";
} else if (screenPixelRatio <= 1.3) {
zoomLevel = "2";
} else if (screenPixelRatio <= 1.4) {
zoomLevel = "2.5";
} else if (screenPixelRatio <= 1.5) {
zoomLevel = "3";
} else if (screenPixelRatio <= 1.6) {
zoomLevel = "3.3";
} else if (screenPixelRatio <= 1.7) {
zoomLevel = "3.7";
} else if (screenPixelRatio <= 1.8) {
zoomLevel = "4";
} else if (screenPixelRatio <= 1.9) {
zoomLevel = "4.5";
} else if (screenPixelRatio <= 2) {
zoomLevel = "5";
} else if (screenPixelRatio <= 2.1) {
zoomLevel = "5.2";
} else if (screenPixelRatio <= 2.2) {
zoomLevel = "5.4";
} else if (screenPixelRatio <= 2.3) {
zoomLevel = "5.6";
} else if (screenPixelRatio <= 2.4) {
zoomLevel = "5.8";
} else if (screenPixelRatio <= 2.5) {
zoomLevel = "6";
} else if (screenPixelRatio <= 2.6) {
zoomLevel = "6.2";
} else if (screenPixelRatio <= 2.7) {
zoomLevel = "6.4";
} else if (screenPixelRatio <= 2.8) {
zoomLevel = "6.6";
} else if (screenPixelRatio <= 2.9) {
zoomLevel = "6.8";
} else if (screenPixelRatio <= 3) {
zoomLevel = "7";
} else if (screenPixelRatio <= 3.1) {
zoomLevel = "7.1";
} else if (screenPixelRatio <= 3.2) {
zoomLevel = "7.2";
} else if (screenPixelRatio <= 3.3) {
zoomLevel = "7.3";
} else if (screenPixelRatio <= 3.4) {
zoomLevel = "7.4";
} else if (screenPixelRatio <= 3.5) {
zoomLevel = "7.5";
} else if (screenPixelRatio <= 3.6) {
zoomLevel = "7.6";
} else if (screenPixelRatio <= 3.7) {
zoomLevel = "7.7";
} else if (screenPixelRatio <= 3.8) {
zoomLevel = "7.8";
} else if (screenPixelRatio <= 3.9) {
zoomLevel = "7.9";
} else if (screenPixelRatio <= 4) {
zoomLevel = "8";
} else if (screenPixelRatio <= 4.1) {
zoomLevel = "8.1";
} else if (screenPixelRatio <= 4.2) {
zoomLevel = "8.2";
} else if (screenPixelRatio <= 4.3) {
zoomLevel = "8.3";
} else if (screenPixelRatio <= 4.4) {
zoomLevel = "8.4";
} else if (screenPixelRatio <= 4.5) {
zoomLevel = "8.5";
} else if (screenPixelRatio <= 4.6) {
zoomLevel = "8.6";
} else if (screenPixelRatio <= 4.7) {
zoomLevel = "8.7";
} else if (screenPixelRatio <= 4.8) {
zoomLevel = "8.8";
} else if (screenPixelRatio <= 4.9) {
zoomLevel = "8.9";
} else if (screenPixelRatio <= 5) {
zoomLevel = "9";
}else {
zoomLevel = "unknown";
}
return zoomLevel;
};
The issue is basically coming when, we are requesting to angular to run the digest cycle even though its in process which is creating issue to angular to understanding. consequence exception in console.
1. It does not have any sense to call scope.$apply() inside the $timeout function because internally it does the same.
2. The code goes with vanilla JavaScript function because its native not angular angular defined i.e. setTimeout
3. To do that you can make use of
if(!scope.$$phase){
scope.$evalAsync(function(){
});
}
The remote
section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:
fetch = +refs/heads/*:refs/remotes/origin/*
(Or replace origin
with bitbucket
.)
Please read about it here: 10.5 Git Internals - The Refspec
wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
I already added these params by xml but it didnot work correctly
and with this line all is ok
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
There are only two syntaxes at play here.
Plain old array initialisation:
int x[] = {0, 0}; // x[0] = 0, x[1] = 0
A designated initialiser. See the accepted answer to this question: How to initialize a struct in accordance with C programming language standards
The syntax is pretty self-explanatory though. You can initialise like this:
struct X {
int a;
int b;
}
struct X foo = { 0, 1 }; // a = 0, b = 1
or to use any ordering,
struct X foo = { .b = 0, .a = 1 }; // a = 1, b = 0
I was getting same errors after an install on Windows 10. And I tried restarting but it did not work, so I did the following (do not recommend if you have been working in docker for awhile, this was on a fresh install):
1) Find the whale in your system tray, and right click
2) Go to settings > Reset
3) Reset to factory defaults
I was then able to follow the starting docker tutorial on the website with Windows 10, and now it works like a charm.
This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.
view.setOnTouchListener { view, motionEvent ->
(view.parent as View).onTouchEvent(motionEvent)
}
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
That means the following for the expression a,b = b,a
:
b,a
is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b
and a
, that were existing before the instruction is encountered during the execution of the program.a
be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b
)b
is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a
)This mechanism has effectively swapped the objects assigned to the identifiers a
and b
So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.
This is exactly how it worked for me. For some reason the above code failed.
This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y
:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup
This gives you the first few digits of the hash and they are unique enough to use as say a version number.
git rev-parse --short HEAD
New version - psql 12 - will support --csv
.
--csv
Switches to CSV (Comma-Separated Values) output mode. This is equivalent to \pset format csv.
csv_fieldsep
Specifies the field separator to be used in CSV output format. If the separator character appears in a field's value, that field is output within double quotes, following standard CSV rules. The default is a comma.
Usage:
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv -P csv_fieldsep='^' postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres > output.csv
You should replace the old OpenSSL binary file by the new one via a symlink:
sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`
Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.
If it's an input element you can write something like....
<input type="radio" [checked]="condition">
The value of condition must be true or false.
Also for style attributes...
<h4 [style.color]="'red'">Some text</h4>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert("Hello!");
}
</script>
</body>
</html>
Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.