There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
A lot of people are going to say this is a bad answer because it is not best practice but you can also convert it to a List before your where.
result = result.ToList().Where(p => date >= p.DOB);
Slauma's answer is better, but this would work as well. This cost more because ToList() will execute the Query against the database and move the results into memory.
You could also use:
List<int> codes = new List<int>();
codes.add(1);
codes.add(2);
var foo = from codeData in channel.AsQueryable<CodeData>()
where codes.Any(code => codeData.CodeID.Equals(code))
select codeData;
I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.
You need to wrap <input type = “file”>
in to <form>
tags and then you can reset input by resetting your form:
onClick="this.form.reset()"
If you don't mind one of the div
s being a master and dictating the height for both div
s there is this:
No matter what, the div
on the right will expand or squish&overflow to match the height of the div
on the left.
Both div
s must be immediate children of a container, and have to specify their widths within it.
Relevant CSS:
.container {
background-color: gray;
display: table;
width: 70%;
position:relative;
}
.container .left{
background-color: tomato;
width: 35%;
}
.container .right{
position:absolute;
top:0px;
left:35%;
background-color: orange;
width: 65%;
height:100%;
overflow-y: auto;
}
This will work fast:
Case 1 - File2 = File1 + extra text appended.
grep -Fxvf File2.txt File1.txt >> File3.txt
File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines
I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
uchar blue;
uchar green;
uchar red; };
And then use it like this on your cv::Mat image:
RGB& rgb = image.ptr<RGB>(y)[x];
image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
from
a directory_of_modules
, you can import
a specific_module.py
specific_module.py
, can contain a Class
with some_methods()
or just functions()
specific_module.py
, you can instantiate a Class
or call functions()
Class
, you can execute some_method()
Example:
#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()
Excerpts from PEP 8 - Style Guide for Python Code:
Modules should have short and all-lowercase names.
Notice: Underscores can be used in the module name if it improves readability.
A Python module is simply a source file(*.py), which can expose:
Class: names using the "CapWords" convention.
Function: names in lowercase, words separated by underscores.
Global Variables: the conventions are about the same as those for Functions.
In MySQL a special column function GROUP_CONCAT
can be used:
SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'computers' AND
TABLE_NAME='Laptop' AND
COLUMN_NAME NOT IN ('code')
ORDER BY ORDINAL_POSITION;
It should be mentioned that the information schema in MySQL covers all database server, not certain databases. That is why if different databases contains tables with identical names, search
condition of the WHERE
clause should specify the schema name: TABLE_SCHEMA='computers'
.
Strings are concatenated with the CONCAT
function in MySQL. The final solution of our problem can be expressed in MySQL as:
SELECT CONCAT('SELECT ',
(SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='computers' AND
TABLE_NAME='Laptop' AND
COLUMN_NAME NOT IN ('code')
ORDER BY ORDINAL_POSITION
), ' FROM Laptop');
You should post it with ajax, this will stop it from changing the page, and you will still get the information back.
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
data: { username: $(this).name.value,
password: $(this).password.value }
});
return false;
});
})
I have got the success using the following commands.
git config --unset-all credential.helper
git config --global --unset-all credential.helper
git config --system --unset-all credential.helper
Try and let me know if these are working for you.
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
The @alaster answer help me a lot, but I would like to add a meaninful information if someone is trying to group the information.
If you have, per example, two Orders
with the same code
but different quantity
of products for each one, and your desire is sum the quantities, you can do:
List<Order> listQuantidade = new ArrayList<>();
listOrders.add(new Order("COD_1", 1L));
listOrders.add(new Order("COD_1", 5L));
listOrders.add(new Order("COD_1", 3L));
listOrders.add(new Order("COD_2", 3L));
listOrders.add(new Order("COD_3", 4L));
listOrders.collect(Collectors.toMap(Order::getCode,
o -> o.getQuantity(),
(o1, o2) -> o1 + o2));
Result:
{COD_3=4, COD_2=3, COD_1=9}
You can make a .reg file and call start on it. You can export any part of the registry as a .reg file to see what the format is.
Format here:
http://support.microsoft.com/kb/310516
This can be run on any Windows machine without installing other software.
The error your are getting is because your-ubuntu-username is not a valid Postgres user.
You need to tell psql what database username to use
psql -U postgres
You may also need to specify the database to connect to
psql -U postgres -d <dbname>
You can use the min and max attributes.
The following code do the same:
<input type="number" min="-999" max="9999"/>
If you are calling the sign_up API (AWS Cognito) using Python3, you can use the following code.
def registerUser(userObj):
''' Registers the user to AWS Cognito.
'''
# Mobile number is not a mandatory field.
if(len(userObj['user_mob_no']) == 0):
mobilenumber = ''
else:
mobilenumber = userObj['user_country_code']+userObj['user_mob_no']
secretKey = bytes(settings.SOCIAL_AUTH_COGNITO_SECRET, 'latin-1')
clientId = settings.SOCIAL_AUTH_COGNITO_KEY
digest = hmac.new(secretKey,
msg=(userObj['user_name'] + clientId).encode('utf-8'),
digestmod=hashlib.sha256
).digest()
signature = base64.b64encode(digest).decode()
client = boto3.client('cognito-idp', region_name='eu-west-1' )
try:
response = client.sign_up(
ClientId=clientId,
Username=userObj['user_name'],
Password=userObj['password1'],
SecretHash=signature,
UserAttributes=[
{
'Name': 'given_name',
'Value': userObj['given_name']
},
{
'Name': 'family_name',
'Value': userObj['family_name']
},
{
'Name': 'email',
'Value': userObj['user_email']
},
{
'Name': 'phone_number',
'Value': mobilenumber
}
],
ValidationData=[
{
'Name': 'email',
'Value': userObj['user_email']
},
]
,
AnalyticsMetadata={
'AnalyticsEndpointId': 'string'
},
UserContextData={
'EncodedData': 'string'
}
)
except ClientError as error:
return {"errorcode": error.response['Error']['Code'],
"errormessage" : error.response['Error']['Message'] }
except Exception as e:
return {"errorcode": "Something went wrong. Try later or contact the admin" }
return {"success": "User registered successfully. "}
error.response['Error']['Code'] will be InvalidPasswordException, UsernameExistsException etc. So in the main function or where you are calling the function, you can write the logic to provide a meaningful message to the user.
An example for the response (error.response):
{
"Error": {
"Message": "Password did not conform with policy: Password must have symbol characters",
"Code": "InvalidPasswordException"
},
"ResponseMetadata": {
"RequestId": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
"HTTPStatusCode": 400,
"HTTPHeaders": {
"date": "Wed, 17 Jul 2019 09:38:32 GMT",
"content-type": "application/x-amz-json-1.1",
"content-length": "124",
"connection": "keep-alive",
"x-amzn-requestid": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
"x-amzn-errortype": "InvalidPasswordException:",
"x-amzn-errormessage": "Password did not conform with policy: Password must have symbol characters"
},
"RetryAttempts": 0
}
}
For further reference : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.sign_up
You could use std::numeric_limits<size_t>::max()
for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector
has size equal to std::numeric_limits<size_t>::max()
, then maximum allowed index will be (std::numeric_limits<size_t>::max()-1)
, since elements counted from 0.
Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.
For you, the only solution is to use the PHP Facebook API.
When creating the application you will have two key data for your code:
YOUR_APP_ID
YOUR_APP_SECRET
Download the Facebook PHP SDK from here.
You can start with this code for share content from your site:
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
// Give the user a logout link
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
You can find more examples in the Facebook Developers site:
VAR1=value1 VAR2=value2 myScript args ...
i use $().one()
for solve this;
When page loaded, I send ajax to server and wait to done.
Then pass result to function.$().one()
is important .Because force typehead.js to attach to input one time.
sorry for bad writing.
(($) => {_x000D_
_x000D_
var substringMatcher = function(strs) {_x000D_
return function findMatches(q, cb) {_x000D_
var matches, substringRegex;_x000D_
// an array that will be populated with substring matches_x000D_
matches = [];_x000D_
_x000D_
// regex used to determine if a string contains the substring `q`_x000D_
substrRegex = new RegExp(q, 'i');_x000D_
_x000D_
// iterate through the pool of strings and for any string that_x000D_
// contains the substring `q`, add it to the `matches` array_x000D_
$.each(strs, function(i, str) {_x000D_
if (substrRegex.test(str)) {_x000D_
matches.push(str);_x000D_
}_x000D_
});_x000D_
cb(matches);_x000D_
};_x000D_
};_x000D_
_x000D_
var states = [];_x000D_
$.ajax({_x000D_
url: 'https://baconipsum.com/api/?type=meat-and-filler',_x000D_
type: 'get'_x000D_
}).done(function(data) {_x000D_
$('.typeahead').one().typeahead({_x000D_
hint: true,_x000D_
highlight: true,_x000D_
minLength: 1_x000D_
},_x000D_
{_x000D_
name: 'states',_x000D_
source: substringMatcher(data)_x000D_
});_x000D_
})_x000D_
_x000D_
_x000D_
})(jQuery);
_x000D_
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
.tt-hint {_x000D_
width: 396px;_x000D_
height: 30px;_x000D_
padding: 8px 12px;_x000D_
font-size: 24px;_x000D_
line-height: 30px;_x000D_
border: 2px solid #ccc;_x000D_
border-radius: 8px;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);_x000D_
}_x000D_
_x000D_
.tt-hint {_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */_x000D_
width: 422px;_x000D_
margin-top: 12px;_x000D_
padding: 8px 0;_x000D_
background-color: #fff;_x000D_
border: 1px solid #ccc;_x000D_
border: 1px solid rgba(0, 0, 0, 0.2);_x000D_
border-radius: 8px;_x000D_
box-shadow: 0 5px 10px rgba(0,0,0,.2);_x000D_
}_x000D_
_x000D_
.tt-suggestion {_x000D_
padding: 3px 20px;_x000D_
font-size: 18px;_x000D_
line-height: 24px;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.tt-suggestion:hover {_x000D_
color: #f0f0f0;_x000D_
background-color: #0097cf;_x000D_
}_x000D_
_x000D_
.tt-suggestion p {_x000D_
margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>_x000D_
_x000D_
<input class="typeahead" type="text" placeholder="where ?">
_x000D_
Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file()
(it's called move not store) for more.
Here is how I would do it:
$("#target option")
.removeAttr('selected')
.find(':first') // You can also use .find('[value=MyVal]')
.attr('selected','selected');
@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Then add this code to your View:
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/
I am doing a simple thing here:
Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.
If you stay on page it works as it is supposed. But if you hide the tab for some seconds, when you get back you will see a weired thing.
Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.
So it seams chrome only delays the events, so when you get back all events will occur but all at once...
A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.
To fix this use the stop(true,true) like pimvdb told. THis will clear the event queue.
It is worth mentioning that MySQL 8.0.23 and above supports Invisible Columns
CREATE TABLE tbl_Country(
CountryId INT NOT NULL AUTO_INCREMENT,
IsDeleted bit,
PRIMARY KEY (CountryId)
);
INSERT INTO tbl_Country VALUES (1, 1), (2,0);
ALTER TABLE tbl_Country ALTER COLUMN IsDeleted SET INVISIBLE;
SELECT * FROM tbl_Country;
CountryId
1
2
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
It may be useful in scenarios when there is need to "hide" a column for a time being before it could be safely dropped(like reworking corresponding application/reports etc.).
Let say button 1 has an event called
Button1_Click(Sender, eventarg)
If you want to call it in Button2 then call this function directly.
Button1_Click(Nothing, Nothing)
If you are in a loop (Do While, For, ...) and you call Me.Close()
, you should follow with an Exit command (Exit Do, ...) or a Return()
to force the message processing to terminate properly. I caught programs hanging due to this.
It's 2019 and you should be using this:
let arr = [...Array(20)].fill(10)
So basically 20
is the length
or a new instantiated Array
.
UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.
With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:
This will NOT work. :
const myImg = './cute.jpg'
<img src={require(myImg)} />
To fix this, just use template strings instead :
const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />
webpack.config.js :
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry : './src/app.js',
output : {
path : './dist',
filename : 'app.bundle.js'
},
plugins : [
new ExtractTextWebpackPlugin('app.bundle.css')],
module : {
rules : [{
test : /\.css$/,
use : ExtractTextWebpackPlugin.extract({
fallback : 'style-loader',
use: 'css-loader'
})
},{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react','es2015']
}
},{
test : /\.jpg$/,
exclude: /(node_modules)/,
loader : 'file-loader'
}]
}
}
Ok, it seems that some versions of PHP have a limitation of length of GET params:
Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.
To add support for long parameters with suhosin, add
suhosin.get.max_value_length = <limit>
inphp.ini
Source: http://www.php.net/manual/en/reserved.variables.get.php#101469
If you want to use If, else if, and else then use this method
{this.state.value === 0 ? (
<Component1 />
) : this.state.value === 1 ? (
<Component2 />
) : (
<Component3 />
)}
I came to this question because I was trying to do the same, but in my case the Bitmap is from a resource/file. I found the best solution is as described in the following link:
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx
// Create the image element.
Image simpleImage = new Image();
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);
// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/sampleImages/cherries_larger.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;
add this code to your project
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
then use
"code : string text ".TextAfter(":")
I know of psExec tools which you can download from here
There comes a psinfo.exe from the tools package. The basic usage is in the following manner in powershell/cmd.
However you could have a lot of options with it
Usage: psinfo [[\computer[,computer[,..] | @file [-u user [-p psswd]]] [-h] [-s] [-d] [-c [-t delimiter]] [filter]
\computer Perform the command on the remote computer or computers specified. If you omit the computer name the command runs on the local system, and if you specify a wildcard (\*), the command runs on all computers in the current domain.
@file Run the command on each computer listed in the text file specified.
-u Specifies optional user name for login to remote computer.
-p Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
-h Show list of installed hotfixes.
-s Show list of installed applications.
-d Show disk volume information.
-c Print in CSV format.
-t The default delimiter for the -c option is a comma, but can be overriden with the specified character.
filter Psinfo will only show data for the field matching the filter. e.g. "psinfo service" lists only the service pack field.
Just remove white space of all folders present in the given path for example Program Files You can remove it by following steps-> Open elevated cmd, In the command prompt execute: mklink /J C:\Program-Files "C:\Program Files" This will remove space and replace it with "-". Better do this with both sdk and jdk path. This works :)
There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.
The server at x3.chatforyoursite.com
needs to output the following header:
Access-Control-Allow-Origin: http://www.example.com
Where http://www.example.com
is your website address. You should check your settings on chatforyoursite.com
to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.
Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.
Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.
For a web app, if the app server already provides the JAR (or its functionality), then use "provided" otherwise use "compile".
Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:
function setMyKeyDownListener() {_x000D_
window.addEventListener(_x000D_
"keydown",_x000D_
function(event) {MyFunction(event.key)}_x000D_
)_x000D_
}_x000D_
_x000D_
function MyFunction (the_Key) {_x000D_
alert("Key pressed is: "+the_Key);_x000D_
}
_x000D_
html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
_x000D_
<body onload="setMyKeyDownListener()">_x000D_
<div>_x000D_
<input id="MyInputId">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.
$('input:checkbox').click(function () {
if ($(this).is(':checked')) {
$('#sendNewSms').click(function () {
return false;
});
} else {
$('#sendNewSms').unbind('click');
}
});
The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.
var clickEvent = function () {
return false;
};
document.getElementById('#checkbox').onclick(function () {
if (document.getElementById('#checkbox').checked) {
document
.getElementById('#sendNewSms')
.onclick(clickEvent);
} else {
document
.getElementById('#sendNewSms')
.removeEventListener('click', clickEvent, false);
}
});
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
First of all There is no such class called Static class.The Static modifier use with inner class (called as Nested Class) says that it is a static member of Outer Class which means we can access it as with other static members and without having any instance of Outer class. (Which is benefit of static originally.)
Difference between using Nested class and regular Inner class is:
OuterClass.InnerClass inner = new OuterClass().new InnerClass();
First We can to instantiate Outerclass then we Can access Inner.
But if Class is Nested then syntax is:
OuterClass.InnerClass inner = new OuterClass.InnerClass();
Which uses the static Syntax as normal implementation of static keyword.
Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available
Original
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap"/>
</basicHttpBinding>
</bindings>
After Edit/Update
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
Use color property to change the color of your target element as follow :
.icon-cog { // selector of your element
color: black;
}
Or in the newest version of font-awesome , you can choose among filled or not filled icons
I have the same issue with the ".index()" method on lists. I have no issue with the fact that it throws an exception but I strongly disagree with the fact that it's a non-descriptive ValueError. I could understand if it would've been an IndexError, though.
I can see why returning "-1" would be an issue too because it's a valid index in Python. But realistically, I never expect a ".index()" method to return a negative number.
Here goes a one liner (ok, it's a rather long line ...), goes through the list exactly once and returns "None" if the item isn't found. It would be trivial to rewrite it to return -1, should you so desire.
indexOf = lambda list, thing: \
reduce(lambda acc, (idx, elem): \
idx if (acc is None) and elem == thing else acc, list, None)
How to use:
>>> indexOf([1,2,3], 4)
>>>
>>> indexOf([1,2,3], 1)
0
>>>
I think with this jQuery-numberformatter you could solve your problem.
Of course, this is assuming that you don't have problem with using jQuery in your project. Please notice that the functionality is tied to the blur event.
$("#salary").blur(function(){_x000D_
$(this).parseNumber({format:"#,###.00", locale:"us"});_x000D_
$(this).formatNumber({format:"#,###.00", locale:"us"});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/gh/timdown/jshashtable/hashtable.js"></script>_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/gh/hardhub/jquery-numberformatter/src/jquery.numberformatter.js"></script>_x000D_
_x000D_
<input type="text" id="salary">
_x000D_
Simple, global change of Jupyter font size and inner & outer background colors (this change will affect all notebooks).
In Windows, find config directory by running a command:
jupyter --config-dir
In Linux it is ~/.jupyter
In this directory create subfolder custom
Create file custom.css
and paste:
/* Change outer background and make the notebook take all available width */
.container {
width: 99% !important;
background: #DDC !important;
}
/* Change inner background (CODE) */
div.input_area {
background: #F4F4E2 !important;
font-size: 16px !important;
}
/* Change global font size (CODE) */
.CodeMirror {
font-size: 16px !important;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode */
div.cell.selected {
border-left-width: 1px !important;
}
Finally - restart Jupyter. Result:
<marquee behavior=scroll direction="left" scrollamount="5">Your message here</marquee>
_x000D_
scrollamount controls the speed of text: higher the value higher is the scrolling speed
If you're using a form
you can disable all the autocompletes with,
<form id="Form1" runat="server" autocomplete="off">
I found a very clean solution that allows separate logic and GUI:
in your razor .cshtml page try this:
<body id="myId" data-my-variable="myValue">
...your page code here
</body>
in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):
$("#myId").data("my-variable")
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:
The client have two network cards,a wireless one and a normal one.
The ping to server can be succeed.However telnet serverAddress 3306
would fail.
And would complain
Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)
when try to connect to server.So I forbidden the normal network adapters.
And tried telnet serverAddress 3306
it works.And then it work when connect to MySQL server.
Use the -i
option:
ssh -i mykey.pem [email protected]
As noted in this answer, this file needs to have correct permissions set. The ssh man page says:
ssh will simply ignore a private key file if it is accessible by others.
You can change the permissions with this command:
chmod go= mykey.pem
That is, set permissions for group and others equal to the empty list of permissions.
The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.
Here is the general explanation from the link
WhatsApp server is almost completely implemented in Erlang.
Server systems that do the backend message routing are done in Erlang.
Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.
Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.
WhatsApp server has started from ejabberd
Ejabberd is a famous open source Jabber server written in Erlang.
Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.
The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.
To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.
A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.
Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).
Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.
What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message
How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.
Best practice is to use an interface to specify the contract and an abstract class as just one implementation thereof. That abstract class can fill in a lot of the boilerplate so you can create an implementation by just overriding what you need to or want to without forcing you to use a particular implementation.
You have to understand that FormData::entries()
returns an instance of Iterator
.
Take this example form:
<form name="test" id="form-id">
<label for="name">Name</label>
<input name="name" id="name" type="text">
<label for="pass">Password</label>
<input name="pass" id="pass" type="text">
</form>
and this JS-loop:
<script>
var it = new FormData( document.getElementById('form-id') ).entries();
var current = {};
while ( ! current.done ) {
current = it.next();
console.info( current )
}
</script>
If you're using MySQL you can run SHOW KEYS FROM table
or SHOW INDEXES FROM table
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
One option is to modify the removeA
method to this -
public void removeA(A a,Iterator<A> iterator) {
iterator.remove(a);
}
But this would mean your doSomething()
should be able to pass the iterator
to the remove
method. Not a very good idea.
Can you do this in two step approach :
In the first loop when you iterate over the list , instead of removing the selected elements , mark them as to be deleted. For this , you may simply copy these elements ( shallow copy ) into another List
.
Then , once your iteration is done , simply do a removeAll
from the first list all elements in the second list.
First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face
rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.
Although Time Complexity of selection sort and insertion sort is the same, that is n(n - 1)/2. The average performance insertion sort is better. Tested on my i5 cpu with random 30000 integers, selection sort took 1.5s in average, while insertion sort take 0.6s in average.
I'm not sure I agree with inheritance from ValueError
-- my interpretation of the documentation is that ValueError
is only supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Another use-case where nameof
feature of C# 6.0 becomes handy - Consider a library like Dapper which makes DB retrievals much easier. Albeit this is a great library, you need to hardcode property/field names within query. What this means is that if you decide to rename your property/field, there are high chances that you will forget to update query to use new field names. With string interpolation and nameof
features, code becomes much easier to maintain and typesafe.
From the example given in link
without nameof
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
with nameof
var dog = connection.Query<Dog>($"select {nameof(Dog.Age)} = @Age, {nameof(Dog.Id)} = @Id", new { Age = (int?)null, Id = guid });
Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true);
won't work with new version of angularjs without specifying the base URL for the application with a <base href="">
tag or setting the parameter requireBase
to false
If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
You can try also:
document.body.offsetHeight
document.body.offsetWidth
If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m
Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini
file which is present in your Eclipse home directory.
To get the size of the JVM during Runtime you can use Runtime.totalMemory()
which returns the total amount of memory in the Java virtual machine, measured in bytes.
A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0
with this.removeAttribute('size')
.
<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
onchange='this.blur()' onblur="this.removeAttribute('size')">
<option>option1</option>
<option>option2</option>
<option>option3</option>
<option>option4</option>
<option>option5</option>
<option>option6</option>
<option>option7</option>
</select>
If you are using the Spring Framework, the most straightforward way to do this is:
private Integer laancNotifyPort = SocketUtils.findAvailableTcpPort();
You can also set an acceptable range, and it will search in this range:
private Integer laancNotifyPort = SocketUtils.findAvailableTcpPort(9090, 10090);
This is a convenience method that abstracts away the complexity but internally is similar to a lot of the other answers on this thread.
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
If you're just testing your APIs manually, we've found RestClient 2.3 or the Poster add-on for Firefox to be pretty helpful. Both of these let you build requests that GET, PUT, POST, or DELETE. You can save these requests to rerun later.
For simple automated testing try the Linux (or Cygwin) 'curl' command in a shell script.
From something more industrial strength you can move up to Apache JMeter. JMeter is great for load testing.
31 October 2014: HTTPRequester is now a better choice for Firefox.
July 2015: Postman is a good choice for Chrome
You can use
root.setBackgroundColor(0xFFFFFFFF);
or
root.setBackgroundColor(Color.parseColor("#ffffff"));
You can implement some basic Calculus and create a universal function for moving array element from one position to the other.
For JavaScript it looks like this:
function magicFunction (targetArray, indexFrom, indexTo) {
targetElement = targetArray[indexFrom];
magicIncrement = (indexTo - indexFrom) / Math.abs (indexTo - indexFrom);
for (Element = indexFrom; Element != indexTo; Element += magicIncrement){
targetArray[Element] = targetArray[Element + magicIncrement];
}
targetArray[indexTo] = targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html
For my development, I find that Chrome has a great solution.
https://superuser.com/a/512833
With developer tools open, simply long click the refresh button and let go once you hover over "Empty Cache and Hard Reload".
This is my best friend, and is a super lightweight way to get what you want!
If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:
WHERE startTime = '2010-04-29'
because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes
WHERE startTime = '2010-04-29 00:00:00'
Certainly not what you want!
The condition is a range and hence it should be given as range. There are several possibilities:
WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)
There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.
Both variants can use an index on startTime which will become important when the table grows.
With Json.NET
public class Movie
{
public string Name { get; set; }
public string Description { get; set; }
public string Classification { get; set; }
public string Studio { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<string> ReleaseCountries { get; set; }
}
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
The result will be:
{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys"
}
I solved it with library PHP_PDO , because my hosting provider didn't accept my requirement for installation of PDO driver to apache server.
I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.
The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.
Here's a solution for Bootstrap4. You just need to put the card-header
class in the a
tag. This is a modified from an example in W3Schools.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div id="accordion">_x000D_
<div class="card">_x000D_
<a class="card-link card-header" data-toggle="collapse" href="#collapseOne" >_x000D_
Collapsible Group Item #1_x000D_
</a>_x000D_
<div id="collapseOne" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<a class="collapsed card-link card-header" data-toggle="collapse" href="#collapseTwo">_x000D_
Collapsible Group Item #2_x000D_
</a>_x000D_
<div id="collapseTwo" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<a class="card-link card-header" data-toggle="collapse" href="#collapseThree">_x000D_
Collapsible Group Item #3_x000D_
</a>_x000D_
<div id="collapseThree" class="collapse" data-parent="#accordion">_x000D_
<div class="card-body">_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .
Then project compile and done ..
Run the below commands and install the required packages globally:
npm install -g ts-node
npm install -g typescript
Now run the following command to execute a typescript file:
ts-node typescript-file.ts
Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9
9.3 Context per request
Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
You can find the Team ID via this link: https://developer.apple.com/membercenter/index.action#accountSummary
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
There is an article on javaworld.com that explains the difference => Which ClassLoader should you use
(1)
Thread context classloaders provide a back door around the classloading delegation scheme.
Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.
(2) from the same source:
This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:
- JNDI uses context classloaders
- Class.getResource() and Class.forName() use the current classloader
- JAXP uses context classloaders (as of J2SE 1.4)
- java.util.ResourceBundle uses the caller's current classloader
- URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
- Java Serialization API uses the caller's current classloader by default
Just open the ~/.profile
file, via nano
in Terminal and type there :
export PATH=whatever/you/want:$PATH
Save this file (cmd+X and Y). After that please logout/login again or just open a new tab in Terminal and try use your new variable.
PLEASE DON'T forget to add ":$PATH" after whatever/you/want, otherwise you'll erase all paths in PATH variable, which were there before that.
Mostly in Hibernate
, need to add the Entity
class in hibernate.cfg.xml
like-
<hibernate-configuration>
<session-factory>
....
<mapping class="xxx.xxx.yourEntityName"/>
</session-factory>
</hibernate-configuration>
One totally different approach is to put things in a grid, such as ui-grid or Kendo's grid, and have the columns be resizable. A downside is that users would not be able to resize the rows, though the row size could be set programmatically.
Two options I just ran into:
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
You can also use OPENROWSET to import excel file in sql server.
SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
'SELECT * FROM [Data$]')
SQL Server by default uses the mdy
date format and so the below works:
SELECT convert(datetime, '07/23/2009', 111)
and this does not work:
SELECT convert(datetime, '23/07/2009', 111)
I myself have been struggling to come up with a single query that can handle both date formats: mdy
and dmy
.
However, you should be ok with the third date format - ymd
.
I was facing the same issue and I searched for almost 2 hours and tried with different possible ways like replacing old hibernate JARs and changing the DB table schema. But finally got the solution as below:
SessionFactory factory = new Configuration().configure().buildSessionFactory(); //This line to be replaced with below commented line
Replace above for
//Configuration config = new Configuration().configure();
//ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//SessionFactory factory = config.buildSessionFactory(servReg);
It will then work fine..
Slightly alternative solution to @jpp's but outputting a YearMonth
string:
df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))
res = df.groupby('YearMonth')['Values'].sum()
The best way is to use:
$("#yourid option:selected").text();
Depending on the requirement, you could also use this way:
var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()
NSTimer has been renamed to Timer in Swift 4.2. this syntax will work in 4.2:
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));
kk.getText().toString();
System.out.println(+kk.getText().toString());
You need to define an AbstractBinder
and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.
public class MyApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MyService.class).to(MyService.class);
}
}
When @Inject
is detected on a parameter or field of type MyService.class
it is instantiated using the class MyService
. To use this binder, it need to be registered with the JAX-RS application. In your web.xml
, define a JAX-RS application like this:
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.mypackage.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Implement the MyApplication
class (specified above in the init-param
).
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new MyApplicationBinder());
packages(true, "com.mypackage.rest");
}
}
The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource
) using the packages()
method call.
I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
/**
* It is the parameter is to show arguments in the method or the class.
*/
boolean showArguments() default false;
}
@Aspect
@Component
public class AnnotationLoggerAspect {
@Autowired
private Logger logger;
private static final String METHOD_NAME = "METHOD NAME: {} ";
private static final String ARGUMENTS = "ARGS: {} ";
@Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
public void logAdviceExecutionBefore(JoinPoint joinPoint){
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
if(annotationLogger!= null) {
StringBuilder annotationLoggerFormat = new StringBuilder();
List<Object> annotationLoggerArguments = new ArrayList<>();
annotationLoggerFormat.append(METHOD_NAME);
annotationLoggerArguments.add(codeSignature.getName());
if (annotationLogger.showArguments()) {
annotationLoggerFormat.append(ARGUMENTS);
List<?> argumentList = Arrays.asList(joinPoint.getArgs());
annotationLoggerArguments.add(argumentList.toString());
}
logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
}
}
private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
AnnotationLogger annotationLogger = null;
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = joinPoint.getTarget().getClass().
getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
if (method.isAnnotationPresent(AnnotationLogger.class)){
annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
}else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
}
return annotationLogger;
}catch(Exception e) {
return annotationLogger;
}
}
}
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
Depends on the RDBMS or even the JDBC driver.
Most of the times you can use java.sql.Timestamp most of the times along with a prepared statement:
pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );
You need to set the value
attribute of option
to the empty string:
<select name="status" required>
<option selected disabled value="">what's your status?</option>
<option value="code">coding</option>
<option value="sleep">sleeping</option>
</select>
select
will return the value
of the selected option
to the server when the user presses submit
on the form
. An empty value
is the same as an empty text
input -> raising the required
message.
The value attribute specifies the value to be sent to a server when a form is submitted.
I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).
Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.
This error is thrown when the column of a table puts constraint [ mostly length ]. . E.g. if database schema for column myColumn is CHAR(2), then when your call from any of your application to insert value, you must pass String of length two.
The error basically says it; string of length three and above is inconsistent to fit the length restriction specified by database schema. That's why SQL Server warns and throws data loss/ Truncation error.
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
Use Array.prototype.filter
instead of forEach
:
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);
For me, I just had to go into the Job Activity Monitor and stop two things that were processing. Then it went offline immediately. In my case though I knew what those 2 processes were and that it was ok to stop them.
It is same as above answers, but is simple in steps
c:\SRC\folder1
c:\SRC\folder2
c:\SRC\folder3
c:\SRC\folder4
to copy all above folders to c:\DST\ except folder1 and folder2.
Step1: create a file c:\list.txt with below content, one folder name per one line
folder1\
folder2\
Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt
const obj = {_x000D_
"Filters":[_x000D_
{_x000D_
"FilterType":"between",_x000D_
"Field":"BasicInformationRow.A0",_x000D_
"MaxValue":"2017-10-01",_x000D_
"MinValue":"2017-09-01",_x000D_
"Value":"Filters value"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
let new_obj1 = Object.assign({}, obj.Filters[0]);_x000D_
let new_obj2 = Object.assign({}, obj.Filters[0]);_x000D_
_x000D_
/*_x000D_
_x000D_
// old version_x000D_
_x000D_
let shaped_obj1 = Object.keys(new_obj1).map(_x000D_
(key, index) => {_x000D_
switch (key) {_x000D_
case "MaxValue":_x000D_
delete new_obj1["MaxValue"];_x000D_
break;_x000D_
case "MinValue":_x000D_
delete new_obj1["MinValue"];_x000D_
break;_x000D_
}_x000D_
return new_obj1;_x000D_
}_x000D_
)[0];_x000D_
_x000D_
_x000D_
let shaped_obj2 = Object.keys(new_obj2).map(_x000D_
(key, index) => {_x000D_
if(key === "Value"){_x000D_
delete new_obj2["Value"];_x000D_
}_x000D_
return new_obj2;_x000D_
}_x000D_
)[0];_x000D_
_x000D_
_x000D_
*/_x000D_
_x000D_
_x000D_
// new version!_x000D_
_x000D_
let shaped_obj1 = Object.keys(new_obj1).forEach(_x000D_
(key, index) => {_x000D_
switch (key) {_x000D_
case "MaxValue":_x000D_
delete new_obj1["MaxValue"];_x000D_
break;_x000D_
case "MinValue":_x000D_
delete new_obj1["MinValue"];_x000D_
break;_x000D_
default:_x000D_
break;_x000D_
}_x000D_
}_x000D_
);_x000D_
_x000D_
let shaped_obj2 = Object.keys(new_obj2).forEach(_x000D_
(key, index) => {_x000D_
if(key === "Value"){_x000D_
delete new_obj2["Value"];_x000D_
}_x000D_
}_x000D_
);
_x000D_
I believe this is the NSDate's selector you're looking for:
- (NSTimeInterval)timeIntervalSince1970
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
Update: My original answer involved having the controller contain DOM-aware code, which breaks Angular conventions in favor of HTML. @dmackerman mentioned directives in a comment on my answer, and I completely missed that until just now. With that input, here's the right way to do this without breaking Angular or HTML conventions:
There's also a way to get both - grab the value of the element and use that to update the model in a directive:
<div ng-controller="Main">
<input type="text" id="rootFolder" ng-model="rootFolders" disabled="disabled" value="Bob" size="40" />
</div>
and then:
app.directive('input', ['$parse', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if(attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
}]);
You can of course modify the above directive to do more with the value
attribute before setting the model to its value, including using $parse(attrs.value, scope)
to treat the value
attribute as an Angular expression (though I'd probably use a different [custom] attribute for that, personally, so the standard HTML attributes are consistently treated as constants).
Also, there is a similar question over at Making data templated in available to ng-model which may also be of interest.
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
getdate()
for MS-SQL, sysdate
for Oracle server
None of the current answers will work for WHM / cPanel servers.
To increase the limit in WHM:
It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):
hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f
So, that is all. No one extra head on revgraph. No extra commit.
Add the Library file in project.. Project->right click->Properties->android->Library-> click Add and select the Library Project and give apply and ok.. then, clean the project and run again.. if you want restart the eclipse..
And also, sometimes, need to update Android SDK build tools..
JavaScript is, with a very few exceptions (XMLHttpRequest
onreadystatechange
handlers in some versions of Firefox) event-loop concurrent. So you needn't worry about locking in this case.
JavaScript has a concurrency model based on an "event loop". This model is quite different than the model in other languages like C or Java.
...
A JavaScript runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame) The message processing ends when the stack becomes empty again.
...
Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.
For more links on event-loop concurrency, see E
Sorry for being late on the party. Depending on your server configuration, You may be required to specify character strictly with lowercase letters utf-8, otherwise it will be ignored. Try this if you end up here searching for solutions and none of answers above helps:
$mail->CharSet = "UTF-8";
should be replaced with:
$mail->CharSet = "utf-8";
Order By
is applied after union
, so just
add an order by
clause at the end of the statements:
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like '%a%'
Order By name
JavaScript Pure:
<script type="text/javascript">
document.getElementById("modal").click();
</script>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#modal").trigger('click');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$("#modal").click();
});
</script>
I could never get $viewContentLoaded
to work for me, and ng-init
should really only be used in an ng-repeat
(according to the documentation), and also calling a function directly in a controller can cause errors if the code relies on an element that hasn't been defined yet.
This is what I do and it works for me:
$scope.$on('$routeChangeSuccess', function () {
// do something
});
Unless you're using ui-router
. Then it's:
$scope.$on('$stateChangeSuccess', function () {
// do something
});
just run git log origin/$BRANCH_NAME
The data members and function members that operate on the instance of the type are called instance members. The int’s ToString method (for example) are examples of instance members. By default, members are instance members. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.
var str = "you can enter maximum 500 choices";
str.replace(/[^0-9]/g, "");
console.log(str); // "500"
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
You can try the code here:
I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).
You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.
Java 9 offers a Matcher.replaceAll()
that accepts a replacement function:
resultString = regexMatcher.replaceAll(
m -> String.valueOf(Integer.parseInt(m.group()) * 3));
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {_x000D_
_x000D_
$('#nCS1 > option').each((index, obj) => {_x000D_
console.log($(obj).val());_x000D_
})_x000D_
_x000D_
}_x000D_
_x000D_
printOptionTexts = () => {_x000D_
$('#nCS1 > option').each((index, obj) => {_x000D_
console.log($(obj).text());_x000D_
})_x000D_
}_x000D_
_x000D_
printSelectedItemText = () => {_x000D_
console.log($('#nCS1 option:selected').text());_x000D_
}_x000D_
_x000D_
printSelectedItemValue = () => {_x000D_
console.log($('#nCS1 option:selected').val());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select size="1" id="nCS1" name="nCS1" class="form-control" >_x000D_
<option value="22">Australia</option>_x000D_
<option value="23">Brunei</option>_x000D_
<option value="33">Cambodia</option>_x000D_
<option value="32">Canada</option>_x000D_
<option value="27">Dubai</option>_x000D_
<option value="28">Indonesia</option>_x000D_
<option value="25">Malaysia</option> _x000D_
</select>_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionValues()' value='print option values' />_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionTexts()' value='print option texts' />_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
_x000D_
Installing through brew on Mac where YOUR_USER_NAME and staff is the group
sudo mkdir -p /data/db
sudo chmod +x+r+w /data/db/
sudo touch /data/db/mongod.lock
sudo chown YOUR_USER_NAME:staff /data/db
sudo chmod +x+r+w /data/db/mongod.lock
sudo chown YOUR_USER_NAME:staff /data/db/mongod.lock
Explanation: You can *ngFor on the arrays. You have your users declared as the array. But, the response from the Get returns you an object. You cannot ngFor on the object. You should have an array for that. You can explicitly cast the object to array and that will solve the issue. data to [data]
Solution
getusers() {
this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
.map(response => response.json())
.subscribe(
data => this.users = [data], //Cast your object to array. that will do it.
error => console.log(error)
)
The function c.query() has two argument
c.query("Fetch Data", "Post-Processing of Data")
The operation "Fetch Data" in this case is a DB-Query, now this may be handled by Node.js by spawning off a worker thread and giving it this task of performing the DB-Query. (Remember Node.js can create thread internally). This enables the function to return instantaneously without any delay
The second argument "Post-Processing of Data" is a callback function, the node framework registers this callback and is called by the event loop.
Thus the statement c.query (paramenter1, parameter2)
will return instantaneously, enabling node to cater for another request.
P.S: I have just started to understand node, actually I wanted to write this as comment to @Philip but since didn't have enough reputation points so wrote it as an answer.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
do:
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow');
});
Updated Jsfiddle
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
Here's another take on the data.table
answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply
instead of sapply
):
library(data.table)
set.seed(1)
dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))
dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
# ID mean.Obs_1 mean.Obs_2 mean.Obs_3 sd.Obs_1 sd.Obs_2 sd.Obs_3
#1: 1 0.4854187 -0.3238542 0.7410611 1.1108687 0.2885969 0.1067961
#2: 2 0.4171586 -0.2397030 0.2041125 0.2875411 1.8732682 0.3438338
#3: 3 -0.3601052 0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692
If you only care about unimodal distributions, consider sth. like this.
public static Optional<Integer> mode(Stream<Integer> stream) {
Map<Integer, Long> frequencies = stream
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return frequencies.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey);
}
I got Solution for me :
Open "SQL Server Configuration Manager"
Now Click on "SQL Server Network Configuration" and Click on "Protocols for Name"
Right Click on "TCP/IP" (make sure it is Enabled) Click on Properties
Now Select "IP Addresses" Tab -and- Go to the last entry "IP All"
Enter "TCP Port" 1433.
Now Restart "SQL Server .Name." using "services.msc" (winKey + r)
It Will Work...
This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video controls >
<source src="sample.mp4" type="video/mp4">
<track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>
the video and subtitle files are stored in the same folder as default.htm
I have the very latest version of Chrome (just updated this morning)
When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!
(note that if I input localhost.. to IE11 the video plays!!!!
In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.
This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4
I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...
I don't know what since I called some procedures before successfully (but there where no out parameters)...
For this one I had entered
CALL my_sqrt(4,@out_value);
SELECT @out_value;
And it results with an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2
Strangely, if I write just:
CALL my_sqrt(4,@out_value);
The result message is: "Query canceled"
I guess, for now I will use only terminal...
Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style
Check out its already been answered, click here
It's worth mentioning that specifically for IE, disabled=disabled
works for anchor tags:
<a href="contact.html" onclick="unleashTheDragon();" disabled="disabled">Contact</a>
IE treats this as an disabled
element and does not trigger click event. However, disabled
is not a valid attribute on an anchor tag. Hence this won't work in other browsers. For them pointer-events:none
is required in the styling.
UPDATE 1: So adding following rule feels like a cross-browser solution to me
UPDATE 2: For further compatibility, because IE will not form styles for anchor tags with disabled='disabled'
, so they will still look active. Thus, a:hover{}
rule and styling is a good idea:
a[disabled="disabled"] {
pointer-events: none; /* this is enough for non-IE browsers */
color: darkgrey; /* IE */
}
/* IE - disable hover effects */
a[disabled="disabled"]:hover {
cursor:default;
color: darkgrey;
text-decoration:none;
}
Working on Chrome, IE11, and IE8.
Of course, above CSS assumes anchor tags are rendered with disabled="disabled"
Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can't pause the process at all. It is simply not applicable to process.
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).
It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).
But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.
A good example: here
And a good documentation from Mozilla: here
http://bootsnipp.com/snippets/featured/circle-button?
CSS:
.btn-circle { width: 30px; height: 30px; text-align: center;padding: 6px 0;font-size: 12px;line-height: 1.428571429;border-radius: 15px;}.btn-circle.btn-lg {width: 50px;height: 50px;padding: 10px 16px;font-size: 18px;line-height:1.33;border-radius: 25px;}
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
Python 2 / 3 including unicode
from __future__ import unicode_literals
from builtins import str # pip install future
isinstance('asdf', str) # True
isinstance(u'asdf', str) # True
There is a simplier way, create a form and post it, this runs the risk of resetting the page if the return mime type is something that a browser would open, but for csv and such it's perfect
Example requires underscore and jquery
var postData = {
filename:filename,
filecontent:filecontent
};
var fakeFormHtmlFragment = "<form style='display: none;' method='POST' action='"+SAVEAS_PHP_MODE_URL+"'>";
_.each(postData, function(postValue, postKey){
var escapedKey = postKey.replace("\\", "\\\\").replace("'", "\'");
var escapedValue = postValue.replace("\\", "\\\\").replace("'", "\'");
fakeFormHtmlFragment += "<input type='hidden' name='"+escapedKey+"' value='"+escapedValue+"'>";
});
fakeFormHtmlFragment += "</form>";
$fakeFormDom = $(fakeFormHtmlFragment);
$("body").append($fakeFormDom);
$fakeFormDom.submit();
For things like html, text and such, make sure the mimetype is some thing like application/octet-stream
php code
<?php
/**
* get HTTP POST variable which is a string ?foo=bar
* @param string $param
* @param bool $required
* @return string
*/
function getHTTPPostString ($param, $required = false) {
if(!isset($_POST[$param])) {
if($required) {
echo "required POST param '$param' missing";
exit 1;
} else {
return "";
}
}
return trim($_POST[$param]);
}
$filename = getHTTPPostString("filename", true);
$filecontent = getHTTPPostString("filecontent", true);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
echo $filecontent;
It's may be a little bit late, but here is more suitable code, for example when you need to use loops:
List<int> genered = new List<int>();
Random rnd = new Random();
for(int x = 0; x < files.Length; x++)
{
int value = rnd.Next(0, files.Length - 1);
while (genered.Contains(value))
{
value = rnd.Next(0, files.Length - 1);
}
genered.Add(value);
returnFiles[x] = files[value];
}
Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".
Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?
TreeSet<Integer> m = new TreeSet<Integer>();
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted
But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:
public class District {
String zipcode;
Double populationDensity;
}
Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:
public class District implements Comparable<District>{
String zipcode;
Double populationDensity;
public int compareTo(District other)
{
return populationDensity.compareTo(other.populationDensity);
}
}
Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.
Basically the ordering logic has to exist somewhere. That can be -
in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)
supplied in an external comparator, as in the example above.
Easy, simply wrap a MemoryStream
around it:
Stream stream = new MemoryStream(buffer);
I'm guessing from the responses that people aren't understanding your question... If I'm right in that you want to have ~\Desktop\github\ then changing the SDK location isn't what you're after.
From Android Studio 3.2.1: From the new project dialog, choose Configure -> Preferences -> Tools -> Terminal -> Start Directory
Put the folder you want as your project default in the field.
e.g. Mine is set to ~/Desktop/github/ since all my work is in ~/Desktop/github/
Use this to disable user input
android:focusable="false"
android:editable="false" This method is deprecated one.
OK, nevermind.. I found the trick:
scales: {
yAxes: [
{
gridLines: {
lineWidth: 0
}
}
]
}
IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.
This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.
Example:
Standard module code:
Option Explicit
Public Sub Main()
Dim myUserForm As UserForm1
Set myUserForm = New UserForm1
myUserForm.Show
End Sub
User form code:
Option Explicit
Private m_initializationDate As Date
Private Sub UserForm_Initialize()
m_initializationDate = VBA.DateTime.Date
MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub
Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.
lambda
is an anonymous function, not an arbitrary function. The parameter being accepted would be the variable you're working with, and the column in which you're sorting it on.
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
char *charPtr = "test string";
cout << charPtr << endl;
string str = charPtr;
cout << str << endl;
For this you can simply use the "HttpWebRequest" and "HttpWebResponse" classes in .net.
Below is a sample console app I wrote to demonstrate how easy this is.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string url = "www.somewhere.com";
string fileName = @"C:\output.file";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 5000;
try
{
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] bytes = ReadFully(response.GetResponseStream());
stream.Write(bytes, 0, bytes.Length);
}
}
}
catch (WebException)
{
Console.WriteLine("Error Occured");
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}
Enjoy!
You can't load JSON like that, sorry.
I know you're thinking "why I can't I just use src
here? I've seen stuff like this...":
<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>
<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
You have a short list of options to load your JSON from a remote file:
$.get('your.json')
or some other such AJAX method.Final point:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src="">
is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
I found it's better to set the width
and height
to 0px
. Otherwise, IE10 ignores the padding defined on the field -- padding-right
-- which was intended to keep the text from typing over the 'X' icon that I overlayed on the input field. I'm guessing that IE10 is internally applying the padding-right
of the input to the ::--ms-clear
pseudo element, and hiding the pseudo element does not restore the padding-right
value to the input
.
This worked better for me:
.someinput::-ms-clear {
width : 0;
height: 0;
}
How do you run a program all by itself without an operating system running?
You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).
Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?
General answer to the question: it can be done. It's often referred to as "bare metal programming". To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.
Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.
Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.
Edit: This article, and the whole wiki.osdev.org will anwer most of your questions http://wiki.osdev.org/Introduction
Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
After you have updated the latest GenyMotion Version to 2.10 from 2.02...
** C:\%Users%\AppData\Local\Genymobile\Genymotion\deployed
Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.
public static String decimalToBinaryString(int value) {
String str = "";
while(value > 0) {
if(value % 2 == 1) {
str = "1"+str;
} else {
str = "0"+str;
}
value /= 2;
}
return str;
}
Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable
using not empty operator on my dataModel
that extends javax.faces.model.ListDataModel
Code sample:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5
For Ubuntu 20.04 users with php-fpm I fixed the issue by adding the full path in the php conf:
edit /etc/php/7.4/fpm/conf.d/20-mysqli.ini
and replace
extension=mysqli.so
with:
extension=/usr/lib/php/20190902/mysqli.so
Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted
/etc/selinux/config
before change:
SELINUX=enforcing and SELINUXTYPE=permissive
/etc/selinux/config
after change:
SELINUX=permissive and SELINUXTYPE=permissive
I have two Java versions on my Ubuntu server 14.04: java 1.7
and java 1.8
.
I have a project that I need to build using java 1.8
.
If I check my Java version using java -version
I get
java version "1.8.0_144"
But when I did mvn -version
I get:
Java version: 1.7.0_79, vendor: Oracle Corporation
java8
I do this:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre/
Then when I do mvn -version
I get:
Java version: 1.8.0_144, vendor: Oracle Corporation
Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.
The empty page can be easily solved by using Shift key+reload button at the browser.
The empty page can be a result of:
Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.
To answer the question in a general manner:
Using z-index
will allow you to control this. see z-index at csstricks.
The element of higher z-index
will be displayed on top of elements of lower z-index
.
For instance, take the following HTML:
<div id="first">first</div>
<div id="second">second</div>
If I have the following CSS:
#first {
position: fixed;
z-index: 2;
}
#second {
position: fixed;
z-index: 1;
}
#first
wil be on top of #second
.
But specifically in your case:
The div
element is a child of the div
that you wish to put in front. This is not logically possible.
You can iterate DataTable
like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable
cell, you can cast the object to whatever you want.
As Doug Currie says use RunAsService.
From my past experience you must remember that the Service you generate will
not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.
Using pure bash :
$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt
another solution with bash regex :
$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
echo ${BASH_REMATCH[1]}
another solution using grep
and look-around advanced regex :
$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"
another solution using sed :
$ echo "US/Central - 10:26 PM (CST)" |
sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'
another solution using perl :
$ echo "US/Central - 10:26 PM (CST)" |
perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'
and last one using awk :
$ echo "US/Central - 10:26 PM (CST)" |
awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'
If you have a bitmap image and you want to use it in drawable, like
Bitmap contact_pic; //a picture to show in drawable
drawable = new BitmapDrawable(contact_pic);
Using moment.js as you asked, there is a unix
method that accepts unix timestamps in seconds:
var dateString = moment.unix(value).format("MM/DD/YYYY");
In short, they are equivalent. Let's have a history view:
(1) at first, the function looks like this.
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:
super(<class>, <instance>)
And init function can be:
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.
(3) in V3. It is more smart,
super()
is enough in most case. You can refer to http://www.python.org/dev/peps/pep-3135/
this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.
''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task
''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task
''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource
''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
Me._ActionTask = Task.Run(taskAction)
Await Me.ActionTask ' Task.Run(streamEntitiesAction)
Try
Me.ActionTask?.Wait()
Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
Catch ex As AggregateException
Me.OnExceptionOccurred(ex)
Finally
Me.TaskCancellationSource.Dispose()
End Try
End Function
''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey"> The bucket key. </param>
''' <param name="timeout"> The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
If Me.IsTaskActive Then
Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
Else
Me._TaskCancellationSource = New Threading.CancellationTokenSource
Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
Me.TaskCancellationSource.CancelAfter(timeout)
' the action class is created withing the Async/Await function
Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
End If
End Sub
at a guess:
sudo apt-get install mysql-client
Create a Empty Guid or New Guid Using a Class...
Default value of Guid is 00000000-0000-0000-0000-000000000000
public class clsGuid ---This is class Name
{
public Guid MyGuid { get; set; }
}
static void Main(string[] args)
{
clsGuid cs = new clsGuid();
Console.WriteLine(cs.MyGuid); --this will give empty Guid "00000000-0000-0000-0000-000000000000"
cs.MyGuid = new Guid();
Console.WriteLine(cs.MyGuid); ----this will also give empty Guid "00000000-0000-0000-0000-000000000000"
cs.MyGuid = Guid.NewGuid();
Console.WriteLine(cs.MyGuid); --this way, it will give new guid "d94828f8-7fa0-4dd0-bf91-49d81d5646af"
Console.ReadKey(); --this line holding the output screen in console application...
}
MySQL doesn't care what IP its on. Closest you could get would be hostname:
select * from GLOBAL_variables where variable_name like 'hostname';
I was also struggling with same issue. The bootstrap classes I use are not working for me. I came up with an workaround, as below:
<form action='...' method='POST' class='form-group'>
<div class="form-horizontal">
<input type="text" name="..."
class="form-control"
placeholder="Search People..."
style="width:280px;max-width:280px;display:inline-block"/>
<button type="submit"
class="btn btn-primary"
style="margin-left:-8px;margin-top:-2px;min-height:36px;">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</form>
Basically, I overrode the display property of class "form-control", and used other style properties for correcting the size and position.
Following is the result:
You can do it even without the HTTP_PROXY environment variable. Try this sample:
import urllib2
proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
html = urllib2.urlopen("http://www.google.com").read()
print html
In your case it really seems that the proxy server is refusing the connection.
Something more to try:
import urllib2
#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"
proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}
proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)
req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html
Edit 2014:
This seems to be a popular question / answer. However today I would use third party requests
module instead.
For one request just do:
import requests
r = requests.get("http://www.google.com",
proxies={"http": "http://61.233.25.166:80"})
print(r.text)
For multiple requests use Session
object so you do not have to add proxies
parameter in all your requests:
import requests
s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}
r = s.get("http://www.google.com")
print(r.text)
Repository are nothing but well-designed DAO.
ORM are table centric but not DAO.
There's no need to use several DAO in repository since DAO itself can do exactly the same with ORM repositories/entities or any DAL provider, no matter where and how a car is persisted 1 table, 2 tables, n tables, half a table, a web service, a table and a web service etc. Services uses several DAO/repositories.
My own DAO, let's say CarDao only deal with Car DTO,I mean, only take Car DTO in input and only return car DTO or car DTO collections in output.
So just like Repository, DAO actually is an IoC, for the business logic, allowing persitence interfaces not be be intimidated by persitence strategies or legacies. DAO both encapsulates the persistence strategy and does provide the domaine-related persitence interface. Repository is just an another word for those who had not understood what a well-defined DAO actualy was.
Don't think of coordinates as indicating where pixels are. Think of them as being between the pixels. That way, the area of a 2x2 rectangle should be 4, not 9.
bool bOverlap = !((A.Left >= B.Right || B.Left >= A.Right)
&& (A.Bottom >= B.Top || B.Bottom >= A.Top));
@sfjedi
I've created a class and assigned the css values to it.
.radioA{
vertical-align: middle;
}
It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.
This can also be controlled with the apache configuration. Check the httpd.conf and/or .htaccess for something like the following:
php_value upload_max_filesize 10M
Go to Windows--> Preference--->Java--->content assist--->Enable auto activation---(insert ._@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ in auto activation triggers for java)
This stored procedure will provide you with a hierarchical tree of relationship. Based on this article from Technet. It will also optionally provide you a query for reading or deleting all the related data.
IF OBJECT_ID('GetForeignKeyRelations','P') IS NOT NULL
DROP PROC GetForeignKeyRelations
GO
CREATE PROC GetForeignKeyRelations
@Schemaname Sysname = 'dbo'
,@Tablename Sysname
,@WhereClause NVARCHAR(2000) = ''
,@GenerateDeleteScripts bit = 0
,@GenerateSelectScripts bit = 0
AS
SET NOCOUNT ON
DECLARE @fkeytbl TABLE
(
ReferencingObjectid int NULL
,ReferencingSchemaname Sysname NULL
,ReferencingTablename Sysname NULL
,ReferencingColumnname Sysname NULL
,PrimarykeyObjectid int NULL
,PrimarykeySchemaname Sysname NULL
,PrimarykeyTablename Sysname NULL
,PrimarykeyColumnname Sysname NULL
,Hierarchy varchar(max) NULL
,level int NULL
,rnk varchar(max) NULL
,Processed bit default 0 NULL
);
WITH fkey (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
AS
(
SELECT
soc.object_id
,scc.name
,soc.name
,convert(sysname,null)
,convert(int,null)
,convert(sysname,null)
,convert(sysname,null)
,convert(sysname,null)
,CONVERT(VARCHAR(MAX), scc.name + '.' + soc.name ) as Hierarchy
,0 as level
,rnk=convert(varchar(max),soc.object_id)
FROM SYS.objects soc
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
WHERE scc.name =@Schemaname
AND soc.name =@Tablename
UNION ALL
SELECT sop.object_id
,scp.name
,sop.name
,socp.name
,soc.object_id
,scc.name
,soc.name
,socc.name
,CONVERT(VARCHAR(MAX), f.Hierarchy + ' --> ' + scp.name + '.' + sop.name ) as Hierarchy
,f.level+1 as level
,rnk=f.rnk + '-' + convert(varchar(max),sop.object_id)
FROM SYS.foreign_key_columns sfc
JOIN Sys.Objects sop
ON sfc.parent_object_id = sop.object_id
JOIN SYS.columns socp
ON socp.object_id = sop.object_id
AND socp.column_id = sfc.parent_column_id
JOIN sys.schemas scp
ON sop.schema_id = scp.schema_id
JOIN SYS.objects soc
ON sfc.referenced_object_id = soc.object_id
JOIN SYS.columns socc
ON socc.object_id = soc.object_id
AND socc.column_id = sfc.referenced_column_id
JOIN sys.schemas scc
ON soc.schema_id = scc.schema_id
JOIN fkey f
ON f.ReferencingObjectid = sfc.referenced_object_id
WHERE ISNULL(f.PrimarykeyObjectid,0) <> f.ReferencingObjectid
)
INSERT INTO @fkeytbl
(ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk)
SELECT ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname
,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk
FROM fkey
SELECT F.Relationshiptree
FROM
(
SELECT DISTINCT Replicate('------',Level) + CASE LEVEL WHEN 0 THEN '' ELSE '>' END + ReferencingSchemaname + '.' + ReferencingTablename 'Relationshiptree'
,RNK
FROM @fkeytbl
) F
ORDER BY F.rnk ASC
-------------------------------------------------------------------------------------------------------------------------------
-- Generate the Delete / Select script
-------------------------------------------------------------------------------------------------------------------------------
DECLARE @Sql VARCHAR(MAX)
DECLARE @RnkSql VARCHAR(MAX)
DECLARE @Jointables TABLE
(
ID INT IDENTITY
,Object_id int
)
DECLARE @ProcessTablename SYSNAME
DECLARE @ProcessSchemaName SYSNAME
DECLARE @JoinConditionSQL VARCHAR(MAX)
DECLARE @Rnk VARCHAR(MAX)
DECLARE @OldTablename SYSNAME
IF @GenerateDeleteScripts = 1 or @GenerateSelectScripts = 1
BEGIN
WHILE EXISTS ( SELECT 1
FROM @fkeytbl
WHERE Processed = 0
AND level > 0 )
BEGIN
SELECT @ProcessTablename = ''
SELECT @Sql = ''
SELECT @JoinConditionSQL = ''
SELECT @OldTablename = ''
SELECT TOP 1 @ProcessTablename = ReferencingTablename
,@ProcessSchemaName = ReferencingSchemaname
,@Rnk = RNK
FROM @fkeytbl
WHERE Processed = 0
AND level > 0
ORDER BY level DESC
SELECT @RnkSql ='SELECT ' + REPLACE (@rnk,'-',' UNION ALL SELECT ')
DELETE FROM @Jointables
INSERT INTO @Jointables
EXEC(@RnkSql)
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT [' + @ProcessSchemaName + '].[' + @ProcessTablename + '].*' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10)
SELECT @JoinConditionSQL = @JoinConditionSQL
+ CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN 'JOIN [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '] ' + CHAR(10) + ' ON '
ELSE ' AND '
END
+ ' [' + f.PrimarykeySchemaname + '].[' + f.PrimarykeyTablename + '].[' + f.PrimarykeyColumnname + '] = [' + f.ReferencingSchemaname + '].[' + f.ReferencingTablename + '].[' + f.ReferencingColumnname + ']' + CHAR(10)
, @OldTablename = CASE
WHEN @OldTablename <> f.PrimarykeyTablename THEN f.PrimarykeyTablename
ELSE @OldTablename
END
FROM @fkeytbl f
JOIN @Jointables j
ON f.Referencingobjectid = j.Object_id
WHERE charindex(f.rnk + '-',@Rnk + '-') <> 0
AND F.level > 0
ORDER BY J.ID DESC
SELECT @Sql = @Sql + @JoinConditionSQL
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE (' + @WhereClause + ')'
PRINT @SQL
PRINT CHAR(10)
UPDATE @fkeytbl
SET Processed = 1
WHERE ReferencingTablename = @ProcessTablename
AND rnk = @Rnk
END
IF @GenerateDeleteScripts = 1
SELECT @Sql = 'DELETE FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF @GenerateSelectScripts = 1
SELECT @Sql = 'SELECT * FROM [' + @Schemaname + '].[' + @Tablename + ']'
IF LTRIM(RTRIM(@WhereClause)) <> ''
SELECT @Sql = @Sql + ' WHERE ' + @WhereClause
PRINT @SQL
END
SET NOCOUNT OFF
go