It's as simple as:
>>> lists = [[1, 2], [3, 4]]
>>> np.array(lists)
array([[1, 2],
[3, 4]])
I found the http://css-tricks.com/forums/topic/how-to-add-shadows-on-all-4-sides-of-a-block-with-css/ site.
.allSides
{
width:350px;height:200px;
border: solid 1px #555;
background-color: #eed;
box-shadow: 0 0 10px rgba(0,0,0,0.6);
-moz-box-shadow: 0 0 10px rgba(0,0,0,0.6);
-webkit-box-shadow: 0 0 10px rgba(0,0,0,0.6);
-o-box-shadow: 0 0 10px rgba(0,0,0,0.6);
}
Adding to the top answer:
after the 2nd method did not initially seem to work I did some additional tinkering and have found the solution.
TLDR; the top answer's 2nd solution almost works, but for some versions of xCode ctrl+dragging to "Top Layout Guide" and selecting Vertical Spacing does nothing. However, by first adjusting the size of the Table View and then selecting "Top Space to Top Layout Guide" works
Drag a blank ViewController onto the storyboard.
Drag a UITableView object into the View. (Not UITableViewController). Position it in the very center using the blue layout guides.
Create your custom subclass of UIViewController, and add the <UITableViewDataSource, UITableViewDelegate>
protocols. Don't forget to set your storyboard's ViewController to this class in the Identity Inspector.
Create an outlet for your TableView in your implementation file, and name it "tableView"
Now for the part of not clipping into the status bar.
Now you can set up your table view like normal, and it won't clip the status bar!
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
for using code, for example to check what modules in Hackerrank etc :
import os
os.system("pip list")
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
For me, the problem was using svg images. I switched them to png and it worked.
There is an isConnected function in BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java
If you want to know if the a bounded(paired) device is currently connected or not, the following function works fine for me:
public static boolean isConnected(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("isConnected", (Class[]) null);
boolean connected = (boolean) m.invoke(device, (Object[]) null);
return connected;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
GCM/APNS are only for Chrome and Safari respectively.
I think you may be looking for Notification
:
https://developer.mozilla.org/en-US/docs/Web/API/notification
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
$(document).on('click', 'selector', handler);
Where click
is an event name, and handler
is an event handler, like reference to a function or anonymous function function() {}
PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document
.
At last I fixed it simply using:
display: table;
Similarly with yum
package manager
yum install libcurl-devel
If you use dnf
, use
dnf install libcurl-devel
There's typically two levels of buffering involved:
The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.
However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.
If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.
So, in order to help with that you have the flush
and fsync
methods, on their respective objects.
The first, flush
, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.
Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.
To do that, you need to call the os.fsync
method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.
Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.
Addendum in 2018.
Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.
I think it is better to change default port of Skype.
Open skype. Go to Tools, Options, Connections, change the port.
There is an alternative to repeating the CONCAT
expression or using subqueries. You can make use of the HAVING
clause, which recognizes column aliases.
SELECT
neededfield, CONCAT(firstname, ' ', lastname) AS firstlast
FROM
users
HAVING firstlast = "Bob Michael Jones"
Here is a working SQL Fiddle.
Try this -
select * from table where id in (3,4) or [name] in ('andy','paul');
From Swift2.0, Apple says:
"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"
<a href="./">Folder</a>
Here's an example:
class RenameOldTableToNewTable < ActiveRecord::Migration
def self.up
rename_table :old_table_name, :new_table_name
end
def self.down
rename_table :new_table_name, :old_table_name
end
end
I had to go and rename the model declaration file manually.
Edit:
In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder
knows how to reverse rename_table migrations, so you can do this:
class RenameOldTableToNewTable < ActiveRecord::Migration
def change
rename_table :old_table_name, :new_table_name
end
end
(You still have to go through and manually rename your files.)
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
In pydev eclipse plugin, you may want to set the environment variable for DYLD. The path can be set as shown in
import math
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print (("This equation has one solutions: "), x)
#add the extra () above or it does not show the answer just the text.
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Below you have some VALID html5 example document. The type
attribute in script
tag is not mandatory in HTML5.
You use jquery by $
charater. Put libraries (like jquery) in <head>
tag - but your script put allways at the bottom of document (<body>
tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src
attribute in bottom script tag to include you script file instead of putting direct js code like above.
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Example</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div>Im the content</div>_x000D_
_x000D_
<script>_x000D_
alert( $('div').text() ); // show message with div content_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
@OneToMany(mappedBy = 'parent', cascade= CascadeType.ALL, orphanRemoval = true)
List<Child> children = new ArrayList<>();
I experienced the same error when I was adding child object to the existing list of Child Objects.
childService.saveOrUpdate(child);
parent.addToChildren(child);
parentService.saveOrUpdate(parent);
What resolved my problem is changing to:
child = childService.saveOrUpdate(child);
Now the child is revive with other details as well and it worked fine.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called Properties.Resources
that gives you access to all your resources, so my code ended up being as simple as:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
Done! Finished! Everything is simple when you know how, isn't it?
This code seems completely unnecessary:
String serverURLS = getRecipientURL(message);
serverURLS = "https:\\\\abc.my.domain.com:55555\\update";
if (serverURLS != null){
serverURL = new URL(serverURLS);
}
serverURLS
is assigned the result of getRecipientURL(message)
serverURLS
, making the previous statement a dead storeif (serverURLS != null)
evaluates to true
, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL
. It is impossible for if (serverURLS != null)
to evaluate to false
!serverURLS
beyond the previous line of code.You could replace all of this with just:
serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
The first solution works well. I want to add one small detail here. Make sure the variable you are trying to replace/update it will has to be a type str. My mysql type is decimal but I had to make the parameter variable as str to be able to execute the query.
temp = "100"
myCursor.execute("UPDATE testDB.UPS SET netAmount = %s WHERE auditSysNum = '42452'",(temp,))
myCursor.execute(var)
SELECT * FROM mysql.general_log WHERE command_type ='Query' LIMIT total;
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)
Reload the datasource of your grid after the update
myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;
I made the regexp for european phone numbers, and it is specific against dial prefix vs length of number.
const PhoneEuropeRegExp = () => {
// eu phones map https://en.wikipedia.org/wiki/Telephone_numbers_in_Europe
const phonesMap = {
"43": [4, 13],
"32": [8, 10],
"359": [7, 9],
"385": [8, 9],
"357": 8,
"420": 9,
"45": 8,
"372": 7,
"358": [5, 12],
"33": 9,
"350": 8,
"49": [3, 12],
"30": 10,
"36": [8, 9],
"354": [7, 9],
"353": [7, 9],
"39": [6, 12],
"371": 8,
"423": [7, 12],
"370": 8,
"352": 8,
"356": 8,
"31": 9,
"47": [4, 12],
"48": 9,
"351": 9,
"40": 9,
"421": 9,
"386": 8,
"34": 9,
"46": [6, 9],
};
const regExpBuilt = Object.keys(phonesMap)
.reduce(function(prev, key) {
const val = phonesMap[key];
if (Array.isArray(val)) {
prev.push("(\\+" + key + `[0-9]\{${val[0]},${val[1]}\})`);
} else {
prev.push("(\\+" + key + `[0-9]\{${val}\})`);
}
return prev;
}, [])
.join("|");
return new RegExp(`^(${regExpBuilt})$`);
};
alert(PhoneEuropeRegExp().test("+420123456789"))
Hide And Show parent view of Activity Indicator
constructor(props) {
super(props)
this.state = {
isHidden: false
}
}
Hide and Show as Follow
{
this.state.isHidden ? <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
Full reference
render() {
return (
<View style={style.mainViewStyle}>
<View style={style.signinStyle}>
<TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
<TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
<TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
<TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
<TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
<Button style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
</View>
{
this.state.isHidden ? <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
</View>
);
}
On Button presss set state as follow
onSignupPress() {
this.setState({isHidden: true})
}
When you need to hide
this.setState({isHidden: false})
.navbar-nav > li > a {padding-top:7px !important; padding-bottom:7px !important;}
.navbar {min-height:32px !important;}
.navbar-brand{padding-top:7px !important; max-height: 24px; }
.navbar .navbar-toggle { margin-top: 0px; margin-bottom: 0px; padding: 8px 9px; }
In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:
var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true
or
var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false
or
var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false
References for syntax:
This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH
# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`
ssh \
-o StrictHostKeyChecking=no \
-i ~/.ssh/id_rsa \
[email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!
EOF
The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.
<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}
call it like this:
x=AnalyseArray(list);
or pass a copy of ArrayList:
x=AnalyseArray(list.clone());
For one dimension array
Controller:
using Newtonsoft.Json;
var listOfIds = _dbContext.Countries.Where(x => x.Id == Country.USA).First().Cities.Where(x => x.IsCoveredByCompany).Select(x => x.Id).ToList();
string strArrayForJS = JsonConvert.SerializeObject(listOfIds); // [1,2,6,7,8,18,25,61,129]
//Now pass it to the view through the model or ViewBag
View:
<script>
$(function () {
var myArray = @HTML.Raw(Model.strArrayForJS);
console.log(myArray); // [1, 2, 6, 7, 8, 18, 25, 61, 129]
console.log(typeof (myArray)); //object
});
</script>
def pzip(c, seq):
result = []
for item in seq:
for i in range(len(item)+1):
result.append(item[i:]+c+item[:i])
return result
def perm(line):
seq = [c for c in line]
if len(seq) <=1 :
return seq
else:
return pzip(seq[0], perm(seq[1:]))
ORGANIZING VALUES:
In Python, lists' order too can be manipulated with sort, organizing your variables in numerical/alphabetical order: Temporarily:
print(sorted(my_list))
Permanent:
my_list.sort(), print(my_list)
You can sort with the flag "reverse=True":
print(sorted(my_list, reverse=True))
or
my_list.sort(reverse=True), print(my_list)
WITHOUT ORGANIZING
Maybe you do not want to sort values, but only reverse the values. Then we can do it like this:
print(list(reversed(my_list)))
**Numbers have priority over alphabet in listing order. The Python values' organization is awesome.
Edit 1: a mistaken moderator claimed that my answer was a copy and deleted my old post.
jQuery $.extend(obj1, obj2)
would merge 2 objects for you, but you should really be using an array.
var alertsObj = {
1: {app:'helloworld','message'},
2: {app:'helloagain',message:'another message'}
};
var alertArr = [
{app:'helloworld','message'},
{app:'helloagain',message:'another message'}
];
var newAlert = {app:'new',message:'message'};
$.extend(alertsObj, newAlert);
alertArr.push(newAlert);
As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.
--EDIT--
Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/
It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.
I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.
you can create a service and generate excel on server and then allow clients download excel. cos buying excel license for 1000 ppl, it is better to have one license for server.
hope that helps.
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
First the good news. This code does what you want (please note the "line numbers")
Sub a()
10: On Error GoTo ErrorHandler
20: DivisionByZero = 1 / 0
30: Exit Sub
ErrorHandler:
41: If Err.Number <> 0 Then
42: Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
43: MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
44: End If
50: Resume Next
60: End Sub
When it runs, the expected MsgBox is shown:
And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.
However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.
HTH!
Interesting question. The problem is that height() does not accept a callback, so you wouldn't be able to fire up a callback. Use either animate() or css() to set the height and then trigger the custom event in the callback. Here is an example using animate() , tested and works (demo), as a proof of concept :
$('#test').bind('style', function() {
alert($(this).css('height'));
});
$('#test').animate({height: 100},function(){
$(this).trigger('style');
});
If u are using Android X: https://material.io/develop/android/docs/getting-started/ follow the instruction here
when the latest library is
implementation 'com.google.android.material:material:1.2.1'
Update : Get latest material design library from here https://maven.google.com/web/index.html?q=com.google.android.material#com.google.android.material:material
For older SDK
Add the design support library version as same as of your appcompat-v7 library
You can get the latest library from android developer documentation https://developer.android.com/topic/libraries/support-library/packages#design
implementation 'com.android.support:design:28.0.0'
In the vast majority of cases, the "stringification" of a SQLAlchemy statement or query is as simple as:
print(str(statement))
This applies both to an ORM Query
as well as any select()
or other statement.
Note: the following detailed answer is being maintained on the sqlalchemy documentation.
To get the statement as compiled to a specific dialect or engine, if the statement itself is not already bound to one you can pass this in to compile():
print(statement.compile(someengine))
or without an engine:
from sqlalchemy.dialects import postgresql
print(statement.compile(dialect=postgresql.dialect()))
When given an ORM Query
object, in order to get at the compile()
method we only need access the .statement accessor first:
statement = query.statement
print(statement.compile(someengine))
with regards to the original stipulation that bound parameters are to be "inlined" into the final string, the challenge here is that SQLAlchemy normally is not tasked with this, as this is handled appropriately by the Python DBAPI, not to mention bypassing bound parameters is probably the most widely exploited security holes in modern web applications. SQLAlchemy has limited ability to do this stringification in certain circumstances such as that of emitting DDL. In order to access this functionality one can use the 'literal_binds' flag, passed to compile_kwargs
:
from sqlalchemy.sql import table, column, select
t = table('t', column('x'))
s = select([t]).where(t.c.x == 5)
print(s.compile(compile_kwargs={"literal_binds": True}))
the above approach has the caveats that it is only supported for basic
types, such as ints and strings, and furthermore if a bindparam
without a pre-set value is used directly, it won't be able to
stringify that either.
To support inline literal rendering for types not supported, implement
a TypeDecorator
for the target type which includes a
TypeDecorator.process_literal_param
method:
from sqlalchemy import TypeDecorator, Integer
class MyFancyType(TypeDecorator):
impl = Integer
def process_literal_param(self, value, dialect):
return "my_fancy_formatting(%s)" % value
from sqlalchemy import Table, Column, MetaData
tab = Table('mytable', MetaData(), Column('x', MyFancyType()))
print(
tab.select().where(tab.c.x > 5).compile(
compile_kwargs={"literal_binds": True})
)
producing output like:
SELECT mytable.x
FROM mytable
WHERE mytable.x > my_fancy_formatting(5)
There is a method specifically for this purpose:
data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
Try this
<input name="selector[]" id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input name="selector[]" id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input name="selector[]" id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input name="selector[]" id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />
function
$(function(){
$('#save_value').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
You can use
%matplotlib qt
If you got the error ImportError: Failed to import any qt binding
then install PyQt5 as: pip install PyQt5
and it works for me.
Starting with Spring Security version 3.2, the custom functionality that has been implemented by some of the older answers, exists out of the box in the form of the @AuthenticationPrincipal
annotation that is backed by AuthenticationPrincipalArgumentResolver
.
An simple example of it's use is:
@Controller
public class MyController {
@RequestMapping("/user/current/show")
public String show(@AuthenticationPrincipal CustomUser customUser) {
// do something with CustomUser
return "view";
}
}
CustomUser needs to be assignable from authentication.getPrincipal()
Here are the corresponding Javadocs of AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver
You can easily do this by:
::variableName.isInitialized
or
this::variableName.isInitialized
But if you are inside a listener or inner class, do this:
this@OuterClassName::variableName.isInitialized
Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:
class Test {
lateinit var str:String
}
And to check if str is initialized:
What we are doing here: checking isInitialized
for field str
of Test
class in Test2
class.
And we get an error backing field of var is not accessible at this point.
Check a question already raised about this.
If the problem is that you don't have access to SQL Server and now you are using mixed mode to enable sa or grant an account admin privileges, then it is far easier just to uninstall SQL Server and reinstall.
Just spent a good few days trying to get this to work on High Sierra 10.13.1. The gdb 8.1 version from homebrew would not work no matter what I tried. Ended up installing gdb 8.0.1 via macports and this miraculously worked (after jumping through all of the other necessary hoops related to codesigning etc).
One additional issue is that in Eclipse you will get extraneous single quotes around all of your program arguments which can be worked around by providing the arguments inside .gdbinit instead.
My C++ templates were there all along, it was my C# ones that were missing.
Similar to CSharpie, after trying many modify/re-installs, oddly the following finally worked for me :
- run the installer, but un-select 'Desktop development with C++'.
- allow installer to complete
- run the installer again, and select 'Desktop development with C++'.
- allow installer to complete
if you invoke .equals()
on null
you will get NullPointerException
So it is always advisble to check nullity before invoking method where ever it applies
if(str!=null && str.equals("hi")){
//str contains hi
}
Also See
It's possible to inject instance of ApplicationContext
class by using SpringClassRule
and SpringMethodRule
rules. It might be very handy if you would like to use
another non-Spring runners. Here's an example:
@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {
@ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
private ApplicationContext context;
@Test
public void shouldInjectContext() {
}
}
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
As for me, it's a bad and quick solution for your problem :
android {
lintOptions {
abortOnError false
}
}
Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.
This problem most frequently occurring when:
Find your bugs by Inspect Code
in Android Studio: Improve Your Code with Lint
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo
depend on itself, but of course, make
is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.
GNU make knows how to run gcc
to produce an executable out of a set of .c
and .h
files, so maybe all you really need amounts to
foo: $(wildcard *.h) $(wildcard *.c)
You could also have problems if the string has <
, >
or &
chars in it, etc. Pass it to cgi.escape()
to deal with those.
http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape
Here is a full example of an axios.post request with custom headers
var postData = {_x000D_
email: "[email protected]",_x000D_
password: "password"_x000D_
};_x000D_
_x000D_
let axiosConfig = {_x000D_
headers: {_x000D_
'Content-Type': 'application/json;charset=UTF-8',_x000D_
"Access-Control-Allow-Origin": "*",_x000D_
}_x000D_
};_x000D_
_x000D_
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)_x000D_
.then((res) => {_x000D_
console.log("RESPONSE RECEIVED: ", res);_x000D_
})_x000D_
.catch((err) => {_x000D_
console.log("AXIOS ERROR: ", err);_x000D_
})
_x000D_
I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false}
property for window.addEventListener
, which is recommended as the only working solution, for example here.
In the end, after many tries, I found a way that works for me in both Firefox and Chrome:
window.addEventListener('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 37: // left
case 39: // right
e.preventDefault();
break;
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Quote for EventTarget.addEventListener()
from MDN
options Optional
An options object specifies characteristics about the event listener. The available options are:capture
ABoolean
indicating that events of this type will be dispatched to the registeredlistener
before being dispatched to anyEventTarget
beneath it in the DOM tree.
once
...
passive
ABoolean
that, if true, indicates that the function specified bylistener
will never callpreventDefault()
. If a passive listener does callpreventDefault()
, the user agent will do nothing other than generate a console warning. ...
For PHP users :)
Make sure you have 'PHP Symbol' plugin then you can get all methods and class in 'OUTLINE' Sidebar's Bottom.
Press ? command + ? shift + O in "macOS" or Ctrl + Shift + O while using "Windows"
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.
In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.
You pick what matters the most to you.
Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.
A slight modification to @Galwegian's answer - which turns e.g. St Elizabeth's
into St Elizabeth'S
.
This modification keeps apostrophe-s as lowercase where the s comes at the end of the string provided or the s is followed by a space (and only in those circumstances).
create function properCase(@text as varchar(8000))
returns varchar(8000)
as
begin
declare @reset int;
declare @ret varchar(8000);
declare @i int;
declare @c char(1);
declare @d char(1);
if @text is null
return null;
select @reset = 1, @i = 1, @ret = '';
while (@i <= len(@text))
select
@c = substring(@text, @i, 1),
@d = substring(@text, @i+1, 1),
@ret = @ret + case when @reset = 1 or (@reset=-1 and @c!='s') or (@reset=-1 and @c='s' and @d!=' ') then upper(@c) else lower(@c) end,
@reset = case when @c like '[a-za-z]' then 0 when @c='''' then -1 else 1 end,
@i = @i + 1
return @ret
end
It turns:
st elizabeth's
into St Elizabeth's
o'keefe
into O'Keefe
o'sullivan
into O'Sullivan
Others' comments that different solutions are preferable for non-English input remain the case.
A UITextField's height is not adjustable in Attributes Inspector only when it has the default rounded corners border style, but adding a height constraint (plus any other constraints which are required to satisfy the autolayout system - often by simply using Add Missing Constraints) to it and adjusting the constraint will adjust the textfield's height. If you don't want constraints, the constraints can be removed (Clear Constraints) and the textfield will remain at the adjusted height.
Works like a charm.
I use varargs frequently for constructors that can take some sort of filter object. For example, a large part of our system based on Hadoop is based on a Mapper that handles serialization and deserialization of items to JSON, and applies a number of processors that each take an item of content and either modify and return it, or return null to reject.
For reference using the [EnableCors()]
approach will not work if you intercept the Message Pipeline using a DelegatingHandler
. In my case was checking for an Authorization
header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()]
had no effect.
In the end found an example CrossDomainHandler
class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.
public class CrossDomainHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
To use it add it to the list of registered message handlers
config.MessageHandlers.Add(new CrossDomainHandler());
Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions]
IHttpActionResult
method on the Controller.
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
You could merge the sub-DataFrame (with just those columns):
df2[list('xab')] # df2 but only with columns x, a, and b
df1.merge(df2[list('xab')])
This should do the trick for you: put include tag inside of a block section.
page1.html:
{% extends "base1.html" %}
{% block foo %}
{% include "commondata.html" %}
{% endblock %}
page2.html:
{% extends "base2.html" %}
{% block bar %}
{% include "commondata.html" %}
{% endblock %}
For UUID4 I make it that there are approximately as many IDs as there are grains of sand in a cube-shaped box with sides 360,000km long. That's a box with sides ~2 1/2 times longer than Jupiter's diameter.
Working so someone can tell me if I've messed up units:
Even if u use DailyRollingFileAppender like @gedevan suggested, u will still get logname.log.2008-10-10
(After a day, because the previous day log will get archived and the date will be concatenated to it's filename).
So if u want .log at the end, u'll have to do it like this on the DatePattern:
log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm'.log'
for Xcode 8:
What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.
Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.
I once saved over 50GB doing this since I did so much testing on older iOS versions.
try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know
A solution is to use background-position to mimic the gradient transition. This solution was used in Twitter Bootstrap a few months ago.
Update
http://codersblock.blogspot.fr/2013/12/gradient-animation-trick.html?showComment=1390287622614
Here is a quick example:
Link state
.btn {
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 12px;
font-weight: 300;
position: relative;
display: inline-block;
text-decoration: none;
color: #fff;
padding: 20px 40px;
background-image: -moz-linear-gradient(top, #50abdf, #1f78aa);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#50abdf), to(#1f78aa));
background-image: -webkit-linear-gradient(top, #50abdf, #1f78aa);
background-image: -o-linear-gradient(top, #50abdf, #1f78aa);
background-image: linear-gradient(to bottom, #50abdf, #1f78aa);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50abdf', endColorstr='#ff1f78aa', GradientType=0);
background-repeat: repeat-y;
background-size: 100% 90px;
background-position: 0 -30px;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
Hover state
.btn:hover {
background-position: 0 0;
}
What is the source of these values?
The "source" of the coefficients posted are the NTSC specifications which can be seen in Rec601 and Characteristics of Television.
The "ultimate source" are the CIE circa 1931 experiments on human color perception. The spectral response of human vision is not uniform. Experiments led to weighting of tristimulus values based on perception. Our L, M, and S cones1 are sensitive to the light wavelengths we identify as "Red", "Green", and "Blue" (respectively), which is where the tristimulus primary colors are derived.2
The linear light3 spectral weightings for sRGB (and Rec709) are:
These are specific to the sRGB and Rec709 colorspaces, which are intended to represent computer monitors (sRGB) or HDTV monitors (Rec709), and are detailed in the ITU documents for Rec709 and also BT.2380-2 (10/2018)
FOOTNOTES
(1) Cones are the color detecting cells of the eye's retina.
(2) However, the chosen tristimulus wavelengths are NOT at the "peak" of each cone type - instead tristimulus values are chosen such that they stimulate on particular cone type substantially more than another, i.e. separation of stimulus.
(3) You need to linearize your sRGB values before applying the coefficients. I discuss this in another answer here.
You needed to iconv your source.
That said, the TEX-based compiler invoked by latex
doesn't really support variable-length encodings; it needs big libraries that tell it that certain bytes go together. Xelatex is Unicode-aware and works much better.
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
html {height: 50%; border: solid red 3px; }_x000D_
body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="container">_x000D_
<p><html> is red</p>_x000D_
<p><body> is green</p>_x000D_
<p><div> is blue</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.
About CSS units: w3schools: CSS units
A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/
To convert a string to a variable:
x <- 42
eval(parse(text = "x"))
[1] 42
And the opposite:
x <- 42
deparse(substitute(x))
[1] "x"
’
(Unicode codepoint U+2019 RIGHT SINGLE QUOTATION MARK
) is encoded in UTF-8 as bytes:
0xE2 0x80 0x99
.
’
(Unicode codepoints U+00E2 U+20AC U+2122
) is encoded in UTF-8 as bytes:
0xC3 0xA2
0xE2 0x82 0xAC
0xE2 0x84 0xA2
.
These are the bytes your browser is actually receiving in order to produce ’
when processed as UTF-8.
That means that your source data is going through two charset conversions before being sent to the browser:
The source ’
character (U+2019
) is first encoded as UTF-8 bytes:
0xE2 0x80 0x99
those individual bytes were then being mis-interpreted and decoded to Unicode codepoints U+00E2 U+20AC U+2122
by one of the Windows-125X charsets (1252, 1254, 1256, and 1258 all map 0xE2 0x80 0x99
to U+00E2 U+20AC U+2122
), and then those codepoints are being encoded as UTF-8 bytes:
0xE2
-> U+00E2
-> 0xC3 0xA2
0x80
-> U+20AC
-> 0xE2 0x82 0xAC
0x99
-> U+2122
-> 0xE2 0x84 0xA2
You need to find where the extra conversion in step 2 is being performed and remove it.
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
If you are managing the Hibernate session manually, you may want to look into sessionFactory.getCurrentSession() and associated docs here:
http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html
In windows, this command works for me to show current activity name
adb shell dumpsys window windows | find "mCurrentFocus"
Output:
mCurrentFocus=Window{a43a55b u0 com.android.contacts/com.android.contacts.activities.TwelveKeyDialer}
Other solutions with "grab" produce error in my windows pc
'grep' is not recognized as an internal or external command, operable program or batch file.
So, using "find" solve the error in my case.
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
Replace URLs in text with HTML links, ignore the URLs within a href/pre tag. https://github.com/JimLiu/auto-link
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
Try to code below,
String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
for(int y = 0; y < 3; y++)
{
shades[i][y] = value;
}
}
I consider that the most Pythonic way is to use a list comprehension instead of map
and filter
. The reason is that list comprehensions are clearer than map
and filter
.
In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension
In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter
In [3]: odd_cubes == odd_cubes_alt
Out[3]: True
As you an see, a comprehension does not require extra lambda
expressions as map
needs. Furthermore, a comprehension also allows filtering easily, while map
requires filter
to allow filtering.
Alternatives to the excellent sed
answer by jfgagne, and which don't include the matching line :
awk '/TERMINATE/ {y=1;next} y'
( https://stackoverflow.com/a/18166628 )awk '/TERMINATE/ ? c++ : c'
( https://stackoverflow.com/a/23984891 )perl -ne 'print unless 1 .. /TERMINATE/'
( https://stackoverflow.com/a/18167194 )Expanding on Mark's suggestions...
Method 3
Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.
export class App implements DoCheck {
person = { first: "Sally", last: "Jones" };
oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning
ngDoCheck() {
// Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
for (let prop in this.person) {
if (this.oldPerson[prop] !== this.person[prop]) {
console.log(`person.${prop} changed: ${this.person[prop]}`);
this.oldPerson[prop] = this.person[prop];
}
}
}
Using the useEffect hook, we can easily implement delay feature while typing in input field:
import React, { useState, useEffect } from 'react'
function Search() {
const [searchTerm, setSearchTerm] = useState('')
// Without delay
// useEffect(() => {
// console.log(searchTerm)
// }, [searchTerm])
// With delay
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
console.log(searchTerm)
// Send Axios request here
}, 3000)
// Cleanup fn
return () => clearTimeout(delayDebounceFn)
}, [searchTerm])
return (
<input
autoFocus
type='text'
autoComplete='off'
className='live-search-field'
placeholder='Search here...'
onChange={(e) => setSearchTerm(e.target.value)}
/>
)
}
export default Search
On MAC you can do sout + return
or ?+j
(cmd+j) opens live template suggestions, enter sout
to choose System.out.println();
You can always use STATUS command to get to know Current database & Current User
At the moment, this can be done as follows
$ANDROID_HOME/build-tools/28.0.3/aapt dump badging /<path to>/<app name>.apk
In General, it will be:
$ANDROID_HOME/build-tools/<version_of_build_tools>/aapt dump badging /<path to>/<app name>.apk
Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml
<module name="SuppressionCommentFilter"/>
and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.
//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON
Or even better, use this more tweaked version:
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
<property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
which allows you to turn off specific checks for specific lines of code:
//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch
*Note: you'll also have to add the FileContentsHolder
:
<module name="FileContentsHolder"/>
See also
<module name="SuppressionFilter">
<property name="file" value="docs/suppressions.xml"/>
</module>
under the SuppressionFilter
section on that same page, which allows you to turn off individual checks for pattern matched resources.
So, if you have in your checkstyle.xml:
<module name="ParameterNumber">
<property name="id" value="maxParameterNumber"/>
<property name="max" value="3"/>
<property name="tokens" value="METHOD_DEF"/>
</module>
You can turn it off in your suppression xml file with:
<suppress id="maxParameterNumber" files="YourCode.java"/>
Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnings
java annotation. To do this, you will need to add two new modules (SuppressWarningsFilter
and SuppressWarningsHolder
) in your configuration file:
<module name="Checker">
...
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
...
<module name="SuppressWarningsHolder" />
</module>
</module>
Then, within your code you can do the following:
@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {
or, for multiple suppressions:
@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {
NB: The "checkstyle:
" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.
I am using Laravel 5.8. Task was to make pagination like next http://some-url/page-N instead of http://some-url?page=N. It cannot be accomplished by editing /resources/views/vendor/pagination/blade-name-here.blade.php template (it could be generated by php artisan vendor:publish --tag=laravel-pagination command). Here I had to extend core classes.
My model used paginate method of DB instance, like next:
$essays = DB::table($this->table)
->select('essays.*', 'categories.name', 'categories.id as category_id')
->join('categories', 'categories.id', '=', 'essays.category_id')
->where('category_id', $categoryId)
->where('is_published', $isPublished)
->orderBy('h1')
->paginate( // here I need to extend this method
$perPage,
'*',
'page',
$page
);
Let's get started. paginate() method placed inside of \Illuminate\Database\Query\Builder and returns Illuminate\Pagination\LengthAwarePaginator object. LengthAwarePaginator extends Illuminate\Pagination\AbstractPaginator, which has public function url($page) method, which need to be extended:
/**
* Get the URL for a given page number.
*
* @param int $page
* @return string
*/
public function url($page)
{
if ($page <= 0) {
$page = 1;
}
// If we have any extra query string key / value pairs that need to be added
// onto the URL, we will put them in query string form and then attach it
// to the URL. This allows for extra information like sortings storage.
$parameters = [$this->pageName => $page];
if (count($this->query) > 0) {
$parameters = array_merge($this->query, $parameters);
}
// this part should be overwrited
return $this->path
. (Str::contains($this->path, '?') ? '&' : '?')
. Arr::query($parameters)
. $this->buildFragment();
}
Step by step guide (part of information I took from this nice article):
2.1 CustomConnection.php file:
namespace App\Extended;
use \Illuminate\Database\MySqlConnection;
/**
* Class CustomConnection
* @package App\Extended
*/
class CustomConnection extends MySqlConnection {
/**
* Get a new query builder instance.
*
* @return \App\Extended\CustomQueryBuilder
*/
public function query() {
// Here core QueryBuilder is overwrited by CustomQueryBuilder
return new CustomQueryBuilder(
$this,
$this->getQueryGrammar(),
$this->getPostProcessor()
);
}
}
2.2 CustomLengthAwarePaginator.php file - this file contains main part of information which need to be overwrited:
namespace App\Extended;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/**
* Class CustomLengthAwarePaginator
* @package App\Extended
*/
class CustomLengthAwarePaginator extends LengthAwarePaginator
{
/**
* Get the URL for a given page number.
* Overwrited parent class method
*
*
* @param int $page
* @return string
*/
public function url($page)
{
if ($page <= 0) {
$page = 1;
}
// here the MAIN overwrited part of code BEGIN
$parameters = [];
if (count($this->query) > 0) {
$parameters = array_merge($this->query, $parameters);
}
$path = $this->path . "/{$this->pageName}-$page";
// here the MAIN overwrited part of code END
if($parameters) {
$path .= (Str::contains($this->path, '?') ? '&' : '?') . Arr::query($parameters);
}
$path .= $this->buildFragment();
return $path;
}
}
2.3 CustomQueryBuilder.php file:
namespace App\Extended;
use Illuminate\Container\Container;
use \Illuminate\Database\Query\Builder;
/**
* Class CustomQueryBuilder
* @package App\Extended
*/
class CustomQueryBuilder extends Builder
{
/**
* Create a new length-aware paginator instance.
* Overwrite paginator's class, which will be used for pagination
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected function paginator($items, $total, $perPage, $currentPage, $options)
{
// here changed
// CustomLengthAwarePaginator instead of LengthAwarePaginator
return Container::getInstance()->makeWith(CustomLengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
In /config/app.php need to change db provider:
'providers' => [
// comment this line
// illuminate\Database\DatabaseServiceProvider::class,
// and add instead:
App\Providers\CustomDatabaseServiceProvider::class,
In your controller (or other place where you receive paginated data from db) you need to change pagination's settings:
// here are paginated results
$essaysPaginated = $essaysModel->getEssaysByCategoryIdPaginated($id, config('custom.essaysPerPage'), $page);
// init your current page url (without pagination part)
// like http://your-site-url/your-current-page-url
$customUrl = "/my-current-url-here";
// set url part to paginated results before showing to avoid
// pagination like http://your-site-url/your-current-page-url/page-2/page-3 in pagination buttons
$essaysPaginated->withPath($customUrl);
Add pagination links in your view (/resources/views/your-controller/your-blade-file.blade.php), like next:
<nav>
{!!$essays->onEachSide(5)->links('vendor.pagination.bootstrap-4')!!}
</nav>
ENJOY! :) Your custom pagination should work now
The main difference between localStorage
and sessionStorage
is that sessionStorage
is unique per tab. If you close the tab the sessionStorage
gets deleted, localStorage
does not. Also you cannot communicate between tabs :)
Another subtle difference is that for example on Safari (8.0.3) localStorage
has a limit of 2551 k characters but sessionStorage
has unlimited storage
On Chrome (v43) both localStorage
and sessionStorage
are limited to 5101 k characters (no difference between normal / incognito mode)
On Firefox both localStorage
and sessionStorage
are limited to 5120 k characters (no difference between normal / private mode )
No difference in speed whatsoever :)
There's also a problem with Mobile Safari and Mobile Chrome, Private Mode Safari & Chrome have a maximum space of 0KB
Same functionality i recently achieved using below function.
I wanted to enable SAVE button on edit.
Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.
Hope it helps you.
function checkAnyFormFieldEdited() {
/*
* If any field is edited,then only it will enable Save button
*/
$(':text').keypress(function(e) { // text written
enableSaveBtn();
});
$(':text').keyup(function(e) {
if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
enableSaveBtn();
} else { // rest ignore
e.preventDefault();
}
});
$(':text').bind('paste', function(e) { // text pasted
enableSaveBtn();
});
$('select').change(function(e) { // select element changed
enableSaveBtn();
});
$(':radio').change(function(e) { // radio changed
enableSaveBtn();
});
$(':password').keypress(function(e) { // password written
enableSaveBtn();
});
$(':password').bind('paste', function(e) { // password pasted
enableSaveBtn();
});
}
Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.
I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.
And this led to the problem.
Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)
So what I did to actually fix the problem was the following. Instead of using:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem(ID));
you just have to cast to Integer. So the working code looked like this:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem((int) ID));
That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
You can use vanilla javascript by simply writing:
var width = el.clientWidth;
You could also use this to get the width of the document as follows:
var docWidth = document.documentElement.clientWidth || document.body.clientWidth;
Source: MDN
You can also get the width of the full window, including the scrollbar, as follows:
var fullWidth = window.innerWidth;
However this is not supported by all browsers, so as a fallback, you may want to use docWidth
as above, and add on the scrollbar width.
Source: MDN
The awk variant :
awk '1;/CLIENTSCRIPT=/{print "CLIENTSCRIPT2=\"hello\""}' file
Just change +
to -
:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]
: match NOT from the set[^a-z0-9-]
: match if not a-z
, 0-9
or -
/ /g
: do global matchMore information:
In my own work, I've realized that every time I've wanted something like variable-length automatic arrays or alloca(), I didn't really care that the memory was physically located on the cpu stack, just that it came from some stack allocator that didn't incur slow trips to the general heap. So I have a per-thread object that owns some memory from which it can push/pop variable sized buffers. On some platforms I allow this to grow via mmu. Other platforms have a fixed size (usually accompanied by a fixed size cpu stack as well because no mmu). One platform I work with (a handheld game console) has precious little cpu stack anyway because it resides in scarce, fast memory.
I'm not saying that pushing variable-sized buffers onto the cpu stack is never needed. Honestly I was surprised back when I discovered this wasn't standard, as it certainly seems like the concept fits into the language well enough. For me though, the requirements "variable size" and "must be physically located on the cpu stack" have never come up together. It's been about speed, so I made my own sort of "parallel stack for data buffers".
You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).
First get all the threads of a given process then call the SuspendThread
function to stop each one (and ResumeThread
to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.
void suspend(DWORD processId)
{
HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
THREADENTRY32 threadEntry;
threadEntry.dwSize = sizeof(THREADENTRY32);
Thread32First(hThreadSnapshot, &threadEntry);
do
{
if (threadEntry.th32OwnerProcessID == processId)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
threadEntry.th32ThreadID);
SuspendThread(hThread);
CloseHandle(hThread);
}
} while (Thread32Next(hThreadSnapshot, &threadEntry));
CloseHandle(hThreadSnapshot);
}
Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.
Starting from Windows XP there is the NtSuspendProcess
but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).
typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);
void suspend(DWORD processId)
{
HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));
NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
GetModuleHandle("ntdll"), "NtSuspendProcess");
pfnNtSuspendProcess(processHandle);
CloseHandle(processHandle);
}
To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess
function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop
.
This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.
void suspend(DWORD processId)
{
DebugActiveProcess(processId);
}
As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:
Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)
Of course if you need it often you can make an alias
for that.
Programming Language: PHP
// Inintialize URL to the variable
$url = 'https://www.youtube.com/watch?v=qnMxsGeDz90';
// Use parse_url() function to parse the URL
// and return an associative array which
// contains its various components
$url_components = parse_url($url);
// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);
// Display result
echo 'v parameter value is '.$params['v'];
This worked for me. I hope, it will also help you :)
I was having a problem running sudo pip install cryptography
because it would not find ffi when trying to compile. (OSX - Yosemite)
I solved it by downloading libffi and setting up the env var.
$ brew install pkg-config libffi
$ export PKG_CONFIG_PATH=/usr/local/Cellar/libffi/3.0.13/lib/pkgconfig/
$ pip install cryptography
If you use the php Datetime class you could use:
function time_ago(Datetime $date) {
$time_ago = '';
$diff = $date->diff(new Datetime('now'));
if (($t = $diff->format("%m")) > 0)
$time_ago = $t . ' months';
else if (($t = $diff->format("%d")) > 0)
$time_ago = $t . ' days';
else if (($t = $diff->format("%H")) > 0)
$time_ago = $t . ' hours';
else
$time_ago = 'minutes';
return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
}
First, concurrent version control seems like an easy problem to solve. It's not at all. Anyway...
SVN is quite non-intuitive. Git is even worse. [sarcastic-speculation] This might be because developers, that like hard problems like concurrent version control, don't have much interest in making a good UI. [/sarcastic-speculation]
SVN supporters think they don't need a distributed version-control system. I thought that too. But now that we use Git exclusively, I'm a believer. Now version control works for me AND the team/project instead of just working for the project. When I need a branch, I branch. Sometimes it's a branch that has a corresponding branch on the server, and sometimes it does not. Not to mention all the other advantages that I'll have to go study up on (thanks in part to the arcane and absurd lack of UI that is a modern version control system).
First of all, go to String.xml file
you can add any HTML attributes like , italic or bold or underline here.
<resources>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
VB6:
Listview1.selecteditem
VB10:
Listview1.FocusedItem.Text
Yes. You need to prefix the table name with "#" (hash) to create temporary tables.
If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.
"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.
Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005
If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.
They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.
DECLARE @ItemBack1 TABLE
(
column1 int,
column2 int,
someInt int,
someVarChar nvarchar(50)
);
INSERT INTO @ItemBack1
SELECT column1,
column2,
someInt,
someVarChar
FROM table2
WHERE table2.ID = 7;
More Info on Table Variables: http://odetocode.com/articles/365.aspx
SUBSTR (documentation):
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment
When selected, it's like any other column. You should give it a name (with As
keyword), and you can selected other columns in the same statement:
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment
You should use:
URLEncoder.encode("NAME", "UTF-8");
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
You can use command prompt to open explorer with path.
here example with batch or command prompt:
start "" explorer.exe (path)
so In VBA ms.access you can write with:
Dim Path
Path="C:\Example"
shell "cmd /c start """" explorer.exe " & Path ,vbHide
Enable:
private void enableEditText() {
mEditText.setFocusableInTouchMode(true);
mEditText.setFocusable(true);
mEditText.setEnabled(true);
}
Disable:
private void disableEditText() {
mEditText.setEnabled(false);
mEditText.setFocusable(false);
mEditText.setFocusableInTouchMode(false);
}
This arstechnica article describes the basic steps:
Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?
Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.
Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.
You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.
The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.
If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.
If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.
The first thing is to make a comparison of functions of SHA and opt for the safest algorithm that supports your programming language (PHP).
Then you can chew the official documentation to implement the hash()
function that receives as argument the hashing algorithm you have chosen and the raw password.
sha256 => 64 bits
sha384 => 96 bits
sha512 => 128 bits
The more secure the hashing algorithm is, the higher the cost in terms of hashing and time to recover the original value from the server side.
$hashedPassword = hash('sha256', $password);
The _cluster/health
API can do far more than the typical output that most see with it:
$ curl -XGET 'localhost:9200/_cluster/health?pretty'
Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
"cluster_name" : "rdu-es-01",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 9,
"number_of_data_nodes" : 6,
"active_primary_shards" : 1106,
"active_shards" : 2213,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0,
"indices" : {
"filebeat-6.5.1-2019.06.10" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.11" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.12" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.13" : {
"status" : "green",
"number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
"cluster_name" : "rdu-es-01",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 9,
"number_of_data_nodes" : 6,
"active_primary_shards" : 1106,
"active_shards" : 2213,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0,
"indices" : {
"filebeat-6.5.1-2019.06.10" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"shards" : {
"0" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"1" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"2" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
The API also has a variety of wait_*
options where it'll wait for various state changes before returning immediately or after some specified timeout
.
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
Here is a more strict version:
^([-+]?\d{1,2}[.]\d+),\s*([-+]?\d{1,3}[.]\d+)$
-90
-- +90
-180
-- +180
Enter this line into Hive command line interface:
insert overwrite directory '/data/test' row format delimited fields terminated by '\t' stored as textfile select * from testViewQuery;
testViewQuery
- some specific view
if ( length(a <- which(1:3 == 5) ) ) print(a) else print("nothing returned for 'a'")
#[1] "nothing returned for 'a'"
On second thought I think any is more beautiful than length(.)
:
if ( any(a <- which(1:3 == 5) ) ) print(a) else print("nothing returned for 'a'")
if ( any(a <- 1:3 == 5 ) ) print(a) else print("nothing returned for 'a'")
I'm currently using two GCM Project Id in the same app package. I put the google-service.json of my first GCM project but I switch from the first to the second one only changing the SENDER_ID:
String token = instanceID.getToken(SENDER_ID,GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
(At this point I think that the google-services.json isn't mandatory )
You can do it in one line:
ls /home/edward/bank1/fiche/Test* >/dev/null 2>&1 && echo "found one" || echo "found none"
To understand what it does you have to decompose the command and have a basic awareness of boolean logic.
Directly from bash man page:
[...]
expression1 && expression2
True if both expression1 and expression2 are true.
expression1 || expression2
True if either expression1 or expression2 is true.
[...]
In the shell (and in general in unix world), the boolean true is a program that exits with status 0.
ls
tries to list the pattern, if it succeed (meaning the pattern exists) it exits with status 0, 2 otherwise (have a look at ls man page for details).
In our case there are actually 3 expressions, for the sake of clarity I will put parenthesis, although they are not needed because &&
has precedence on ||
:
(expression1 && expression2) || expression3
so if expression1 is true (ie: ls
found the pattern) it evaluates expression2 (which is just an echo and will exit with status 0). In this case expression3 is never evaluate because what's on the left site of ||
is already true and it would be a waste of resources trying to evaluate what's on the right.
Otherwise, if expression1 is false, expression2 is not evaluated but in this case expression3 is.
If you want to center align an element without knowing it's width and height do:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Example:
*{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}_x000D_
section{_x000D_
background:red;_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
}_x000D_
div{ _x000D_
width: 80vw;_x000D_
height: 80vh;_x000D_
background: white;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<section>_x000D_
<div>_x000D_
<h1>Popup</h1>_x000D_
</div>_x000D_
</section>
_x000D_
another example with just scriplets, when iterating through an ArrayList that contains Maps.
<%
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");
for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>
</tr>
...
<%}%>
Saw this answer on another site and it works for me as well!
Posted by Shawn on October 14, 2001 1:24 PM
var1 = 1
var2 = 5
Rows(var1 & ":" & var2).Select
That worked for me, looks like you just have to keep the variables outside the quotes and add the and statement (&)
-Shawn
I set the PHPRC variable and uncommented zend_extension=php_opcache.dll
in php.ini
and all works well.
The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html
I found many answers but not one is simple... I hope this will help you...
try{
Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
startActivity(intent);
} finally {
finish();
}
so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).
Unrelated to the OP's problem, but my issue was that I'm a noob shell scripter. All the other languages I've used require parentheses to invoke methods, whereas shell doesn't seem to like that.
function do_something() {
# do stuff here
}
# bad
do_something()
# works
do_something
In Spring Boot 2, the easiest way is to declare in your application.properties:
spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
and define the toString() method of your enums.
See Google Collections. Or, as you suggest, use a map internally, and have that map use a Pair. You'll have to write or find Pair<>; it's pretty easy but not part of the standard Collections.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
For finding value use below
if let a = companies["AAPL"] {
// a is the value
}
For traversing through the dictionary
for (key, value) in companies {
print(key,"---", value)
}
Finally for searching key by value you firstly add the extension
extension Dictionary where Value: Equatable {
func findKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}
Then just call
companies.findKey(val : "Apple Inc")
Change the database.php file from
$db['default']['dbdriver'] = 'mysql';
to
$db['default']['dbdriver'] = 'mysqli';
using from ListSelectionModel
:
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
To put code to NPE's answer, I think the most efficient way to do this is:
def insert(originalfile,string):
with open(originalfile,'r') as f:
with open('newfile.txt','w') as f2:
f2.write(string)
f2.write(f.read())
os.rename('newfile.txt',originalfile)
I just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.
Have you tried val?
$("textarea#ExampleMessage").val(result.exampleMessage);
Perhaps a more realistic example about not sorting a Map object but preparing the sorting up front before doing the Map. The syntax gets actually pretty compact if you do it like this. You can apply the sorting before the map function like this, with a sort function before map (Example from a React app I am working on using JSX syntax)
Mark that I here define a sorting function inside using an arrow function that returns -1 if it is smaller and 0 otherwise sorted on a property of the Javascript objects in the array I get from an API.
report.ProcedureCodes.sort((a, b) => a.NumericalOrder < b.NumericalOrder ? -1 : 0).map((item, i) =>
<TableRow key={i}>
<TableCell>{item.Code}</TableCell>
<TableCell>{item.Text}</TableCell>
{/* <TableCell>{item.NumericalOrder}</TableCell> */}
</TableRow>
)
I like the solution for modern browsers, but the bullets are missing, so I add it a little trick:
http://jsfiddle.net/HP85j/419/
ul {
list-style-type: none;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}
li:before {
content: "• ";
}
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout
like below:
[Violation] 'setTimeout' handler took 43129ms
That number (43129ms) depends on how long you stop in your async function
Base is younger than your question, and definitely feels like a 1.0, but the user experience is miles better than the experience of using any of the "cross-platform" apps on a Mac.
http://menial.co.uk/software/base/
I recommend you buy a license before the developer realizes he is charging too little for it.
UPDATE: Since December 2008, Base is now up to version 2.1, it has become an excellent product. I don't remember what it used to cost, but I paid for the 1.x to 2.x upgrade. Still highly recommended.
ANOTHER UPDATE: Base is available on the Mac App Store, you may find it useful to read the reviews there.
There really isn't an easy way to find out what version of Subversion your server is running -- except to get onto the server and see for yourself.
However, this may not be as big a problem as you may think. Subversion clients is were much of the grunt work is handled, and most versions of the Subversion clients can work with almost any version of the server.
The last release where the server version really made a difference to the client was the change from release 1.4 to release 1.5 when merge tracking was added. Merge tracking had been greatly improved in version 1.6, but that doesn't really affect the interactions between the client and server.
Let's take the latest changes in Subversion 1.8:
svn move
is now a first class operation: Subversion finally understands the svn move
is not a svn copy
and svn delete
. However, this is something that the client handles and doesn't really affect the server version.svn merge --reintegrate
deprecated: Again, as long as the server is at version 1.5 or greater this isn't an issue.svn:global-ignores
and svn:auto-props
: Alas! What we really wanted. A way to setup these two properties without depending upon the Subversion configuration file itself. However, this is a client-only issue, so it again doesn't matter what version of the server you're using.Of all the features, only one depends upon the version of the server being 1.5 or greater (and 1.4 has been obsolete for quite a while. The newer features of 1.8 will improve performance of your working copy, but the server being at revision 1.8 isn't necessary. You're much more affected by your client version than your server version.
I know this isn't the answer you wanted (no official way to see the server version), but fortunately the server version doesn't really affect you that much.
The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.
The JavaMail FAQ recommends using
Session.getInstance(properties);
instead of
Session.getDefaultInstance(properties);
because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.
See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance
The vblank_mode
environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.
$> vblank_mode=0 glxgears
Select all text afected by this issue:
Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.
The same problem came up with Nginx 1.14.2 on Debian 10.6.
It can be resolved by setting the charset
variable. By adding to the server block, beneath the server_name
directive the following:
charset utf-8; # Use the appropriate charset in place of "utf-8"
If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant)
(which requires minimum of API 26) you can use:
ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());
or:
Date date = DateTimeUtils.toDate(zdt.toInstant());
Please also read the advice in Basil Bourque's answer
It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.
If I cannot come up with a more concrete name for my class than XyzManager this would be a point for me to reconsider whether this is really functionality that belongs together in a class, i.e. an architectural 'code smell'.
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
You can use except , for example something like this :
-- DB1..Tb1 have values than DB2..Tb1 not have
Select Col1,Col2,Col3 From DB1..Tb1
except
Select Col1,Col2,Col3 From DB2..Tb1
-- Now we change order
-- DB2..Tb1 have values than DB1..Tb1 not have
Select Col1,Col2,Col3 From DB2..Tb1
except
Select Col1,Col2,Col3 From DB1..Tb1
For me this was simply calling route()
on a named route that I had not created/created incorrectly. This caused the Forbidden error page.
Restarting the web server allowed proper Whoops! error to display:
Route [my-route-name] not defined.
Fixing the route name ->name('my-route-name')
fixed the error.
This is on Laravel 5.5 & using wampserver.
Are you missing the reference to System.Configuration.dll? ConfigurationManager
class lies there.
EDIT: The System.Configuration
namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...
<input type="button" />
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
<input type="submit">
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.
If you use cv2
, correct method is to use .copy()
method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.
eg:
In [1]: import numpy as np
In [2]: x = np.arange(10*10).reshape((10,10))
In [4]: y = x[3:7,3:7].copy()
In [6]: y[2,2] = 1000
In [8]: 1000 in x
Out[8]: False # see, 1000 in y doesn't change values in x, parent array.
You can try
sed 's:\\:\/:g'`
The first \
is to insert an input, the second \
will be the one you want to substitute.
So it is 's ":" First Slash "\" second slash "\" ":" "\" to insert input "/" as the new slash that will be presented ":" g'
\\ \/
And that's it. It will work.
An example where things could go wrong with Shell=True is shown here
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
Check the doc here: subprocess.call()
In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int
if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.
To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-*
flags if possible.
Instead of stdlib.h, you should try:
#include <string.h>
That's where strcpy
and strncpy
are defined, at least according to the strcpy
(2) man page.
The exit
function is defined in stdlib.h, though, so I don't know what's going on there.
Refer this link for linux command linux http://linuxcommand.org/man_pages/grep1.html
for displaying line no ,line of code and file use this command in your terminal or cmd, GitBash(Powered by terminal)
grep -irn "YourStringToBeSearch"
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
I use
if (count(explode("<TAG>", $input))>1){
$content = explode("</TAG>",explode("<TAG>", $input)[1])[0];
}else{
$content = "";
}
Subtitue <TAG> for whatever delimiter you want.
There may be other potential solutions out there (I am still looking) but thus far in my search for the same functionality, I have only found http://www.maxivista.com/ . As far as I can tell through, it only supports a dual monitor, not multiple.
Place static contents like css ,js in following path
resources
->static
->css
->js
(or)
resources
->public
->css
->js
Here you be able to get date like "2020-03-11T20:16:17" and return "11/Mar/2020 - 20:16"
private String transformLocalDateTimeBrazillianUTC(String dateJson) throws ParseException {
String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);
//Here is will set the time zone
formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));
String brazilianFormat = "dd/MMM/yyyy - HH:mm";
SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
Date date = formatInput.parse(dateJson);
return formatOutput.format(date);
}
This is what worked for me (Updated for VS 2013, see revision history for 2010, for VS 2015 see this: https://stackoverflow.com/a/32744234/218971):
Right-click your Web Application Project ? Properties
? Web
, then configure the Servers
section as follows:
http://localhost
http://dev.example.com
Default Site
to anything but port :80
, make sure Skype isn't using port 80, etc.)Optionally: Set the Start URL
to http://dev.example.com
Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config
(Windows XP, Vista, and 7) and edit the site definition in the <sites>
config block to be along the lines of the following:
<site name="DevExample" id="997005936">
<application path="/" applicationPool="Clr2IntegratedAppPool">
<virtualDirectory
path="/"
physicalPath="C:\path\to\application\root" />
</application>
<bindings>
<binding
protocol="http"
bindingInformation=":80:dev.example.com" />
</bindings>
<applicationDefaults applicationPool="Clr2IntegratedAppPool" />
</site>
If running MVC: make sure the applicationPool
is set to one of the "Integrated" options (like "Clr2IntegratedAppPool").
Open your hosts
file and add the line 127.0.0.1 dev.example.com
.
? Start your application!
Some great advice from the comments:
- You may need to run Visual Studio as Administrator.
- If you want to make other devs see your IIS run
netsh http add urlacl url=http://dev.example.com:80/ user=everyone
- If you want the site to resolve for all hosts set
bindingInformation="*:80:"
. Use any port you want, 80 is just convenient. To resolve all hosts you'll need to run Visual Studio as an administrator
@Acyra- performance of object delivery from a single bucket would depend greatly on the names of the objects in it.
If the file names were distanced by random characters then their physical locations would be spread further on the AWS hardware, but if you named everything 'common-x.jpg', 'common-y.jpg' then those objects will be stored together.
This may slow delivery of the files if you request them simultaneously but not by enough to worry you, the greater risk is from data-loss or an outage, since these objects are stored together they will be lost or unavailable together.
You add web components to a J2EE application in a package called a web application archive (WAR), which is a JAR similar to the package used for Java class libraries. A WAR usually contains other resources besides web components, including:
- Server-side utility classes (database beans, shopping carts, and so on).
- Static web resources (HTML, image, and sound files, and so on)
- Client-side classes (applets and utility classes)
A WAR has a specific hierarchical directory structure. The top-level directory of a WAR is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources are stored.
(source)
So a .war is a .jar, but it contains web application components and is laid out according to a specific structure. A .war is designed to be deployed to a web application server such as Tomcat or Jetty or a Java EE server such as JBoss or Glassfish.
It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).
The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.
I prefer doing a "PAD" to the data. MySql calls it LPAD, but you can work your way around to doing the same thing in SQL Server.
ORDER BY REPLACE(STR(ColName, 3), SPACE(1), '0')
This formula will provide leading zeroes based on the Column's length of 3. This functionality is very useful in other situations outside of ORDER BY, so that is why I wanted to provide this option.
Results: 1 becomes 001, and 10 becomes 010, while 100 remains the same.
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string
0
is false. Everything else is true.
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)Using background cover is fine for images, and so is width 100%. These are not optimal for <video>
, and these answers are overly complicated. You do not need jQuery or JavaScript to accomplish a full width video background.
Keep in mind that my code will not cover a background completely with a video like cover will, but instead it will make the video as big as it needs to be to maintain aspect ratio and still cover the whole background. Any excess video will bleed off the page edge, which sides depend on where you anchor the video.
The answer is quite simple.
Just use this HTML5 video code, or something along these lines: (test in Full Page)
html, body {_x000D_
width: 100%; _x000D_
height:100%; _x000D_
overflow:hidden;_x000D_
}_x000D_
_x000D_
#vid{_x000D_
position: absolute;_x000D_
top: 50%; _x000D_
left: 50%;_x000D_
-webkit-transform: translateX(-50%) translateY(-50%);_x000D_
transform: translateX(-50%) translateY(-50%);_x000D_
min-width: 100%; _x000D_
min-height: 100%; _x000D_
width: auto; _x000D_
height: auto;_x000D_
z-index: -1000; _x000D_
overflow: hidden;_x000D_
}
_x000D_
<video id="vid" video autobuffer autoplay>_x000D_
<source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">_x000D_
</video>
_x000D_
The min-height and min-width will allow the video to maintain the aspect ratio of the video, which is usually the aspect ratio of any normal browser at a normal resolution. Any excess video bleeds off the side of the page.
Here's a slightly modified version of TibTibs':
function serialize(form) {
var field, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (i=0; i<len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
for (j=form.elements[i].options.length-1; j>=0; j--) {
if(field.options[j].selected)
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[j].value);
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
}
}
}
}
return s.join('&').replace(/%20/g, '+');
}
Disabled fields are discarded and names are also URL encoded. Regex replace of %20 characters takes place only once, before returning the string.
The query string is in identical form to the result from jQuery's $.serialize() method.
This is for dot net core 2.1 - after a lot of trial and error I finally got this to work flawlessly:
var url = "Hub URL goes here";
var connection = new HubConnectionBuilder()
.WithUrl($"{url}")
.WithAutomaticReconnect() //I don't think this is totally required, but can't hurt either
.Build();
//Start the connection
var t = connection.StartAsync();
//Wait for the connection to complete
t.Wait();
//Make your call - but in this case don't wait for a response
//if your goal is to set it and forget it
await connection.InvokeAsync("SendMessage", "User-Server", "Message from the server");
This code is from your typical SignalR poor man's chat client. The problem that I and what seems like a lot of other people have run into is establishing a connection before attempting to send a message to the hub. This is critical, so it is important to wait for the asynchronous task to complete - which means we are making it synchronous by waiting for the task to complete.
The idea behind CGI is that a program/script (whether Perl or even C) receives input via STDIN
(the request data) and outputs data via STDOUT
(echo, printf
statements).
The reason most PHP scripts don't qualify is that they are run under the PHP Apache module.
This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.
Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):
Teacher | Date | Room
----------|------------------|-----
Mr Smith | 2018-12-18 18:15 | A12
Mr Jones | 2018-12-18 18:30 | B10
Ms Doe | 2018-12-18 18:45 | C21
Ms Rogers | 2018-12-18 19:00 | A08
There's only one teacher per room and they never move. If you have a look, you'll see that:
(1) for every attribute Teacher
, Date
, Room
, we have only one value per row.
(2) super-keys are: (Teacher, Date, Room)
, (Teacher, Date)
and (Date, Room)
and candidate keys are obviously (Teacher, Date)
and (Date, Room)
.
(Teacher, Room)
is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):
Teacher | Date | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12
What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.
My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room
attribute is dependant on the Teacher
attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:
Teacher | Date
----------|-----------------
Mr Smith | 2018-12-18 18:15
Mr Jones | 2018-12-18 18:30
Ms Doe | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00
And
Teacher | Room
----------|-----
Mr Smith | A12
Mr Jones | B10
Ms Doe | C21
Ms Rogers | A08
But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.
With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).
As soon as Room
depends on Teacher
, Room
must be a subset of Teacher
(that's not the case) or Teacher
must be a super key (that's not the case in my diary, but thats the case when you split the table).
To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:
You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.
id //field 1
name //field2
1,peter
2,daniel
...
--example on windows
LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';
.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }
In rare cases this error might be fixed by setting proper platform here [ProjectNavigator]->[Project]->[Target]-> (Architectures) BaseSDK
When creating a framework I've chosen accidentally wrong template (as I was creating macOS framework previously) because it was set to like my previous choice. When adding a target it is easy to miss out configuring platform so double check that.
In Addition to the suggestions, I would also suggest annotating your Repository interface with @Repository.
The Spring IOC may not detect this as a repository and thus be unable to detect the entity and its corresponding property.
I used String.prototype.match(regex)
which returns a string array of all found matches of the given regex
in the string (more info see here):
function getLastIndex(text, regex, limit = text.length) {_x000D_
const matches = text.match(regex);_x000D_
_x000D_
// no matches found_x000D_
if (!matches) {_x000D_
return -1;_x000D_
}_x000D_
_x000D_
// matches found but first index greater than limit_x000D_
if (text.indexOf(matches[0] + matches[0].length) > limit) {_x000D_
return -1;_x000D_
}_x000D_
_x000D_
// reduce index until smaller than limit_x000D_
let i = matches.length - 1;_x000D_
let index = text.lastIndexOf(matches[i]);_x000D_
while (index > limit && i >= 0) {_x000D_
i--;_x000D_
index = text.lastIndexOf(matches[i]);_x000D_
}_x000D_
return index > limit ? -1 : index;_x000D_
}_x000D_
_x000D_
// expect -1 as first index === 14_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g, 10));_x000D_
_x000D_
// expect 29_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g));
_x000D_