bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
Note that Python classes are also callable.
To get functions (and by functions we mean standard functions and lambdas) use:
import types
def is_func(obj):
return isinstance(obj, (types.FunctionType, types.LambdaType))
def f(x):
return x
assert is_func(f)
assert is_func(lambda x: x)
Here's a more technical and thorough answer to an old question: Visual Basic for Applications (VBA) and Visual Basic (pre-.NET) are not just similar languages, they are the same language. Specifically:
In an old VB reference book I came across last year, the author (Paul Lomax) even asserted that 'VBA' has always been the name of the language itself, whether used in stand-alone applications or in embedded contexts (such as MS Office):
"Before we go any further, let's just clarify on fundamental point. Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB). VB itself is a development environment; the language element of that environment is VBA."
The minor differences
Hosted vs. stand-alone: In practical, terms, when most people say "VBA" they specifically mean "VBA when used in MS Office", and they say "VB6" to mean "VBA used in the last version of the standalone VBA compiler (i.e. Visual Studio 6)". The IDE and compiler bundled with MS Office is almost identical to Visual Studio 6, with the limitation that it does not allow compilation to stand-alone dll or exe files. This in turns means that classes defined in embedded VBA projects are not accessible from non-embedded COM consumers, because they cannot be registered.
Continued development: Microsoft stopped producing a stand-alone VBA compiler with Visual Studio 6, as they switched to the .NET runtime as the platform of choice. However, the MS Office team continues to maintain VBA, and even released a new version (VBA7) with a new VM (now just called VBA7.dll) starting with MS Office 2010. The only major difference is that VBA7 has both a 32- and 64-bit version and has a few enhancements to handle the differences between the two, specifically with regards to external API invocations.
This is pretty much what the generic method Value()
is for. You get exactly the behavior you want if you combine it with nullable value types and the ??
operator:
width = jToken.Value<double?>("width") ?? 100;
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
I'm directly assigning jest.fn()
to window.open
.
window.open = jest.fn()
// ...code
expect(window.open).toHaveBeenCalledTimes(1)
expect(window.open).toHaveBeenCalledWith('/new-tab','__blank')
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
I've added some usability to the function from the answer by @Octopus, for debugging purposes.
void MatType( Mat inputMat )
{
int inttype = inputMat.type();
string r, a;
uchar depth = inttype & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (inttype >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; a = "Mat.at<uchar>(y,x)"; break;
case CV_8S: r = "8S"; a = "Mat.at<schar>(y,x)"; break;
case CV_16U: r = "16U"; a = "Mat.at<ushort>(y,x)"; break;
case CV_16S: r = "16S"; a = "Mat.at<short>(y,x)"; break;
case CV_32S: r = "32S"; a = "Mat.at<int>(y,x)"; break;
case CV_32F: r = "32F"; a = "Mat.at<float>(y,x)"; break;
case CV_64F: r = "64F"; a = "Mat.at<double>(y,x)"; break;
default: r = "User"; a = "Mat.at<UKNOWN>(y,x)"; break;
}
r += "C";
r += (chans+'0');
cout << "Mat is of type " << r << " and should be accessed with " << a << endl;
}
If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:
//j is a multiple of four if
j % 4 == 0
The module operator performs division and gives you the remainder.
Similar to activa's answer, here's a function to create an n-dimensional array:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
You can have multiple <context:property-placeholder />
elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.
Element.clientWidth
& Element.clientHeight
return the height/width of that element's content in addition any applicable padding.
The jQuery implementation of these are:
$(target).outerWidth()
& $(target).outerHeight()
.clientWidth
& .clientHeight
are included in the CSSOM View Module specification which is currently in the working draft stage. While modern browsers have a consistent implementation of this specification, to insure consistent performance across legacy platforms, the jQuery implementation should still be used.
Additional information:
You can use somthing like this.
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
I believe you need quotes around the model
:
JSON.stringify({ "model": source })
Put your text file in Asset Folder...& read file form that folder...
see below reference links...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
hope it will help...
Do yourself a favor by dropping the Windows compatibility layer.
The normal shortcut for entering Visual-Block mode is <C-v>
.
Others have dealt with recording macros, here are a few other ideas:
Using only visual-block mode.
Put the cursor on the second word:
asd |a|sd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom:
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
Hit I"<Esc>
to obtain:
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
Put the cursor on the last char of the third word:
asd "asd as|d| asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom:
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
Hit A"<Esc>
to obtain:
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
With visual-block mode and Surround.vim.
Put the cursor on the second word:
asd |a|sd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom and the right:
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
Hit S"
to surround your selection with ":
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
With visual-line mode and :normal
.
Hit V
to select the whole line and expand it toward the bottom:
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR>
to obtain:
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
:norm[al]
allows you to execute normal mode commands on a range of lines (the '<,'>
part is added automatically by Vim and means "act on the selected area")
^
puts the cursor on the first char of the line
w
moves to the next word
i"
inserts a "
before the cursor
<C-v><Esc>
is Vim's way to input a control character in this context, here it's <Esc>
used to exit insert mode
ee
moves to the end of the next word
a"
appends a "
after the cursor
<CR>
executes the command
Using Surround.vim, the command above becomes
:'<,'>norm ^wvees"<CR>
A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.
Unfortunately, you also need to escape the regex, for which no standard function exists.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.
"hello world".split.each{|i| i.capitalize!}.join(' ')
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
On python 3.5.2
sudo apt-get install libmysqlclient-dev python-dev
Each control deriving from Panel
implements distinct layout logic performed in Measure()
and Arrange()
:
Measure()
determines the size of the panel and each of its childrenArrange()
determines the rectangle where each control rendersThe last child of the DockPanel
fills the remaining space. You can disable this behavior by setting the LastChild
property to false
.
The StackPanel
asks each child for its desired size and then stacks them. The stack panel calls Measure()
on each child, with an available size of Infinity
and then uses the child's desired size.
A Grid
occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel
and then overriding MeasureOverride()
and ArrangeOverride()
.
See this article for a simple example.
There is two way for hide a element
Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :
<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">
2.Better way of doing this is to use " *ngIf " directive like this :
<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">
Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.
I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.
using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
I hope this will be useful to someone.
The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:
CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src
OutputExecutable: part1api.o part2api.o part3api.o
This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
Chrome not implement support RTSP streaming. An important project to check it WebRTC.
"WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs"
Supported Browsers:
Chrome, Firefox and Opera.
Supported Mobile Platforms:
Android and IOS
If you can use C++11 you may want to use std::function
and using
keyword.
using FunctionFunc = std::function<void(int arg1, std::string arg2)>;
For check of email use email_validator
from email_validator import validate_email, EmailNotValidError
def check_email(email):
try:
v = validate_email(email) # validate and get info
email = v["email"] # replace with normalized form
print("True")
except EmailNotValidError as e:
# email is not valid, exception message is human-readable
print(str(e))
check_email("test@gmailcom")
Thank for the question. But I have found my own solution to this problem. At first, I created a method
public T GetSettingsWithDictionary<T>() where T:new()
{
IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
.AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
var instance = new T();
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType == typeof(Dictionary<string, string>))
{
property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
break;
}
}
return instance;
}
Then I used this method to produce an instance of a class
var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();
I have the next declaration of class
public class AuthMongoConnectionStrings
{
public Dictionary<string, string> ConnectionStrings { get; set; }
}
and I store my setting in App.config
<configuration>
<AuthMongoConnectionStrings
First="first"
Second="second"
Third="33" />
</configuration>
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
DateTime begindate = Convert.ToDateTime("01/Jan/2018");
DateTime enddate = Convert.ToDateTime("12 Feb 2018");
while (begindate < enddate)
{
begindate= begindate.AddDays(1);
Console.WriteLine(begindate + " " + enddate);
}
As other people have commented above, using TRUNC will prevent the use of indexes (if there was an index on TIME_CREATED). To avoid that problem, the query can be structured as
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED BETWEEN TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TO_DATE('26/JAN/2011','dd/mon/yyyy') + INTERVAL '86399' second;
86399 being 1 second less than the number of seconds in a day.
More generic method as variant of https://stackoverflow.com/a/52296246
/**
* Returns a duplicated values found in given collection based on fieldClassifier
*
* @param collection given collection of elements
* @param fieldClassifier field classifier which specifies element to check for duplicates(useful in complex objects).
* @param <T> Type of element in collection
* @param <K> Element which will be returned from method in fieldClassifier.
* @return returns list of values that are duplocated.
*/
public static <T, K> List<K> lookForDuplicates(List<T> collection, Function<? super T, ? extends K> fieldClassifier) {
return collection.stream().collect(Collectors.groupingBy(fieldClassifier))
.entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
during command line works. I'm using Ant to commit an artifact after build completes. Experienced the same issue... Manually excepting the cert did not work (Jenkins is funny that way). Add these options to your svn command:
--non-interactive
--trust-server-cert
I generally use:
killall ruby
OR
pkill -9 ruby
which will kill all ruby related processes that are running like rails server
, rails console
, etc.
The other Answers are correct, especially this one by Stephen C.
Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.
If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:
uuidgen
found in Mac OS X, BSD, and Linux.uuid-ossp
extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
uuid_generate_v1mc()
– generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.uuid_generate_v5(namespace uuid, name text)
– generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.You speak of two different things "HTML5 validation" and validation of HTML form using javascript/jquery.
HTML5 "has" built-in options for validating a form. Such as using "required" attribute on a field, which could (based on browser implementation) fail form submission without using javascript/jquery.
With javascrip/jquery you can do something like this
$('your_form_id').bind('submit', function() {
// validate your form here
return (valid) ? true : false;
});
There is an overload of Split that takes strings.
"THExxQUICKxxBROWNxxFOX".Split(new [] { "xx" }, StringSplitOptions.None);
You can use either of these StringSplitOptions
So if the string is "THExxQUICKxxxxBROWNxxFOX", StringSplitOptions.None
will return an empty entry in the array for the "xxxx" part while StringSplitOptions.RemoveEmptyEntries
will not.
yes just do
git checkout master
git pull
git checkout mobiledevicesupport
git merge master
to keep mobiledevicesupport in sync with master
then when you're ready to put mobiledevicesupport into master, first merge in master like above, then ...
git checkout master
git merge mobiledevicesupport
git push origin master
and thats it.
the assumption here is that mobilexxx is a topic branch with work that isn't ready to go into your main branch yet. So only merge into master when mobiledevicesupport is in a good place
FLAnimatedImage is a performant open source animated GIF engine for iOS:
It's a well-tested component that I wrote to power all GIFs in Flipboard.
function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string')
? a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string')
? b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
http://yazilimsozluk.com/sort-array-in-javascript-by-asc-or-desc
Looks like the answer above was a little incomplete try the following:-
=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))
Obviously, this is for cell A2...
What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.
After the length has been determined and the portion of that which is required - then the Right command will display the information you need.
This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...
=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
with org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
, you are trying to select from the users
table. But you are annotating your class with @Table( name = "Users" )
. So either use users
, or Users
.
Click \Build\Select Build Variant...
in Android Studio.
And choose release
.
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
Put this at the top of your .py file (for python 2.x)
#!/usr/bin/env python
or for python 3.x
#!/usr/bin/env python3
This should look up the python environment, without it, it will execute the code as if it were not python code, but straight to the CLI. If you need to specify a manual location of python environment put
#!/#path/#to/#python
I like both of the 2 main solutions:
NSArray *array = [NSArray arrayWithArray:mutableArray];
Or
NSArray *array = [mutableArray copy];
The primary difference I see in them is how they behave when mutableArray is nil:
NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == @[] (empty array)
NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil
I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle
file as following:
rootProject.name='YourNewName'
This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
I had the same problem when I was trying to move the android studio to another Drive as it was taking a lot of space in my C(Windows drive) Drive, Here's what fixed my problem:-
For Entity framework 6 I use this annotation and works fine.
public partial class MyDbContext : DbContext
{
private const int TimeoutDuration = 300;
public MyDbContext ()
: base("name=Model1")
{
this.Database.CommandTimeout = TimeoutDuration;
}
// Some other codes
}
The CommandTimeout parameter is a nullable integer that set timeout values as seconds, if you set null or don't set it will use default value of provider you use.
This would get you the index of the clicked row, starting with one:
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
<tr>_x000D_
<td>1</td><td>1</td><td>1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td><td>2</td><td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td><td>3</td><td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you want to return the number stored in that first cell of each row:
$('#thetable').find('tr').click( function(){
var row = $(this).find('td:first').text();
alert('You clicked ' + row);
});
In my case the above suggestions did not work for me. Mine was little different scenario.
When i tried installing bundler
using gem install bundler
.. But i was getting
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.
then i tried using sudo gem install bundler
then i was getting
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /usr/bin directory.
then i tried with sudo gem install bundler -n /usr/local/bin
( Just /usr/bin
dint work in my case ).
And then successfully installed bundler
EDIT: I use MacOS, maybe /usr/bin
din't work for me for that reason (https://stackoverflow.com/a/34989655/3786657 comment )
There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.
To get the result I believe you are looking for try this:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
</div>
</div>
Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.
Hope this helps.
The syntax is the *
and **
. The names *args
and **kwargs
are only by convention but there's no hard requirement to use them.
You would use *args
when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargs
allows you to handle named arguments that you have not defined in advance:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args
and **kwargs
. The named arguments come first in the list. For example:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args
must occur before **kwargs
.
You can also use the *
and **
syntax when calling a function. For example:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a *
both in the function definition and in the function call.
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
There is no need to add a listener to the ?android:attr/ratingBarStyleSmall
. Just add
android:isIndicator=false
and it will capture click events, e.g.
<RatingBar
android:id="@+id/myRatingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:isIndicator="false" />
A completely valid way to select all browsers but IE8 and below is using the :root
selector. Since IE versions 8 and below do not support :root
, selectors containing it are ignored. This means you could do something like this:
p {color:red;}
:root p {color:blue;}
This is still completely valid CSS, but it does cause IE8 and lower to render different styles.
Here's a list of all completely valid CSS browser-specific selectors I could find, except for some that seem quite redundant, such as ones that select for just 1 type of ancient browser (1, 2):
/****** First the hacks that target certain specific browsers ******/
* html p {color:red;} /* IE 6- */
*+html p {color:red;} /* IE 7 only */
@media screen and (-webkit-min-device-pixel-ratio:0) {
p {color:red;}
} /* Chrome, Safari 3+ */
p, body:-moz-any-link {color:red;} /* Firefox 1+ */
:-webkit-any(html) p {color:red;} /* Chrome 12+, Safari 5.1.3+ */
:-moz-any(html) p {color:red;} /* Firefox 4+ */
/****** And then the hacks that target all but certain browsers ******/
html> body p {color:green;} /* not: IE<7 */
head~body p {color:green;} /* not: IE<7, Opera<9, Safari<3 */
html:first-child p {color:green;} /* not: IE<7, Opera<9.5, Safari&Chrome<4, FF<3 */
html>/**/body p {color:green;} /* not: IE<8 */
body:first-of-type p {color:green;} /* not: IE<9, Opera<9, Safari<3, FF<3.5 */
:not([ie8min]) p {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
body:not([oldbrowser]) p {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
Typing cd
will take you back to your home directory.
Whereas typing cd ..
will move you up only one directory (the direct parent of the current directory).
Since I don't like any Object.prototype-calls, I searched for another solution. Especially because the solutions of ChaosPandion won't always work, and the solution of MidnightTortoise with isArray()
doesn't work with arrays coming from the DOM (like getElementsByTagName). And finally I found an easy and cross-browser solution, which probably also would have worked with Netscape 4. ;)
It's just these 4 lines (checking any object h
):
function isArray(h){
if((h.length!=undefined&&h[0]!=undefined)||(h.length===0&&h[0]===undefined)){
return true;
}
else{ return false; }
}
I already tested these arrays (all return true):
1) array=d.getElementsByName('some_element'); //'some_element' can be a real or unreal element
2) array=[];
3) array=[10];
4) array=new Array();
5) array=new Array();
array.push("whatever");
Can anybody confirm that this works for all cases? Or does anybody find a case where my solution don't work?
Blending mode used to apply the background tint.
Tint to apply to the background. Must be a color value, in the form of
#rgb
,#argb
,#rrggbb
, or#aarrggbb
.This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
It's really a 6 of one, a half-dozen of the other situation.
The only possible argument against your approach is $_SERVER['REQUEST_METHOD'] == 'POST' may not be populated on certain web-servers/configuration, whereas the $_POST array will always exist in PHP4/PHP5 (and if it doesn't exist, you have bigger problems (-:)
As stated by Martijn Pieters, the correct, and fastest, format is:
if 1 in {x, y, z}:
Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True
or False
. Such as:
if 0 in {x, y, z}:
mylist.append("c")
if 1 in {x, y, z}:
mylist.append("d")
if 2 in {x, y, z}:
mylist.append("e")
...
This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:
num_to_letters = {0: "c", 1: "d", 2: "e", 3: "f"}
for number in num_to_letters:
if number in {x, y, z}:
mylist.append(num_to_letters[number])
inet_ntoa()
works for IPv4; inet_ntop()
works for both IPv4 and IPv6.
Given an input struct sockaddr *res
, here are two snippets of code (tested on macOS):
#include <arpa/inet.h>
struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
char *s = inet_ntoa(addr_in->sin_addr);
printf("IP address: %s\n", s);
#include <arpa/inet.h>
#include <stdlib.h>
char *s = NULL;
switch(res->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
s = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res;
s = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
printf("IP address: %s\n", s);
free(s);
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
You can also achieve this using the backreference technique
sed -i.bak 's/\(.*\)/\1:80/' foo.txt
You can also use with awk like this
awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
If you need to query large (or small) log files on Windows, the best tool I have found is Microsoft's free Log Parser 2.2. You can call it from PowerShell if you want and it will do all the heavy lifting for you, and very fast too.
3 steps:
Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);
Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;
Use the code to download stream:
URL u = null;
InputStream is = null;
try {
u = new URL(url);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
int size = huc.getContentLength();
if(huc != null) {
String fileName = "FILE.mp4";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len1 = 0;
if(is != null) {
while ((len1 = is.read(buffer)) > 0) {
fos.write(buffer,0, len1);
}
}
if(fos != null) {
fos.close();
}
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null) {
is.close();
}
} catch (IOException ioe) {
// just going to ignore this one
}
}
That's all, most of stuff you'll find on the web!!!
If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):
unsigned int l=0, removed=0;
for( unsigned int i=0; i<count; i++ ) {
if( array[i] != to_remove )
array[l++] = array[i];
else
removed++;
}
count -= removed;
Use
//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
echo $value->sm_id;
}
OR
//$arr should be array as you mentioned as below
foreach($arr as $value){
echo $value->sm_id;
}
Here is my contribution.
I will not try to list all tools/libraries/plugins that exist to take advantage of Docker with Maven. Some answers have already done it.
instead of, I will focus on applications typology and the Dockerfile way.
Dockerfile
is really a simple and important concept of Docker (all known/public images rely on that) and I think that trying to avoid understanding and using Dockerfile
s is not necessarily the better way to enter in the Docker world.
1) For applications that we want to go on to run them on installed/standalone Java server (Tomcat, JBoss, etc...)
The road is harder and that is not the ideal target because that adds complexity (we have to manage/maintain the server) and it is less scalable and less fast than embedded servers in terms of build/deploy/undeploy.
But for legacy applications, that may considered as a first step.
Generally, the idea here is to define a Docker image for the server and to define an image per application to deploy.
The docker images for the applications produce the expected WAR/EAR but these are not executed as container and the image for the server application deploys the components produced by these images as deployed applications.
For huge applications (millions of line of codes) with a lot of legacy stuffs, and so hard to migrate to a full spring boot embedded solution, that is really a nice improvement.
I will not detail more that approach since that is for minor use cases of Docker but I wanted to expose the overall idea of that approach because I think that for developers facing to these complex cases, it is great to know that some doors are opened to integrate Docker.
2) For applications that embed/bootstrap the server themselves (Spring Boot with server embedded : Tomcat, Netty, Jetty...)
That is the ideal target with Docker.
I specified Spring Boot because that is a really nice framework to do that and that has also a very high level of maintainability but in theory we could use any other Java way to achieve that.
Generally, the idea here is to define a Docker image per application to deploy.
The docker images for the applications produce a JAR or a set of JAR/classes/configuration files and these start a JVM with the application (java command) when we create and start a container from these images.
For new applications or applications not too complex to migrate, that way has to be favored over standalone servers because that is the standard way and the most efficient way of using containers.
I will detail that approach.
1) Without Spring Boot
The idea is to create a fat jar with Maven (the maven assembly plugin and the maven shade plugin help for that) that contains both the compiled classes of the application and needed maven dependencies.
Then we can identify two cases :
if the application is a desktop or autonomous application (that doesn't need to be deployed on a server) : we could specify as CMD/ENTRYPOINT
in the Dockerfile
the java execution of the application : java -cp .:/fooPath/* -jar myJar
if the application is a server application, for example Tomcat, the idea is the same : to get a fat jar of the application and to run a JVM in the CMD/ENTRYPOINT
. But here with an important difference : we need to include some logic and specific libraries (org.apache.tomcat.embed
libraries and some others) that starts the embedded server when the main application is started.
We have a comprehensive guide on the heroku website.
For the first case (autonomous application), that is a straight and efficient way to use Docker.
For the second case (server application), that works but that is not straight, may be error prone and is not a very extensible model because you don't place your application in the frame of a mature framework such as Spring Boot that does many of these things for you and also provides a high level of extension.
But that has a advantage : you have a high level of freedom because you use directly the embedded Tomcat API.
2) With Spring Boot
At last, here we go.
That is both simple, efficient and very well documented.
There are really several approaches to make a Maven/Spring Boot application to run on Docker.
Exposing all of them would be long and maybe boring.
The best choice depends on your requirement.
But whatever the way, the build strategy in terms of docker layers looks like the same.
We want to use a multi stage build : one relying on Maven for the dependency resolution and for build and another one relying on JDK or JRE to start the application.
Build stage (Maven image) :
mvn dependency:resolve-plugins
chained to mvn dependency:resolve
may do the job but not always.package
execution to package the fat jar may rely on different artifacts/plugins and even for a same artifact/plugin, these may still pull a different version.
So a safer approach while potentially slower is resolving dependencies by executing exactly the mvn
command used to package the application (which will pull exactly dependencies that you are need) but by skipping the source compilation and by deleting the target folder to make the processing faster and to prevent any undesirable layer change detection for that step. Run stage (JDK or JRE image) :
Here two examples.
a) A simple way without cache for downloaded maven dependencies
Dockerfile :
########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app
#copy pom
COPY pom.xml .
#resolve maven dependencies
RUN mvn clean package -Dmaven.test.skip -Dmaven.main.skip -Dspring-boot.repackage.skip && rm -r target/
#copy source
COPY src ./src
# build the app (no dependency download here)
RUN mvn clean package -Dmaven.test.skip
# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar
########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app
#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF
#run the app
CMD java -cp .:classes:lib/* \
-Djava.security.egd=file:/dev/./urandom \
foo.bar.MySpringBootApplication
Drawback of that solution ? Any changes in the pom.xml means re-creates the whole layer that download and stores the maven dependencies. That is generally not acceptable for applications with many dependencies (and Spring Boot pulls many dependencies), overall if you don't use a maven repository manager during the image build.
b) A more efficient way with cache for maven dependencies downloaded
The approach is here the same but maven dependencies downloads that are cached in the docker builder cache.
The cache operation relies on buildkit (experimental api of docker).
To enable buildkit, the env variable DOCKER_BUILDKIT=1 has to be set (you can do that where you want : .bashrc, command line, docker daemon json file...).
Dockerfile :
# syntax=docker/dockerfile:experimental
########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app
#copy pom
COPY pom.xml .
#copy source
COPY src ./src
# build the app (no dependency download here)
RUN --mount=type=cache,target=/root/.m2 mvn clean package -Dmaven.test.skip
# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar
########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app
#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF
#run the app
CMD java -cp .:classes:lib/* \
-Djava.security.egd=file:/dev/./urandom \
foo.bar.MySpringBootApplication
How about:
public override int GetHashCode()
{
return string.Format("{0}_{1}_{2}", prop1, prop2, prop3).GetHashCode();
}
Assuming performance is not an issue :)
From the looks of things you haven't passed enough data to Spring Boot to configure the datasource
Create/In your existing application.properties
add the following
spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
making sure you append a value for each of properties.
It should be while(true)
not while(1)
, so while(1)
is incorrect in C#, yes ;)
From Microsoft:
Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop.
I'm assuming the exception is happening within an internal .NET method, and not in your code.
You can do a couple things.
You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.
EDIT: I just tested, here is how to do it:
MainProcess:
// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.Start();
p1.WaitForExit();
if (p1.ExitCode == 1)
Console.WriteLine("StackOverflow was thrown");
ApplyTransform Process:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new StackOverflowException();
}
// We trap this, we can't save the process,
// but we can prevent the "ILLEGAL OPERATION" window
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Environment.Exit(1);
}
}
}
pystring is a small library which implements a bunch of Python's string functions, including the split method:
#include <string>
#include <vector>
#include "pystring.h"
std::vector<std::string> chunks;
pystring::split("this string", chunks);
// also can specify a separator
pystring::split("this-string", chunks, "-");
This is the correct way to make a pure call. No CSS.
<div style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAFCAYAAABW1IzHAAAAHklEQVQokWNgGPaAkZHxPyMj439sYrSQo51PBgsAALa0ECF30JSdAAAAAElFTkSuQmCC)repeat-x center;'></div>
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT: Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
Here's what you need to do to fix the issue on Arch Linux :
Enable the multilib
repository on your system if you have not already done so by uncommenting the [multilib]
section in /etc/pacman.conf
:
[multilib]
Include = /etc/pacman.d/mirrorlist
Update pacman :
# pacman -Suy
Install the 32 bit version of libstdc++5 :
# pacman -S lib32-libstdc++5
This expression will match all the image urls -
^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$
Examples -
Valid -
https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg
Invalid -
https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008
In addition to all the above answer, a way based on a function introduced in sql 2012
SELECT DATEFROMPARTS(YEAR(@mydate),MONTH(@mydate),1)
4 years later, ES6 way simpler version.
function getCookie(name) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [k,v] = el.split('=');
cookie[k.trim()] = v;
})
return cookie[name];
}
I have also created a gist to use it as a Cookie
object. e.g., Cookie.set(name,value)
and Cookie.get(name)
This read all cookies instead of scanning through. It's ok for small number of cookies.
This can now be done without expression trees and extension methods in a type safe manner with the new C# feature nameof()
like this:
Attribute.IsDefined(typeof(YourClass).GetProperty(nameof(YourClass.Id)), typeof(IsIdentity));
nameof() was introduced in C# 6
I think what you are trying to achieve can simply be done like this :
While you are compiling the coffeescript, use the "-b" parameter.
-b
/ --bare
Compile the JavaScript without the top-level function safety wrapper.
So something like this : coffee -b --compile somefile.coffee whatever.js
This will output your code just like in the CoffeeScript.org site.
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
You can get textbox value and Id by the following simple example in dotNet programming
<html>
<head>
<script type="text/javascript">
function GetTextboxId_Value(textBox)
{
alert(textBox.value); // To get Text Box Value(Text)
alert(textBox.id); // To get Text Box Id like txtSearch
}
</script>
</head>
<body>
<input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" /> </body>
</html>
It works in my react project:
import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
}
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
In this line:
for name, email, lastname in unpaidMembers.items():
unpaidMembers.items()
must have only two values per iteration.
Here is a small example to illustrate the problem:
This will work:
for alpha, beta, delta in [("first", "second", "third")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
This will fail, and is what your code does:
for alpha, beta, delta in [("first", "second")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
In this last example, what value in the list is assigned to delta
? Nothing, There aren't enough values, and that is the problem.
There are no quotes in the return value, only in the default output from print() when you display the value. Try
> print(char[1], quote=FALSE)
[1] one
or
> cat(char[1], "\n")
one
to see the value without quotes.
This what you need to do.
@Url.Action(action,controller, null, Request.Url.Scheme)
If you hit git stash
when you have changes in the working copy (not in the staging area), git will create a stashed object and pushes onto the stack of stashes (just like you did git checkout -- .
but you won't lose changes). Later, you can pop from the top of the stack.
SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.
Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
You cannot directly access the table with the name 'customer'. Either it should be 'user1.customer' or create a synonym 'customer' for user2 pointing to 'user1.customer'. hope this helps..
Perhaps if you wish to go an easier way, this should do it.
WITH date_range (calc_date) AS (
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP) - 6, 0)
UNION ALL SELECT DATEADD(DAY, 1, calc_date)
FROM date_range
WHERE DATEADD(DAY, 1, calc_date) < CURRENT_TIMESTAMP)
SELECT calc_date
FROM date_range;
But the temporary table is a very good approach also. Perhaps shall you also consider a populated calendar table.
Here is how to delete ALL BUILDS FOR ALL JOBS...... using the Jenkins Scripting.
def jobs = Jenkins.instance.projects.collect { it }
jobs.each { job -> job.getBuilds().each { it.delete() }}
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");
It looks like you trying to do something similar to C# if you want setAge create method
setAge(int age){
this.age = age;}
@Controller
public abstract class AbstractController {
@ModelAttribute("loggedUser")
public User getLoggedUser() {
return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".
<meta http-equiv="refresh" content="15" >
This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.
Let us know if it worked/solved your problem!?
-Brad
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
Happen to have a task on pivot. Below works for me as tested just now on 11g:
select * from
(
select ID, COUNTRY_NAME, TOTAL_COUNT from ONE_TABLE
)
pivot(
SUM(TOTAL_COUNT) for COUNTRY_NAME in (
'Canada', 'USA', 'Mexico'
)
);
The 5th step in "New Project' has apparently changed slightly since.
Where it says android sdk then has the drop down menu that says none, there is no longer a 'new' button.
5.)
If you already have a wheel file (.whl) on your pc, then just go with the following code:
cd ../user
pip install file.whl
If you want to download a file from web, and then install it, go with the following in command line:
pip install package_name
or, if you have the url:
pip install http//websiteurl.com/filename.whl
This will for sure install the required file.
Note: I had to type pip2 instead of pip while using Python 2.
This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.
var txt_msg = $("textarea").val();
if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
return false;
}
<script type="text/javascript">
<!--
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>
Here's the other way, it's simpler than the other one.
<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />
It's simpler.
If you're writing Python using Sublime and getting indentation errors,
view -> indentation -> convert indentation to spaces
The issue I'm describing is caused by the Sublime text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
As written, this question is ambigous. The statement:
... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.
does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.
If you want to ensure to collections have exactly the same set of members regardless of order, you can use:
// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();
If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:
// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();
Using the set operations (Intersect
, Union
, Except
) is more efficient than using methods like Contains
. In my opinion, it also better expresses the expectations of your query.
EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:
var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };
// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any();
If you use Spring Boot + Spring Security, you can do that in the security configuration.
In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired FilterDependency filterDependency;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
new MyFilter(filterDependency),
UsernamePasswordAuthenticationFilter.class);
}
}
And the filter class
class MyFilter extends OncePerRequestFilter {
private final FilterDependency filterDependency;
public MyFilter(FilterDependency filterDependency) {
this.filterDependency = filterDependency;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// filter
filterChain.doFilter(request, response);
}
}
View - Layout and View - Groups will do in latest Sublime 3
eg:
Shift+Alt+2 --> creates 2 columns
Ctrl+2 --> move selected file to column 2
This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.
At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.
For instance, if you are using tomcat-jdbc:
spring.datasource.tomcat.max-wait=10000
You can find the explanation out here
spring.datasource.max-wait=10000
this have no effect anymore.
If want to remove the word from only the start of the string, then you could do:
string[string.startswith(prefix) and len(prefix):]
Where string is your string variable and prefix is the prefix you want to remove from your string variable.
For example:
>>> papa = "papa is a good man. papa is the best."
>>> prefix = 'papa'
>>> papa[papa.startswith(prefix) and len(prefix):]
' is a good man. papa is the best.'
That depends on what you want to do, but as you said, getting an entity reference using find()
and then just updating that entity is the easiest way to do that.
I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.
mailx -a /path/to/file email@address
You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.
I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).
It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project
ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\
.
From there, use the search function to find your application.
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
I ran into similar problem - Invalid value encountered in ... After spending a lot of time trying to figure out what is causing this error I believe in my case it was due to NaN in my dataframe. Check out working with missing data in pandas.
None == None True
np.nan == np.nan False
When NaN is not equal to NaN then arithmetic operations like division and multiplication causes it throw this error.
Couple of things you can do to avoid this problem:
Use pd.set_option to set number of decimal to consider in your analysis so an infinitesmall number does not trigger similar problem - ('display.float_format', lambda x: '%.3f' % x).
Use df.round() to round the numbers so Panda drops the remaining digits from analysis. And most importantly,
Set NaN to zero df=df.fillna(0). Be careful if Filling NaN with zero does not apply to your data sets because this will treat the record as zero so N in the mean, std etc also changes.
//for update
(from x in dataBase.Customers
where x.Name == "Test"
select x).ToList().ForEach(xx => xx.Name="New Name");
//for delete
dataBase.Customers.RemoveAll(x=>x.Name=="Name");
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
.Scroll {
height:600px;
overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="Scroll">
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section3">
<h2>Section 3</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section4">
<h2>Section 4</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section5">
<h2>Section 5</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
<div class="main" id="section6">
<h2>Section 6</h2>
<p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
</div>
<div class="main" id="section7">
<h2>Section 7</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</div>
</body>
</html>
_x000D_
Two options:
<button>multiline<br/>button<br/>text</button>
or
<input type="button" value="Carriage return separators" style="text-align:center;">
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
The best approach to use CData sections for the string in strings.xml file to get a actual display of the html content to the TextView the below code snippet will give you the fair idea.
//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>
//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));
CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.
Output:
Welcome, to your favorite music app store. Logged in as: username
You can use google-gson
. Details:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Another example for Gson:
Gson is easy to learn and implement, you need to know is the following two methods:
-> toJson() – convert java object to JSON format
-> fromJson() – convert JSON into java object
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
Output
{"data1":100,"data2":"hello"}
Resources:
Correct, np.log(x)
is the Natural Log (base e
log) of x
.
For other bases, remember this law of logs: log-b(x) = log-k(x) / log-k(b)
where log-b
is the log in some arbitrary base b
, and log-k
is the log in base k
, e.g.
here k = e
l = np.log(x) / np.log(100)
and l
is the log-base-100 of x
var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';
console.log(x['key1']);
// outputs value1
console.log(x['key2']);
// outputs value2
If you would like to then iterate through your dictionary, you can use.
Object.keys(x).forEach((key) => {console.log(x[key])});
Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.
You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.
You could use it like a hashset by just assigning the same value to the key and its value.
if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.
var valueToAdd = 'one';
if(!x[valueToAdd])
x[valueToAdd] = valueToAdd;
or you could build your own class to act as a hashset of sorts.
Class HashSet{
private var keys: IHash = {};
private var values: string[] = [];
public Add(key: string){
if(!keys[key]){
values.push(key);
keys[key] = key;
}
}
public GetValues(){
// slicing the array will return it by value so users cannot accidentally
// start playing around with your array
return values.slice();
}
}
def someFunc(a, b, c):
params = locals()
for _item in params:
print type(params[_item]), _item, params[_item]
Demo:
>> someFunc(1, 'asd', 1.0)
>> <type 'int'> a 1
>> <type 'float'> c 1.0
>> <type 'str'> b asd
more about locals()
Well, you may try this '.*[0-9]'
For those who expect JSON and still getting the same error, make sure that you parse your data:
$scope.customers = JSON.parse(data)
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util
version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.
onclick="this.target='_blank';"
I started using that to bypass the W3C's XHTML strict test.
If you mean you want to execute the function inputted, yes, that is simple:
Use this JS code:
eval(document.getElementById( -- el ID -- ).value);
The issue is that you haven't got command line tools installed, I believe. Try run in terminal:
sudo gem update --system
after that download command line tools from Apple just search for 'Command Line Tools' and download the right version for your OS. Once you install it run in terminal:
sudo gem install cocoapods
pod setup
There are several ways to concatenate two strings together.
Use the concatenation operator .
(and .=
)
In PHP .
is the concatenation operator which returns the concatenation of its right and left arguments
$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;
If you want to append a string to another string you would use the .=
operator:
$data1 = "the color is ";
$data1 .= "red"
Complex (curly) syntax / double quotes strings
In PHP variables contained in double quoted strings are interpolated (i.e. their values are "swapped out" for the variable). This means you can place the variables in place of the strings and just put a space in between them. The curly braces make it clear where the variables are.
$result = "{$data1} {$data2}";
Note: this will also work without the braces in your case:
$result = "$data1 $data2";
You can also concatenate array values inside a string :
$arr1 = ['val' => 'This is a'];
$arr2 = ['val' => 'test'];
$variable = "{$arr1['val']} {$arr2['val']}";
Use sprintf()
or printf()
sprintf()
allows us to format strings using powerful formatting options. It is overkill for such simple concatenation but it handy when you have a complex string and/or want to do some formatting of the data as well.
$result = sprintf("%s %s", $data1, $data2);
printf()
does the same thing but will immediately display the output.
printf("%s %s", $data1, $data2);
// same as
$result = sprintf("%s %s", $data1, $data2);
echo $result;
Heredoc
Heredocs can also be used to combine variables into a string.
$result= <<<EOT
$data1 $data2
EOT;
Use a ,
with echo()
This only works when echoing out content and not assigning to a variable. But you can use a comma to separate a list of expressions for PHP to echo out and use a string with one blank space as one of those expressions:
echo $data1, ' ', $data2;
list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]
output=[]
cur_loclist = []
To get unique values present in list2
list_set = set(list2)
To find the loc of the index in list2
list_str = ''.join(str(s) for s in list2)
Location of index in list2
is tracked using cur_loclist
[0, 3, 7, 1, 2, 4, 8, 5, 6]
for i in list_set:
cur_loc = list_str.find(str(i))
while cur_loc >= 0:
cur_loclist.append(cur_loc)
cur_loc = list_str.find(str(i),cur_loc+1)
print(cur_loclist)
for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)
Another approach will be using an attached behavior, I implemented my custom TextBoxHelper class, which can be used on textboxes all over my project. Because I figured that subscribing to the events for every textboxes and in every individual XAML file for this purpose can be time consuming.
The TextBoxHelper class I implemented has these features:
Here is the implementation of TextBoxHelper class:
public static class TextBoxHelper
{
#region Enum Declarations
public enum NumericFormat
{
Double,
Int,
Uint,
Natural
}
public enum EvenOddConstraint
{
All,
OnlyEven,
OnlyOdd
}
#endregion
#region Dependency Properties & CLR Wrappers
public static readonly DependencyProperty OnlyNumericProperty =
DependencyProperty.RegisterAttached("OnlyNumeric", typeof(NumericFormat?), typeof(TextBoxHelper),
new PropertyMetadata(null, DependencyPropertiesChanged));
public static void SetOnlyNumeric(TextBox element, NumericFormat value) =>
element.SetValue(OnlyNumericProperty, value);
public static NumericFormat GetOnlyNumeric(TextBox element) =>
(NumericFormat) element.GetValue(OnlyNumericProperty);
public static readonly DependencyProperty DefaultValueProperty =
DependencyProperty.RegisterAttached("DefaultValue", typeof(string), typeof(TextBoxHelper),
new PropertyMetadata(null, DependencyPropertiesChanged));
public static void SetDefaultValue(TextBox element, string value) =>
element.SetValue(DefaultValueProperty, value);
public static string GetDefaultValue(TextBox element) => (string) element.GetValue(DefaultValueProperty);
public static readonly DependencyProperty EvenOddConstraintProperty =
DependencyProperty.RegisterAttached("EvenOddConstraint", typeof(EvenOddConstraint), typeof(TextBoxHelper),
new PropertyMetadata(EvenOddConstraint.All, DependencyPropertiesChanged));
public static void SetEvenOddConstraint(TextBox element, EvenOddConstraint value) =>
element.SetValue(EvenOddConstraintProperty, value);
public static EvenOddConstraint GetEvenOddConstraint(TextBox element) =>
(EvenOddConstraint)element.GetValue(EvenOddConstraintProperty);
#endregion
#region Dependency Properties Methods
private static void DependencyPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TextBox textBox))
throw new Exception("Attached property must be used with TextBox.");
switch (e.Property.Name)
{
case "OnlyNumeric":
{
var castedValue = (NumericFormat?) e.NewValue;
if (castedValue.HasValue)
{
textBox.PreviewTextInput += TextBox_PreviewTextInput;
DataObject.AddPastingHandler(textBox, TextBox_PasteEventHandler);
}
else
{
textBox.PreviewTextInput -= TextBox_PreviewTextInput;
DataObject.RemovePastingHandler(textBox, TextBox_PasteEventHandler);
}
break;
}
case "DefaultValue":
{
var castedValue = (string) e.NewValue;
if (castedValue != null)
{
textBox.TextChanged += TextBox_TextChanged;
}
else
{
textBox.TextChanged -= TextBox_TextChanged;
}
break;
}
}
}
#endregion
private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = (TextBox)sender;
string newText;
if (textBox.SelectionLength == 0)
{
newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
}
else
{
var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);
newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);
}
var evenOddConstraint = GetEvenOddConstraint(textBox);
switch (GetOnlyNumeric(textBox))
{
case NumericFormat.Double:
{
if (double.TryParse(newText, out double number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.Handled = true;
else
e.Handled = false;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.Handled = true;
else
e.Handled = false;
break;
}
}
else
e.Handled = true;
break;
}
case NumericFormat.Int:
{
if (int.TryParse(newText, out int number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.Handled = true;
else
e.Handled = false;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.Handled = true;
else
e.Handled = false;
break;
}
}
else
e.Handled = true;
break;
}
case NumericFormat.Uint:
{
if (uint.TryParse(newText, out uint number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.Handled = true;
else
e.Handled = false;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.Handled = true;
else
e.Handled = false;
break;
}
}
else
e.Handled = true;
break;
}
case NumericFormat.Natural:
{
if (uint.TryParse(newText, out uint number))
{
if (number == 0)
e.Handled = true;
else
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.Handled = true;
else
e.Handled = false;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.Handled = true;
else
e.Handled = false;
break;
}
}
}
else
e.Handled = true;
break;
}
}
}
private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)
{
var textBox = (TextBox)sender;
if (e.DataObject.GetDataPresent(typeof(string)))
{
var clipboardText = (string) e.DataObject.GetData(typeof(string));
var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);
var evenOddConstraint = GetEvenOddConstraint(textBox);
switch (GetOnlyNumeric(textBox))
{
case NumericFormat.Double:
{
if (double.TryParse(newText, out double number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.CancelCommand();
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.CancelCommand();
break;
}
}
else
e.CancelCommand();
break;
}
case NumericFormat.Int:
{
if (int.TryParse(newText, out int number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.CancelCommand();
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.CancelCommand();
break;
}
}
else
e.CancelCommand();
break;
}
case NumericFormat.Uint:
{
if (uint.TryParse(newText, out uint number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.CancelCommand();
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.CancelCommand();
break;
}
}
else
e.CancelCommand();
break;
}
case NumericFormat.Natural:
{
if (uint.TryParse(newText, out uint number))
{
if (number == 0)
e.CancelCommand();
else
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
e.CancelCommand();
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
e.CancelCommand();
break;
}
}
}
else
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
}
private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
var defaultValue = GetDefaultValue(textBox);
var evenOddConstraint = GetEvenOddConstraint(textBox);
switch (GetOnlyNumeric(textBox))
{
case NumericFormat.Double:
{
if (double.TryParse(textBox.Text, out double number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
textBox.Text = defaultValue;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
textBox.Text = defaultValue;
break;
}
}
else
textBox.Text = defaultValue;
break;
}
case NumericFormat.Int:
{
if (int.TryParse(textBox.Text, out int number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
textBox.Text = defaultValue;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
textBox.Text = defaultValue;
break;
}
}
else
textBox.Text = defaultValue;
break;
}
case NumericFormat.Uint:
{
if (uint.TryParse(textBox.Text, out uint number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
textBox.Text = defaultValue;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
textBox.Text = defaultValue;
break;
}
}
else
textBox.Text = defaultValue;
break;
}
case NumericFormat.Natural:
{
if (uint.TryParse(textBox.Text, out uint number))
{
if(number == 0)
textBox.Text = defaultValue;
else
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
textBox.Text = defaultValue;
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
textBox.Text = defaultValue;
break;
}
}
}
else
{
textBox.Text = defaultValue;
}
break;
}
}
}
}
And here is some example of its easy usage:
<TextBox viewHelpers:TextBoxHelper.OnlyNumeric="Double"
viewHelpers:TextBoxHelper.DefaultValue="1"/>
Or
<TextBox viewHelpers:TextBoxHelper.OnlyNumeric="Natural"
viewHelpers:TextBoxHelper.DefaultValue="3"
viewHelpers:TextBoxHelper.EvenOddConstraint="OnlyOdd"/>
Note that my TextBoxHelper resides in the viewHelpers xmlns alias.
I hope that this implementation eases some other one's work :)
You can factor out your common logic to a private method, for example called Initialize
that gets called from both constructors.
Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.
Example:
public Point2D(double x, double y)
{
// Contracts
Initialize(x, y);
}
public Point2D(Point2D point)
{
if (point == null)
throw new ArgumentNullException("point");
// Contracts
Initialize(point.X, point.Y);
}
private void Initialize(double x, double y)
{
X = x;
Y = y;
}
I use this small extension in Swift 5, which keeps it simple and easy to check for any object that is member of UIView.
extension UIView {
var isVisible: Bool {
guard let _ = self.window else {
return false
}
return true
}
}
Then, I just use it as a simple if statement check...
if myView.isVisible {
// do something
}
I hope it helps! :)
It's very simple to control custom messages with the help of the HTML5
oninvalid
event
Here is the code:
User ID
<input id="UserID" type="text" required
oninvalid="this.setCustomValidity('User ID is a must')">
for the linq expression you can use like this :
List<int> list = new List<int>() {1,2,3 };
var result = (from l in list
select l).FirstOrDefault();
for the lambda expression you can use like this
List list = new List() { 1, 2, 3 }; int x = list.FirstOrDefault();
IF you need to softly suppress the delete and backspace keys in your Web app, so that when they are editing / deleting items the page does not get redirected unexpectedly, you can use this code:
window.addEventListener('keydown', function(e) {
var key = e.keyCode || e.which;
if (key == 8 /*BACKSPACE*/ || key == 46/*DELETE*/) {
var len=window.location.href.length;
if(window.location.href[len-1]!='#') window.location.href += "#";
}
},false);
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
There is a NuGet package Microsoft Experimental Collections that contains a class MultiValueDictionary
which does exactly what you need.
Here is a blog post of the creator of the package that describes it further.
Here is another blog post if you're feeling curious.
Example Usage:
MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
If your localhost is not running on the default HTTP port(which is port 80), you need to specify the port in your url to something that corresponds to the port on which your localhost is running. E.g. If your localhost is running on, say port 85, Your url should be
http://10.0.2.2:85
dict.iteritems()
: gives you an iterator. You may use the iterator in other patterns outside of the loop.
student = {"name": "Daniel", "student_id": 2222}
for key,value in student.items():
print(key,value)
('student_id', 2222)
('name', 'Daniel')
for key,value in student.iteritems():
print(key,value)
('student_id', 2222)
('name', 'Daniel')
studentIterator = student.iteritems()
print(studentIterator.next())
('student_id', 2222)
print(studentIterator.next())
('name', 'Daniel')
I'm using a popup to show the map in a new window. I'm using the following url
https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE
HTML snippet
<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>
Use CONCAT_WS().
SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users
WHERE firstlast = "Bob Michael Jones";
The first argument is the separator for the rest of the arguments.
You can simply do this with a bool:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
You could make use of Typescript's optional chaining. Example:
const name = person?.name;
If the property name
exists on the person
object you would get its value but if not it would automatically return undefined.
You could make use of this resource for a better understanding.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
This is the error line:
if (called_from.equalsIgnoreCase("add")) { --->38th error line
This means that called_from
is null. Simple check if it is null above:
String called_from = getIntent().getStringExtra("called");
if(called_from == null) {
called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
// do whatever
} else {
// do whatever
}
That way, if called_from
is null, it'll execute the else
part of your if statement.
You can use HTML5 for this:
<video autoplay></video>
<script>
var onFailSoHard = function(e) {
console.log('Reeeejected!', e);
};
// Not showing vendor prefixes.
navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
// Ready to go. Do some stuff.
};
}, onFailSoHard);
</script>
For anyone else landing here expecting to see a webforms implementation, you want to use the Page Request Manager's endRequest event handler (https://stackoverflow.com/a/1388170/1830512). Here's what I did for my TextBox in a Content Page from a Master Page, please ignore the fact that I didn't use a variable for the control:
var prm = Sys.WebForms.PageRequestManager.getInstance();
function EndRequestHandler() {
if ($get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>') != null) {
$get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>').scrollTop =
$get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>').scrollHeight;
}
}
prm.add_endRequest(EndRequestHandler);
My version:
class String
def upcase_first
return self if empty?
dup.tap {|s| s[0] = s[0].upcase }
end
def upcase_first!
replace upcase_first
end
end
['NASA title', 'MHz', 'sputnik'].map &:upcase_first #=> ["NASA title", "MHz", "Sputnik"]
Check also:
https://www.rubydoc.info/gems/activesupport/5.0.0.1/String%3Aupcase_first
https://www.rubydoc.info/gems/activesupport/5.0.0.1/ActiveSupport/Inflector#upcase_first-instance_method
Just delete module-info.java at your Project Explorer tab.
When I use Vladimir's CALayer solution, and on top of the view I have an animation, like a modal UINavigationController dismissing, I see a lot of glitches happening and having drawing performance issues.
So, another way to achieve this, but without the glitches and performance loss, is to make a custom UIView and implement the drawRect
message like so:
- (void)drawRect:(CGRect)rect
{
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(contextRef, 1);
CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);
CGContextStrokeRect(contextRef, rect);
}
You can also use sprintf:
char str[1024];
sprintf(str, "somtext %s sometext %s", somevar, somevar);
this
is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.
super
allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.
You could try:
var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;
Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses
in the coupon table will be updated.
CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS
Declare @couponCount int,
@CouponName nvarchar(50),
@couponIdFromQuery int
Declare curP cursor For
select COUNT(*) as totalcount , Name as name,couponuse.couponid as couponid from Coupon as coupon
join CouponUse as couponuse on coupon.id = couponuse.couponid
where couponuse.id=@cuponId
group by couponuse.couponid , coupon.Name
OPEN curP
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
While @@Fetch_Status = 0 Begin
print @couponCount
print @CouponName
update Coupon SET NoofUses=@couponCount
where couponuse.id=@couponIdFromQuery
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
End -- End of Fetch
Close curP
Deallocate curP
Hope this helps!
I had to set
Container_height = Element1_height = Element2_height
.Container {
position: relative;
}
.ElementOne, .Container ,.ElementTwo{
width: 283px;
height: 71px;
}
.ElementOne {
position:absolute;
}
.ElementTwo{
position:absolute;
}
Use can use z-index to set which one to be on top.
Python solution
def subtree(node, relationships):
return {
v: subtree(v, relationships)
for v in [x[0] for x in relationships if x[1] == node]
}
For example:
# (child, parent) pairs where -1 means no parent
flat_tree = [
(1, -1),
(4, 1),
(10, 4),
(11, 4),
(16, 11),
(17, 11),
(24, 17),
(25, 17),
(5, 1),
(8, 5),
(9, 5),
(7, 9),
(12, 9),
(22, 12),
(23, 12),
(2, 23),
(26, 23),
(27, 23),
(20, 9),
(21, 9)
]
subtree(-1, flat_tree)
Produces:
{
"1": {
"4": {
"10": {},
"11": {
"16": {},
"17": {
"24": {},
"25": {}
}
}
},
"5": {
"8": {},
"9": {
"20": {},
"12": {
"22": {},
"23": {
"2": {},
"27": {},
"26": {}
}
},
"21": {},
"7": {}
}
}
}
}
Worth mentioning Java 8 approach, using BiConsumer
and lambda functions:
BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) ->
System.out.println(o1 + ", " + o2);
example.forEach(consumer);
Assuming that you've overridden toString
method of the two types if needed.
Most answers are a bit more complicated than necessary, or don't provide the exact format requested.
select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'
If you want a comma, as you normally would, use:
select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'
Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.
Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.
EDIT: my answer makes me think of the classic old man saying "when I was your age..."
If you want to delete object after each response you don't need session,
If you want keep object during user session , There are some ways:
directly add one attribute to session:
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
return "testJsp";
}
and you can get it from controller like this :
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
Make your controller session scoped
@Controller
@Scope("session")
Scope the Objects ,for example you have user object that should be in session every time:
@Component
@Scope("session")
public class User
{
String user;
/* setter getter*/
}
then inject class in each controller that you want
@Autowired
private User user
that keeps class on session.
The AOP proxy injection : in spring -xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="user" class="com.User" scope="session">
<aop:scoped-proxy/>
</bean>
</beans>
then inject class in each controller that you want
@Autowired
private User user
5.Pass HttpSession to method:
String index(HttpSession session) {
session.setAttribute("mySessionAttribute", "someValue");
return "index";
}
6.Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):
public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status by sessionStatus.setComplete();
}
or you can add Model To entire Controller Class like,
@Controller
@SessionAttributes("ShoppingCart")
@RequestMapping("/req")
public class MYController {
@ModelAttribute("ShoppingCart")
public Visitor getShopCart (....) {
return new ShoppingCart(....); //get From DB Or Session
}
}
each one has advantage and disadvantage:
@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.
To access session jsp
<%=session.getAttribute("ShoppingCart.prop")%>
in Jstl :
<c:out value="${sessionScope.ShoppingCart.prop}"/>
in Thymeleaf:
<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>
You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items()
. Then you have both directly in variables and don't need a lookup at all:
for key, value in PIX0.items():
NUM = input("What is the Resolution of %s?" % key)
if NUM == value:
You can of course use that both ways then.
Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.
You can map the strings to enum values, then switch on the enum:
enum Options {
Option_Invalid,
Option1,
Option2,
//others...
};
Options resolveOption(string input);
// ...later...
switch( resolveOption(input) )
{
case Option1: {
//...
break;
}
case Option2: {
//...
break;
}
// handles Option_Invalid and any other missing/unmapped cases
default: {
//...
break;
}
}
Resolving the enum can be implemented as a series of if
checks:
Options resolveOption(std::string input) {
if( input == "option1" ) return Option1;
if( input == "option2" ) return Option2;
//...
return Option_Invalid;
}
Or a map lookup:
Options resolveOption(std::string input) {
static const std::map<std::string, Option> optionStrings {
{ "option1", Option1 },
{ "option2", Option2 },
//...
};
auto itr = optionStrings.find(input);
if( itr != optionStrings.end() ) {
return *itr;
}
return Option_Invalid;
}
A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button
It's only another way to do it but it helped me a lot so I write it here:
Having this data structure:
X=[1,2,3,4]
Y=['a','b','c','d']
XY=zip(X,Y)
Resulting in:
In: XY
Out: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
The more pythonic way to unzip it and go back to the original is this one in my opinion:
x,y=zip(*XY)
But this return a tuple so if you need a list you can use:
x,y=(list(x),list(y))
Use something like:
Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');
There are multiple options. See Split single comma delimited string into rows in Oracle
You just need to add LEVEL in the select list as a column, to get the sequence number to each row returned. Or, ROWNUM would also suffice.
Using any of the below SQLs, you could include them into a FUNCTION.
INSTR in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY instr(str, ',', 1, LEVEL - 1) > 0 7 / STR ---------------------------------------- word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
REGEXP_SUBSTR in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY regexp_substr(str , '[^,]+', 1, LEVEL) IS NOT NULL 7 / STR ---------------------------------------- word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
REGEXP_COUNT in CONNECT BY clause:
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str 5 FROM DATA 6 CONNECT BY LEVEL
Using XMLTABLE
SQL> WITH DATA AS 2 ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual 3 ) 4 SELECT trim(COLUMN_VALUE) str 5 FROM DATA, xmltable(('"' || REPLACE(str, ',', '","') || '"')) 6 / STR ------------------------------------------------------------------------ word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
Using MODEL clause:
SQL> WITH t AS 2 ( 3 SELECT 'word1, word2, word3, word4, word5, word6' str 4 FROM dual ) , 5 model_param AS 6 ( 7 SELECT str AS orig_str , 8 ',' 9 || str 10 || ',' AS mod_str , 11 1 AS start_pos , 12 Length(str) AS end_pos , 13 (Length(str) - Length(Replace(str, ','))) + 1 AS element_count , 14 0 AS element_no , 15 ROWNUM AS rn 16 FROM t ) 17 SELECT trim(Substr(mod_str, start_pos, end_pos-start_pos)) str 18 FROM ( 19 SELECT * 20 FROM model_param MODEL PARTITION BY (rn, orig_str, mod_str) 21 DIMENSION BY (element_no) 22 MEASURES (start_pos, end_pos, element_count) 23 RULES ITERATE (2000) 24 UNTIL (ITERATION_NUMBER+1 = element_count[0]) 25 ( start_pos[ITERATION_NUMBER+1] = instr(cv(mod_str), ',', 1, cv(element_no)) + 1, 26 end_pos[iteration_number+1] = instr(cv(mod_str), ',', 1, cv(element_no) + 1) ) ) 27 WHERE element_no != 0 28 ORDER BY mod_str , 29 element_no 30 / STR ------------------------------------------ word1 word2 word3 word4 word5 word6 6 rows selected. SQL>
You could also use DBMS_UTILITY package provided by Oracle. It provides various utility subprograms. One such useful utility is COMMA_TO_TABLE procedure, which converts a comma-delimited list of names into a PL/SQL table of names.
To avoid linter errors, I use it like this:
render() {
const props = {
dangerouslySetInnerHTML: { __html: '<br/>' },
};
return (
<div {...props}></div>
);
}
Never use escape()
. It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.
If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
However whilst this is enough to put your user_id
in places like the input value
, it's not enough for id
because IDs can only use a limited selection of characters. (And %
isn't among them, so escape()
or even encodeURIComponent()
is no good.)
You could invent your own encoding scheme to put any characters in an ID, for example:
function encodeID(s) {
if (s==='') return '_';
return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
return '_'+match[0].charCodeAt(0).toString(16)+'_';
});
}
But you've still got a problem if the same user_id
occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById
, or worrying about how arbitrary strings are inserted into IDs.
eg.:
function addChut(user_id) {
var log= document.createElement('div');
log.className= 'log';
var textarea= document.createElement('textarea');
var input= document.createElement('input');
input.value= user_id;
input.readonly= True;
var button= document.createElement('input');
button.type= 'button';
button.value= 'Message';
var chut= document.createElement('div');
chut.className= 'chut';
chut.appendChild(log);
chut.appendChild(textarea);
chut.appendChild(input);
chut.appendChild(button);
document.getElementById('chuts').appendChild(chut);
button.onclick= function() {
alert('Send '+textarea.value+' to '+user_id);
};
return chut;
}
You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.
ETA:
I'm using jQuery at the moment as a framework
OK, then consider the jQuery 1.4 creation shortcuts, eg.:
var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...
The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.
You can keep a lookup of user_id
to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id
are restricted.
var chut_lookup= {};
...
function getChut(user_id) {
var key= '_map_'+user_id;
if (key in chut_lookup)
return chut_lookup[key];
return chut_lookup[key]= addChut(user_id);
}
(The _map_
prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object
member names, confuse it.)
You want to enclose it with a scrollView
.
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:
E.g. half-transparency red:
plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")
Ok, sorry for the poor question. gbn got me on the right track. This is what I was looking for in an answer.
SELECT [FirstName], [MiddleName], [LastName], [Date]
FROM #temp
PIVOT
( MIN([Data])
FOR [DBColumnName] IN ([FirstName], [MiddleName], [LastName], [Date])
)AS p
Then I had to use a while statement and build the above statement as a varchar and use dynmaic sql.
Using something like this
SET @fullsql = @fullsql + 'SELECT ' + REPLACE(REPLACE(@fulltext,'(',''),')','')
SET @fullsql = @fullsql + 'FROM #temp '
SET @fullsql = @fullsql + 'PIVOT'
SET @fullsql = @fullsql + '('
SET @fullsql = @fullsql + ' MIN([Data])'
SET @fullsql = @fullsql + ' FOR [DBColumnName] IN '+@fulltext
SET @fullsql = @fullsql + ')'
SET @fullsql = @fullsql + 'AS p'
EXEC (@fullsql)
Having a to build @fulltext using a while loop and select the distinct column names out of the table. Thanks for the answers.
You have to just add the index_col=False
parameter
df1 = pd.read_csv('foo.csv',
header=0,
index_col=False,
names=["dummy", "date", "loc", "x"],
usecols=["dummy", "date", "loc", "x"],
parse_dates=["date"])
print df1
To complete J.F. Sebastian's answer, if you have a list of lists with different lengths, check out this great post from ActiveState. In short:
The built-in function zip does a similar job, but truncates the result to the length of the shortest list, so some elements from the original data may be lost afterwards.
To handle list of lists with different lengths, use:
def transposed(lists):
if not lists: return []
return map(lambda *row: list(row), *lists)
def transposed2(lists, defval=0):
if not lists: return []
return map(lambda *row: [elem or defval for elem in row], *lists)
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
The JTextField
offers a getText()
and a setText()
method - those are for getting and setting the content of the text field.
.yaml
is apparently the official extension, because some applications fail when using .yml
. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml
extension.
I just stumbled across this, as I was used to writing .yml
in Ansible and Docker Compose. Out of habit I used .yml
when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:
- name: Capturing Existing Configurations
find:
paths: /etc/netplan
patterns: "*.yml,*.yaml"
register: _netplan_configs
Yet any files with a .yml
extension get ignored by Netplan in the same way as files with a .bak
extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug
, a config such as 01-netcfg.yml
will fail silently without any meaningful feedback.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours
inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:
When I log in the user I save the access token:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$accessToken = $facebook->getAccessToken();
//save the access token for later
Now when I make requests to facebook I just do something like this:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)
You can't, since dict
is unordered. you can use .popitem()
to get an arbitrary item, but that will remove it from the dict.
I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:
checkFileExistence= function (file){
result=false;
jQuery.ajaxSetup({async:false});
$.get(file)
.done(function() {
result=true;
})
.fail(function() {
result=false;
})
jQuery.ajaxSetup({async:true});
return(result);
},
You can set data to session simply like this in Codeigniter:
$this->load->library('session');
$this->session->set_userdata(array(
'user_id' => $user->uid,
'username' => $user->username,
'groupid' => $user->groupid,
'date' => $user->date_cr,
'serial' => $user->serial,
'rec_id' => $user->rec_id,
'status' => TRUE
));
and you can get it like this:
$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');
bind
is deprecated. Use on
:
$("#textarea").on('change keyup paste', function() {
// your code here
});
Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
var currentVal = $(this).val();
if(currentVal == oldVal) {
return; //check to prevent multiple simultaneous triggers
}
oldVal = currentVal;
//action to be performed on textarea changed
alert("changed!");
});
You can also use:
var obj = {
alert: alert.bind(window)
};
obj.alert('I´m an alert!!');