Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".
if you are using IOS react native platform and want to debugging real android device you can use following code:
adb reverse tcp:8081 tcp:8081
npm start -- --reset-cache
react-native run-android
Set the aaSorting
option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.
"aaSorting": []
The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').
Use
[self dismissViewControllerAnimated:NO completion:nil];
<asp:Button ID="btnSubmit" runat="server" OnClientClick ="showDiv()"
OnClick="btnImport_Click" Text="Upload" ></asp:Button>
For those who are more comfortable with learning by visualizing, here is a handy diagram I created to explain Process and Threads.
I used the information from MSDN - About Processes and Threads
For .NET server can configure this in web.config as shown below
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
</customHeaders>
</httpProtocol>
</system.webServer>
For instance lets say, if the server domain is http://live.makemypublication.com and client is http://www.makemypublication.com then configure in server's web.config as below
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.makemypublication.com" />
</customHeaders>
</httpProtocol>
</system.webServer>
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\
" prefix the path to use greater than 260 characters.
A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths
Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the
\\?\
prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.
this function takes the number and precision and returns the rounded off number
float roundoff(float num,int precision)
{
int temp=(int )(num*pow(10,precision));
int num1=num*pow(10,precision+1);
temp*=10;
temp+=5;
if(num1>=temp)
num1+=10;
num1/=10;
num1*=10;
num=num1/pow(10,precision+1);
return num;
}
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
You are looking for the android:layout_weight
attribute. It will allow you to use percentages to define your layout.
In the following example, the left button uses 70% of the space, and the right button 30%.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".70" />
<Button
android:text="right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30" />
</LinearLayout>
It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs.
Be sure to set the layout_width
to 0dp
or your views may not be scaled properly.
Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result.
Complete example of encrypting/Decrypting a huge video without throwing Java OutOfMemoryException
and using Java SecureRandom
for Initialization Vector generation. Also depicted storing key bytes to database and then reconstructing same key from those bytes.
I believe you can also get just the Xcode command-line tools which is about 170 MB.. It's described in the 'brew' setup guide: https://github.com/mxcl/homebrew/wiki/installation and can be found here: https://developer.apple.com/downloads/index.action#
Edit: this was already mentioned above by @josh
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
Here is my code below perfectly working Do not add the header in NavigationView tag in activity_main.xml
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="@menu/activity_main_drawer"
app:itemBackground="@drawable/active_drawer_color" />
add header programmatically with below code
View navHeaderView = navigationView.inflateHeaderView(R.layout.nav_header_main);
headerUserName = (TextView) navHeaderView.findViewById(R.id.nav_header_username);
headerMobileNo = (TextView) navHeaderView.findViewById(R.id.nav_header_mobile);
headerMobileNo.setText("+918861899697");
headerUserName.setText("Anirudh R Huilgol");
http://www.decompileandroid.com/
This website will decompile the code embedded in APK files and extract all the other assets in the file.
Go to the Build Path
dialog (right-click project > Build Path > Configure Build Path
) and make sure you have the correct source folder listed, and make sure it exists.
The source folder is the one that holds your sources, usuglaly in the form: project/src/com/yourpackage/...
sklearn.cross_validation
is deprecated since version 0.18, instead you should use sklearn.model_selection
as show below
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
Yes I think this would be quicker.
Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1
To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.
To get the hour, do (hour % 12) || 12
.
This should do it:
var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;
That assumes that AM times are formatted as, eg, 08:00:00
. If they are formatted without the leading zero, you would have to test the position of the first colon:
var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;
merge into MY_TABLE tgt
using (select [expressions]
from dual ) src
on (src.key_condition = tgt.key_condition)
when matched then
update tgt
set tgt.column1 = src.column1 [,...]
when not matched then
insert into tgt
([list of columns])
values
(src.column1 [,...]);
How to write literal boolean value in SQL Server?
select * from SomeTable where PSEUDO_TRUE
There is no such thing.
You have to compare the value with something using = < > like ...
. The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null
, 0
and 1
.
would this work?
function eraseCookie(name) {
document.cookie = name + '=; Max-Age=0'
}
I know Max-Age
causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.
Here is code you can get url segment.
{{ Request::segment(1) }}
If you don't want the data to be escaped then use {!! !!} else use {{ }}.
{!! Request::segment(1) !!}
According to the Swift 2.2 Book published by apple:
“You indicate type methods by writing the static
keyword before the method’s func keyword. Classes may also use the class
keyword to allow subclasses to override the superclass’s implementation of that method.”
I'll add something that helps me out a lot with cygwin. Whenever setting up a new system, I always do this
ln -s /cygdrive/c /c
This creates a symbolic link to /cygdrive/c
with a new file called /c
(in the home directory)
Then you can do this in your shell
cd /c/Foo
cd /c/
Very handy.
add Microsoft.AspNet.Mvc nuget package.
if you have to pass the value you should enter url like this
localhost/yoururl/index.php/products_controller/delete_controller/70
and in controller function you can read like this
function delete_controller( $product_id = NULL ) {
echo $product_id;
}
If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding ID}"/>
</StackPanel>
That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.
Swift 3
self.paddingView.layer.masksToBounds = false
self.paddingView.layer.shadowOffset = CGSize(width: -15, height: 10)
self.paddingView.layer.shadowRadius = 5
self.paddingView.layer.shadowOpacity = 0.5
You can't always rely on MIME type..
According to: http://filext.com/file-extension/CSV
text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext
There are various MIME types for CSV.
Your probably best of checking extension, again not very reliable, but for your application it may be fine.
$info = pathinfo($_FILES['uploadedfile']['tmp_name']);
if($info['extension'] == 'csv'){
// Good to go
}
Code untested.
Little bit more complex data, mix of @Laran's and @Nisal Gunawardana's answers
[
{
"foodItemsList":[
{
"id":7,
"price":240,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"price":340,
"customer_id":1
},
{
"foodItemsList":[
{
"id":7,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"customer_id":2
}
]
The validation rule will be
return [
'*.customer_id' => 'required|numeric|exists:customers,id',
'*.foodItemsList.*.id' => 'required|exists:food_items,id',
'*.foodItemsList.*.quantity' => 'required|numeric',
];
None of the other answers worked for me. I fixed my error by changing the web project's output path. I had had it set to bin\debug but the web project doesn't work unless the output path is set to simply "bin"
The default null value for a field is "not null". So you must set it to "null" before you can set that field value for any record to null. Then you can:
UPDATE `myTable` SET `myField` = null
A const int var
can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed.
A constexpr int var
cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.
Here is a solid example:
int main(int argc, char*argv[]) {
const int p = argc;
// p = 69; // cannot change p because it is a const
// constexpr int q = argc; // cannot be, bcoz argc cannot be computed at compile time
constexpr int r = 2^3; // this works!
// r = 42; // same as const too, it cannot be changed
}
The snippet above compiles fine and I have commented out those that cause it to error.
The key notions here to take note of, are the notions of compile time
and run time
. New innovations have been introduced into C++ intended to as much as possible ** know **
certain things at compilation time to improve performance at runtime.
Any attempt of explanation which does not involve the two key notions above, is hallucination.
You could use Javascript to achieve this. Try the following code:
HTML
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
JS
document.getElementById("myDropdown").selectedIndex = -1;
or JQuery
$("#myDropdown").prop("selectedIndex", -1);
Sometimes it is the simple things. In my case, I had an invalid url. I had left out a colon before the at sign (@). I had "jdbc:oracle:thin@//localhost" instead of "jdbc:oracle:thin:@//localhost" Hope this helps someone else with this issue.
It's preferable to use context managers to close the files automatically
with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
for line in textfile:
var1, var2 = line.split(",");
myfile.writelines(var1)
Swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor.darkGray
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor.clear
}
/^[0-9\+]{1,}[0-9\-]{3,15}$/
so first is a digit or a +, then some digits or -
The following solution would take 2(N-1) comparisons:
arr #array with 'n' elements
first=arr[0]
second=-999999 #large negative no
i=1
while i is less than length(arr):
if arr[i] greater than first:
second=first
first=arr[i]
else:
if arr[i] is greater than second and arr[i] less than first:
second=arr[i]
i=i+1
print second
You can just use the ContentResult
to return a plain string:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult
by default returns a text/plain
as its contentType. This is overloadable so you can also do:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Kotlin implementation I recently made based on Edward's answer:
fun setEnv(newEnv: Map<String, String>) {
val unmodifiableMapClass = Collections.unmodifiableMap<Any, Any>(mapOf()).javaClass
with(unmodifiableMapClass.getDeclaredField("m")) {
isAccessible = true
@Suppress("UNCHECKED_CAST")
get(System.getenv()) as MutableMap<String, String>
}.apply {
clear()
putAll(newEnv)
}
}
In my case,
image = cv2.imread(filepath)
final_img = cv2.resize(image, size_img)
filepath was incorrect, cv2.imshow didn't give any error in this case but due to wrong path cv2.resize was giving me error.
Update:
Since git rm .
deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:
git reset HEAD . # This undoes the index changes
git checkout . # This checks out files in this and child directories from the HEAD
This should do what you want. It does not affect parent folders of your checked-out code or index.
Old answer that wasn't:
reset HEAD
will do the trick, and will not erase any uncommitted changes you have made to your files.
after that you need to repeat any git add
commands you had queued up.
public class MyActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_options);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
button.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.button:
// Write your code here first button
break;
case R.id.button2:
// Write your code here for second button
break;
}
}
}
Have a look at this archived question: TortoiseSVN for Mac? at superuser. (Original question was removed, so only archive remains.)
Have a look at this page for more likely up to date alternatives to TortoiseSVN for Mac: Alternative to: TortoiseSVN
If you are running xampp on linux based image, to change root directory open:
/opt/lampp/etc/httpd.conf
Change default document root:
DocumentRoot "/opt/lampp/htdocs" and <Directory "/opt/lampp/htdocs"
to your folder DocumentRoot "/opt/lampp/htdocs/myFolder" and <Directory "/opt/lampp/htdocs/myFolder">
try:
SELECT first_name + ISNULL(' '+last_name, '') AS Name FROM dbo.person
This adds the space to the last name, if it is null, the entire space+last name goes to NULL and you only get a first name, otherwise you get a firts+space+last name.
this will work as long as the default setting for concatenation with null strings is set:
SET CONCAT_NULL_YIELDS_NULL ON
this shouldn't be a concern since the OFF
mode is going away in future versions of SQl Server
I can confirm this works:
class CSSImporter < Sass::Importers::Filesystem
def extensions
super.merge('css' => :scss)
end
end
view_context = ActionView::Base.new
css = Sass::Engine.new(
template,
syntax: :scss,
cache: false,
load_paths: Rails.application.assets.paths,
read_cache: false,
filesystem_importer: CSSImporter # Relevant option,
sprockets: {
context: view_context,
environment: Rails.application.assets
}
).render
Credit to Chriss Epstein: https://github.com/sass/sass/issues/193
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
The method above will bring you something like this:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
From here you can navigate backwards using System.IO.Directory.GetParent:
_filePath = Directory.GetParent(_filePath).FullName;
1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:
_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
Hope it helps.
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
If you're trying to query an Oracle database, you might want to use
select owner, table_name
from all_tab_columns
where column_name = 'ColName';
You can try this as well, it is easy to implement
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
Change the text to which standard time you want to change.
Use TimeZone
feature of C# to implement.
Here is a solution that does not involve querying INFORMATION_SCHEMA
, it simply ignores the error if the column does exist.
DROP PROCEDURE IF EXISTS `?`;
DELIMITER //
CREATE PROCEDURE `?`()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
ALTER TABLE `table_name` ADD COLUMN `column_name` INTEGER;
END //
DELIMITER ;
CALL `?`();
DROP PROCEDURE `?`;
P.S. Feel free to give it other name rather than ?
A simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
use eModal to display a modal for alert, ajax, prompt or confirm
// Display an alert modal with default title (Attention)
eModal.alert('You shall not pass!');
I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
@Ian Nelson: I'm wondering if others see the problem there.
Let's say you have split fields. That's 70 characters total, 35 for first name and 35 for last name. However, if you have one field, you neglect the space that separates first and last names, short changing you by 1 character. Sure, it's "only" one character, but that could make the difference between someone entering their full name and someone not. Therefore, I would change that suggestion to "35 characters for each of Given Name and Family Name, or 71 characters for a single field to hold the Full Name".
function resize() {
var canvas = document.getElementById('game');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
};
window.addEventListener('resize', resize, false);
to use unverified ssl you can add this to your code:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ?+x, it will output 120, true
This only seems to work in Safari - not Chrome
Diagrams are back as of the June 11 2019 release
as stated:
Yes, we’ve heard the feedback; Database Diagrams is back.
SQL Server Management Studio (SSMS) 18.1 is now generally available
?? Latest Version Does Not Included It ??
Sadly, the last version of SSMS to have database diagrams as a feature was version v17.9.
Since that version, the newer preview versions starting at v18.* have, in their words "...feature has been deprecated".
Hope is not lost though, for one can still download and use v17.9 to use database diagrams which as an aside for this question is technically not a ER diagramming tool.
As of this writing it is unclear if the release version of 18 will have the feature, I hope so because it is a feature I use extensively.
cd
. .bash_profile
You need to use Range
and Valu
e functions.
Range
would be the cell where you want the text you want
Value
would be the text that you want in that Cell
Range("A1").Value="whatever text"
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
For the LISTEN, ESTABLISHED and CLOSED ports
sudo lsof -n -i -P | grep TCP
For the LISTEN ports only
sudo lsof -n -i -P | grep LISTEN
For a specific LISTEN port, ex: port 80
sudo lsof -n -i -P | grep ':80 (LISTEN)'
Or if you just want a compact summary [no service/apps described], go by NETSTAT. The good side here is, no sudo needed
netstat -a -n | grep 'LISTEN '
Explaining the items used:
-n suppress the host name
-i for IPv4 and IPv6 protocols
-P omit port names
-a [over netstat] for all sockets
-n [over netstat] don't resolve names, show network addresses as numbers
Tested on High Sierra 10.13.3 and Mojave 10.14.3
- the last syntax netstat works on linux too
Check if the jQuery object contains any element before you try to get its offset:
var nav = $('.content-nav');
if (nav.length) {
var contentNav = nav.offset().top;
...continue to set up the menu
}
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
some of the answers assume you have 'eslint-plugin-jest' installed, however without needing to do that, you can simply do this in your .eslintrc
file, add:
"globals": {
"jest": true,
}
A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):
import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
for file in files:
filepath = subdir + os.sep + file
# you can have multiple endswith
if filepath.endswith((".pdf", ".PDF")):
file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)
for k, v in file_dict.items():
print(k, v)
merger.append(v)
merger.write("combined_result.pdf")
In case someone is using swagger:
Change the Scheme to HTTP
or HTTPS
, depend on needs, prior to hit the execute.
Postman:
Change the URL Path to http://
or https://
in the url address
I've used SQL Delta before (http://www.sqldelta.com/), it's really good. Not free however, not sure how prices compare to Red-Gates
Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.
$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts
Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.
#!/bin/bash
#Jason Xiong: Dec 2013
# The ip or ipalias stored in known_hosts file is hashed and
# is not human readable.This script check if the supplied ip
# or ipalias exists in ~/.ssh/known_hosts file
if [[ $# != 2 ]]; then
echo "Usage: ./search_known_hosts -i ip_or_ipalias"
exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;
cat $known_host_file | while read -r line;do
if [[ -z "$line" ]]; then
continue;
fi
hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}');
key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}');
hex_key=$(echo $key | base64 -d | xxd -p);
if [[ $hash_type = 1 ]]; then
gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
-macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);
if [[ $gen_value = $stored_value ]]; then
echo $gen_value;
echo "Found match in known_hosts file : entry#"$entry" !!!!"
fi
else
echo "unknown hash_type"
fi
entry=$((entry + 1));
done
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
You Should Try
After Setting The Frame
NSArray *arr10 =[NSArray arrayWithObjects:btn1,btn2,nil];
for(UIButton *btn10 in arr10)
{
CAGradientLayer *btnGradient2 = [CAGradientLayer layer];
btnGradient2.frame = btn10.bounds;
btnGradient2.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:151.0/255.0f green:206.0/255.5 blue:99.0/255.0 alpha:1] CGColor],
(id)[[UIColor colorWithRed:126.0/255.0f green:192.0/255.5 blue:65.0/255.0 alpha:1]CGColor],
nil];
[btn10.layer insertSublayer:btnGradient2 atIndex:0];
}
In addition to the other answers here you can naturally use the XmlDocument class, for XML DOM-like reading, or the XmlReader, fast forward-only reader, to do it "by hand".
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
Adding lots of load balancers creates extra overhead and latency and that is the drawback for scaling out horizontally in nosql databases. It is like the question why people say RPC is not recommended since it is not robust.
I think in a real system we should use both sql and nosql databases to utilize both multicore and cloud computing capabilities of today's systems.
On the other hand, complex transactional queries has high performance if sql databases such as oracle being used. NoSql could be used for bigdata and horizontal scalability by sharding.
I had this issue with Xcode 4.2.1.
For me it was nothing to do with Entitlements file, or Ad-hoc...
I was returning to and old project, and I'd forgotten to add my new iPhone to the provision.
Silly mistake, but also a silly corresponding error message... :-/
import React from 'react';
import {connect} from 'react-redux';
import Userlist from './Userlist';
class Userdetails extends React.Component{
render(){
return(
<div>
<p>Name : <span>{this.props.user.name}</span></p>
<p>ID : <span>{this.props.user.id}</span></p>
<p>Working : <span>{this.props.user.Working}</span></p>
<p>Age : <span>{this.props.user.age}</span></p>
</div>
);
}
}
function mapStateToProps(state){
return {
user:state.activeUser
}
}
export default connect(mapStateToProps, null)(Userdetails);
var base_element = document.getElementById('__EXAMPLE_ELEMENT__');
for( var found_parent=base_element, i=100; found_parent.parentNode && !(found_parent=found_parent.parentNode).classList.contains('__CLASS_NAME__') && i>0; i-- );
console.log( found_parent );
You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Then you can get hold of the axes objects (an array of axes):
axes = lm.axes
After that you can tweak the axes properties
axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)
creates:
The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:
JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab
Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.
A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.
And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:
And now you have these tools at your disposal:
Ctrl+Enter
Shift+Enter
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...
FragmentStatePagerAdapter:
with FragmentStatePagerAdapter
,your unneeded fragment is
destroyed.A transaction is committed to completely remove the
fragment from your activity's FragmentManager
.
The state in FragmentStatePagerAdapter
comes from the fact that it
will save out your fragment's Bundle
from savedInstanceState
when
it is destroyed.When the user navigates back,the new fragment will be
restored using the fragment's state.
FragmentPagerAdapter:
By comparision FragmentPagerAdapter
does nothing of the kind.When
the fragment is no longer needed.FragmentPagerAdapter
calls
detach(Fragment)
on the transaction instead of remove(Fragment)
.
This destroy's the fragment's view but leaves the fragment's instance
alive in the FragmentManager
.so the fragments created in the
FragmentPagerAdapter
are never destroyed.
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
You need to either convert each table individually:
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4
(this will convert the columns just as well), or export the database with latin1
and import it back with utf8mb4
.
For another non-invasive, current-user only approach:
# First, make $HOME/bin, which will be automatically added to user's PATH
mkdir -p ~/bin
# make link actual python binaries
ln -s $(which python3) python
ln -s $(which pip3) pip
python
pip
will be ready in a new shell.
As distributionUrl
is still pointing to older version, upgrade wrapper using:
gradle wrapper --gradle-version 5.1.1
Note: Use gradle
and not gradlew
String is immutable, meaning that when you perform an operation on a String you are really creating a whole new String.
StringBuffer is mutable, and you can append to it as well as reset its length to 0.
In practice, the compiler seems to use StringBuffer during String concatenation for performance reasons.
As a general rule, I declare my variables in the inner-most possible scope. So, if you're not using intermediateResult outside of the loop, then I'd go with B.
Redirect aspx :
<iframe>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.avsapansiyonlar.com/altinkum-tatil-konaklari.aspx");
}
</script>
</iframe>
You may use this formula to get the path of the file:
=LEFT(CELL("filename"),FIND("[",CELL("filename"),1)-1)
The best solution:-
angular.module("myapp").controller("frstCtrl",function($scope){
$scope.name="Atul Singh";
})
.controller("secondCtrl",function($scope){
angular.extend(this, $controller('frstCtrl', {$scope:$scope}));
console.log($scope);
})
// Here you got the first controller call without executing it
If it's really required to access SessionFactory through @Autowire, I'd rather configure another EntityManagerFactory and then use it to configure the SessionFactory bean, like following:
@Configuration
public class SessionFactoryConfig {
@Autowired
DataSource dataSource;
@Autowired
JpaVendorAdapter jpaVendorAdapter;
@Bean
@Primary
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPackagesToScan("com.hibernateLearning");
emf.setPersistenceUnitName("default");
emf.afterPropertiesSet();
return emf.getObject();
}
@Bean
public SessionFactory setSessionFactory(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.unwrap(SessionFactory.class);
} }
If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .
Example:
views.py:
def my_view(request, interview_pk):
interview = Interview.objects.get(pk=interview_pk)
all_rounds = interview.round_set.order_by('created_at')
all_round_names = [rnd.name for rnd in all_rounds]
form = forms.AddRatingForRound(all_round_names)
return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})
forms.py
class AddRatingForRound(forms.ModelForm):
def __init__(self, round_list, *args, **kwargs):
super(AddRatingForRound, self).__init__(*args, **kwargs)
self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))
class Meta:
model = models.RatingSheet
fields = ('name', )
template:
<form method="post">
{% csrf_token %}
{% if interview %}
{{ interview }}
{% endif %}
{% if rounds %}
<hr>
{{ form.as_p }}
<input type="submit" value="Submit" />
{% else %}
<h3>No rounds found</h3>
{% endif %}
</form>
same issue after removing properties from a schema after first building some indexes on saving. removing property from schema leads to an null value for a non existing property, that still had an index. dropping index or starting with a new collection from scratch helps here.
note: the error message will lead you in that case. it has a path, that does not exist anymore. im my case the old path was ...$uuid_1 (this is an index!), but the new one is ....*priv.uuid_1
Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.
df.coalesce(1)
.write
.option("header","true")
.option("sep",",")
.mode("overwrite")
.csv("output/path")
If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.
This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent
was an interface, as was in my case, then
SignInComponent
should be in a file named SignInComponent.ts
.
As already answered, the C standards have no way to directly write binary numbers. There are compiler extensions, however, and apparently C++14 includes the 0b
prefix for binary. (Note that this answer was originally posted in 2010.)
One popular workaround is to include a header file with helper macros. One easy option is also to generate a file that includes macro definitions for all 8-bit patterns, e.g.:
#define B00000000 0
#define B00000001 1
#define B00000010 2
…
This results in only 256 #define
s, and if larger than 8-bit binary constants are needed, these definitions can be combined with shifts and ORs, possibly with helper macros (e.g., BIN16(B00000001,B00001010)
). (Having individual macros for every 16-bit, let alone 32-bit, value is not plausible.)
Of course the downside is that this syntax requires writing all the leading zeroes, but this may also make it clearer for uses like setting bit flags and contents of hardware registers. For a function-like macro resulting in a syntax without this property, see bithacks.h
linked above.
In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];
Array.from(array1).forEach(element =>
console.log(element)
);
in my case I want to loop through files and add their types to another array:
Array.from(files).forEach((file) => {
if(this.mediaTypes.image.includes(file.type)) {
this.media.images.push(file)
console.log(this.media.images)
}
}
In java array length is fixed.
You can use a List to hold the values and invoke the toArray
method if needed
See the following sample:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class A {
public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();
// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}
// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );
System.out.println( "size of array = " + array.length );
}
}
class xClass {}
I would add that HTMLElement has a built-in .blur
method as well.
Here's a demo using both .focus
and .blur
which work in similar ways.
const input = document.querySelector("#myInput");
_x000D_
<input id="myInput" value="Some Input">_x000D_
_x000D_
<button type="button" onclick="input.focus()">Focus</button>_x000D_
<button type="button" onclick="input.blur()">Lose focus</button>
_x000D_
**multiple delete not working**
function delete_selection()
{
$id_array = array();
$selection = $this->input->post("selection", TRUE);
$id_array = explode("|", $selection);
foreach ($id_array as $item):
if ($item != ''):
//DELETE ROW
$this->db->where('entry_id', $item);
$this->db->delete('helpline_entry');
endif;
endforeach;
}
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
a = ['it']
b = ['was']
c = ['annoying']
a.extend(b)
a.extend(c)
# a now equals ['it', 'was', 'annoying']
If you want "Use Autolayout" to be enabled at any cost place the following code in viewdidload.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
{
self.edgesForExtendedLayout = UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars = NO;
self.automaticallyAdjustsScrollViewInsets = NO;
}
Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:
bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
If you happen to use Vavr(formerly known as Javaslang), you can leverage the dedicated method:
Stream.of("A", "B", "C")
.zipWithIndex();
If we print out the content, we will see something interesting:
Stream((A, 0), ?)
This is because Streams
are lazy and we have no clue about next items in the stream.
You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.
Extract from Android Developer Guide link above:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
Here is my take on the problem:
from math import sqrt
from itertools import count, islice
def is_prime(n):
return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1)))
This is a really simple and concise algorithm, and therefore it is not meant to be anything near the fastest or the most optimal primality check algorithm. It has a time complexity of O(sqrt(n))
. Head over here to learn more about primality tests done right and their history.
I'm gonna give you some insides about that almost esoteric single line of code that will check for prime numbers:
First of all, using range()
in Python 2 is really a bad idea, because it will create a list of numbers, which uses a lot of memory. Using xrange()
is better, because it creates a generator, which only needs to memorize the initial arguments you provide, and generates every number on-the-fly. If you're using
Python 3, range()
has been converted to a generator by default. By the way, this is still not the best solution: trying to call xrange(n)
for some n
such that n > 231-1
(which is the maximum value for a C long
) raises OverflowError
. Therefore the best way to create a range generator is to use itertools
:
xrange(2147483647+1) # OverflowError
from itertools import count, islice
count(1) # Count from 1 to infinity with step=+1
islice(count(1), 2147483648) # Count from 1 to 2^31 with step=+1
islice(count(1, 3), 2147483648) # Count from 1 to 3*2^31 with step=+3
You do not actually need to go all the way up to n
if you want to check if n
is a prime number. You can dramatically reduce the tests and only check from 2 to v(n)
(square root of n
). Here's an example:
Let's find all the divisors of n = 100
, and list them in a table:
2 x 50 = 100
4 x 25 = 100
5 x 20 = 100
10 x 10 = 100 <-- sqrt(100)
20 x 5 = 100
25 x 4 = 100
50 x 2 = 100
You will easily notice that, after the square root of n
, all the divisors we find were actually already found. For example 20
was already found doing 100/5
. The square root of a number is the exact mid-point where the divisors we found begin being duplicated. Therefore, to check if a number is prime, you'll only need to check from 2 to sqrt(n)
.
Why sqrt(n)-1
then, and not just sqrt(n)
? That's just because the second argument provided to itertools.islice()
is the number of iterations to execute. islice(count(a), b)
stops after b
iterations. That's the reason why:
for number in islice(count(10), 2):
print number,
# Will print: 10 11
for number in islice(count(1, 3), 10):
print number,
# Will print: 1 4 7 10 13 16 19 22 25 28
The function all(...)
is the same of the following:
def all(iterable):
for element in iterable:
if not element:
return False
return True
It literally checks for all the elements in the iterable
, returning False
when any of them evaluates to False
(which for an integer means only if it's zero). Why do we use it then? First of all, we don't need to use an additional index variable (like we would do using a loop), other than that: just for concision, there's no real need of it, but it looks way less bulky to work with only a single line of code instead of several nested lines.
I'm including an "unpacked" version of the is_prime()
function, to make it easier to understand and read:
from math import sqrt
from itertools import count, islice
def is_prime(n):
if n < 2:
return False
for number in islice(count(2), int(sqrt(n) - 1)):
if n % number == 0:
return False
return True
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
This works on Laravel 5:
{!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}
Use it ...
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)
DECLARE @uuid VARCHAR(50)
SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'
SELECT CAST(
SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
AS UNIQUEIDENTIFIER)
Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
The code you posted does not produce the error messages you quoted. You should provide a (small) example that actually exhibits the problem.
Generally, you can design a class that behaves like a dictionary, mainly be implementing the methods __contains__
, __getitem__
, __delitem__
, __setitem__
and some more. That class can have any behaviour you like, for example prividing a sorted iterator over the keys ...
You can use SimpleDateformat for change string to date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2000-01-01";
Date date = sdf.parse(strDate);
_x000D_
Put very simple ::
is the scoping operator, .
is the access operator (I forget what the actual name is?), and ->
is the dereference arrow.
::
- Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static
function.
.
- This allows access to a member function on an already created object. For instance, Foo x; x.bar()
calls the method bar()
on instantiated object x
which has type Foo
. You can also use this to access public class variables.
->
- Essentially the same thing as .
except this works on pointer types. In essence it dereferences the pointer, than calls .
. Using this is equivalent to (*ptr).method()
You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting
countByType.entrySet()
.stream()
.sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
.map(e -> e.getKey())
.collect(Collectors.toList());
The Python docs for hash()
state:
Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.
Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash()
is called on the keys that you pass in for assignment, or look-up.
Additionally, the docs for the dict
type state:
Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
For other users with the same problem. Here is a function i just made up.
It does NOT run on every mouse movement the user makes, or clears a timer every time the mouse moves.
<script>
// Timeout in seconds
var timeout = 10; // 10 seconds
// You don't have to change anything below this line, except maybe
// the alert('Welcome back!') :-)
// ----------------------------------------------------------------
var pos = '', prevpos = '', timer = 0, interval = timeout / 5 * 1000;
timeout = timeout * 1000 - interval;
function mouseHasMoved(e){
document.onmousemove = null;
prevpos = pos;
pos = e.pageX + '+' + e.pageY;
if(timer > timeout){
timer = 0;
alert('Welcome back!');
}
}
setInterval(function(){
if(pos == prevpos){
timer += interval;
}else{
timer = 0;
prevpos = pos;
}
document.onmousemove = function(e){
mouseHasMoved(e);
}
}, interval);
</script>
when you use lxml all simple:
tree = lxml.html.fromstring(html)
i_need_element = tree.xpath('//a[@class="shared-components"]/@href')
but when use BeautifulSoup BS4 all simple too:
try this magic:
soup = BeautifulSoup(html, "lxml")
i_need_element = soup.select ('a[class*="shared-components"]')
as you see, this does not support sub-tag, so i remove "/@href" part
This worked for me:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
I found this on https://css-tricks.com/snippets/php/change-month-number-to-month-name/ and it worked perfectly.
Need to remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath from environment and replace by JAVA_HOME which is works fine for me
This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.
You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.
As pointed out in comments, you cannot call cellForRowAtIndexPath
inside heightForRowAtIndexPath
.
What you can do is creating a template cell used to populate with your data and then compute its height. This cell doesn't participate to the table rendering, and it can be reused to calculate the height of each table cell.
Briefly, it consists of configuring the template cell with the data you want to display, make it resize accordingly to the content, and then read its height.
I have taken this code from a project I am working on - unfortunately it's in Objective C, I don't think you will have problems translating to swift
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
static PostCommentCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tblComments dequeueReusableCellWithIdentifier:POST_COMMENT_CELL_IDENTIFIER];
});
sizingCell.comment = self.comments[indexPath.row];
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
Check my code, I hope this helped you :)
public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)
{
int ab=0;
var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
var getFrames = gif.Frames;
BitmapFrame[] frames = getFrames.ToArray();
await Task.Run(() =>
{
while (ab < getFrames.Count())
{
Thread.Sleep(speed);
try
{
Dispatcher.Invoke(() =>
{
gifImage.Source = frames[ab];
});
if (ab == getFrames.Count - 1&&_Repeat)
{
ab = 0;
}
ab++;
}
catch
{
}
}
});
}
or
public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)
{
int ab = 0;
var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
var getFrames = gif.Frames;
BitmapFrame[] frames = getFrames.ToArray();
await Task.Run(() =>
{
while (ab < getFrames.Count())
{
Thread.Sleep(speed);
try
{
Dispatcher.Invoke(() =>
{
gifImage.Source = frames[ab];
});
if (ab == getFrames.Count - 1&&_Repeat)
{
ab = 0;
}
ab++;
}
catch{}
}
});
}
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
\r used for carriage return. (ASCII value is 13) \n used for new line. (ASCII value is 10)
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:
this.$scope.ticketsGrid = {
showColumn: jasmine.createSpy('showColumn'),
hideColumn: jasmine.createSpy('hideColumn'),
select: jasmine.createSpy('select'),
dataItem: jasmine.createSpy('dataItem'),
_data: []
}
It's a bit long winded but it works a treat
The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)
SELECT
*
FROM
< table_name >
WHERE
< date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)
AND NOW();
If using TextViews in tabs this selector definition worked for me (tried Klaus Balduino's but it did not):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active tab -->
<item
android:state_selected="true"
android:state_focused="false"
android:state_pressed="false"
android:color="#000000" />
<!-- Inactive tab -->
<item
android:state_selected="false"
android:state_focused="false"
android:state_pressed="false"
android:color="#FFFFFF" />
</selector>
Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.
For Ruby >=2.4.0 you can use sum
from Enumerables.
[1, 2, 3, 4].sum
It is dangerous to mokeypatch base classes. If you like danger and using an older version of Ruby, you could add #sum
to the Array
class:
class Array
def sum
inject(0) { |sum, x| sum + x }
end
end
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Yes, although Internet Explorer 9 will compile your Javascript on a separate thread in preparation for execution on the main thread. This doesn't change anything for you as a programmer, though.
To hide arrows and cross in a "time" input :
#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
-webkit-appearance: none;
margin: 0;
}
.widget-HomePageSlider .slider-loader-hide {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 10000;
background: white;
}
First: reload(sys)
and setting some random default encoding just regarding the need of an output terminal stream is bad practice. reload
often changes things in sys which have been put in place depending on the environment - e.g. sys.stdin/stdout streams, sys.excepthook, etc.
The best solution I know for solving the encode problem of print
'ing unicode strings and beyond-ascii str
's (e.g. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs:
When sys.stdout.encoding
is None
for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct .encoding
attribute. At last by replacing sys.stdout & sys.stderr
by a translating file-like object.
When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print
's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.
Here an example:
#!/usr/bin/env python
# encoding: utf-8
import sys
class SmartStdout:
def __init__(self, encoding=None, org_stdout=None):
if org_stdout is None:
org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)
self.org_stdout = org_stdout
self.encoding = encoding or \
getattr(org_stdout, 'encoding', None) or 'utf-8'
def write(self, s):
self.org_stdout.write(s.encode(self.encoding, 'backslashreplace'))
def __getattr__(self, name):
return getattr(self.org_stdout, name)
if __name__ == '__main__':
if sys.stdout.isatty():
sys.stdout = sys.stderr = SmartStdout()
us = u'aouäöü?zß²'
print us
sys.stdout.flush()
The only good reason to change the global default encoding (to UTF-8 only) I think is regarding an application source code decision - and not because of I/O stream encodings issues: For writing beyond-ascii string literals into code without being forced to always use u'string'
style unicode escaping. This can be done rather consistently (despite what anonbadger's article says) by taking care of a Python 2 or Python 2 + 3 source code basis which uses ascii or UTF-8 plain string literals consistently - as far as those strings potentially undergo silent unicode conversion and move between modules or potentially go to stdout. For that, prefer "# encoding: utf-8
" or ascii (no declaration). Change or drop libraries which still rely in a very dumb way fatally on ascii default encoding errors beyond chr #127 (which is rare today).
And do like this at application start (and/or via sitecustomize.py) in addition to the SmartStdout
scheme above - without using reload(sys)
:
...
def set_defaultencoding_globally(encoding='utf-8'):
assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding)
import imp
_sys_org = imp.load_dynamic('_sys_org', 'sys')
_sys_org.setdefaultencoding(encoding)
if __name__ == '__main__':
sys.stdout = sys.stderr = SmartStdout()
set_defaultencoding_globally('utf-8')
s = 'aouäöü?zß²'
print s
This way string literals and most operations (except character iteration) work comfortable without thinking about unicode conversion as if there would be Python3 only. File I/O of course always need special care regarding encodings - as it is in Python3.
Note: plains strings then are implicitely converted from utf-8 to unicode in SmartStdout
before being converted to the output stream enconding.
A bit verbose but this is how I do it:
@click="$emit('click', $event)"
UPDATE: Example added by @sparkyspider
<div-container @click="doSomething"></div-container>
In div-container
component...
<template>
<div @click="$emit('click', $event);">The inner div</div>
</template>
I have disabled Instant Run feature from the preferences and the issue was solved.
The syntax for accessing a dict given a key is number_map[int(x)]
. number_map(int(x))
would actually be a function call but since number_map
is not a callable, an exception is raised.
Decode to Unicode, encode the results to UTF8.
apple.decode('latin1').encode('utf8')
Another example using Deferred
s to implement a cache for any kind of computation (typically some performance-intensive or long-running tasks):
var ResultsCache = function(computationFunction, cacheKeyGenerator) {
this._cache = {};
this._computationFunction = computationFunction;
if (cacheKeyGenerator)
this._cacheKeyGenerator = cacheKeyGenerator;
};
ResultsCache.prototype.compute = function() {
// try to retrieve computation from cache
var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
var promise = this._cache[cacheKey];
// if not yet cached: start computation and store promise in cache
if (!promise) {
var deferred = $.Deferred();
promise = deferred.promise();
this._cache[cacheKey] = promise;
// perform the computation
var args = Array.prototype.slice.call(arguments);
args.push(deferred.resolve);
this._computationFunction.apply(null, args);
}
return promise;
};
// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
return Array.prototype.slice.call(arguments).join("|");
};
Here is an example of using this class to perform some (simulated heavy) calculation:
// The addingMachine will add two numbers
var addingMachine = new ResultsCache(function(a, b, resultHandler) {
console.log("Performing computation: adding " + a + " and " + b);
// simulate rather long calculation time by using a 1s timeout
setTimeout(function() {
var result = a + b;
resultHandler(result);
}, 1000);
});
addingMachine.compute(2, 4).then(function(result) {
console.log("result: " + result);
});
addingMachine.compute(1, 1).then(function(result) {
console.log("result: " + result);
});
// cached result will be used
addingMachine.compute(2, 4).then(function(result) {
console.log("result: " + result);
});
The same underlying cache could be used to cache Ajax requests:
var ajaxCache = new ResultsCache(function(id, resultHandler) {
console.log("Performing Ajax request for id '" + id + "'");
$.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
resultHandler(data.value);
});
});
ajaxCache.compute("anID").then(function(result) {
console.log("result: " + result);
});
ajaxCache.compute("anotherID").then(function(result) {
console.log("result: " + result);
});
// cached result will be used
ajaxCache.compute("anID").then(function(result) {
console.log("result: " + result);
});
You can play with the above code in this jsFiddle.
Sortest one...
select top 0 * into #temptable from mytable
Note : This creates an empty copy of temp, But it doesn't create a primary key
For Node.js there is Nodeclipse 0.2 with some bug fixes for chromedevtools
you need to JSON.stringify
the data parameter
before sending it.
You can define style rules which only apply to specific elements inside your div
with id divContainer
like this:
#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */
Do note that using the VisualTreeHelper does only work on controls that derive from Visual or Visual3D. If you also need to inspect other elements (e.g. TextBlock, FlowDocument etc.), using VisualTreeHelper will throw an exception.
Here's an alternative that falls back to the logical tree if necessary:
http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways
First thing, define a type or interface for your object, it will make things much more readable:
type Product = { productId: number; price: number; discount: number };
You used a tuple of size one instead of array, it should look like this:
let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
So now this works fine:
myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.
http://www.w3.org/TR/2009/WD-webstorage-20091222/
https://www.w3.org/TR/webstorage/. (second edition)
Here are some sample code for setting and getting the values using sessionStorage and localStorage :
// HTML5 session Storage
sessionStorage.setItem("variableName","test");
sessionStorage.getItem("variableName");
//HTML5 local storage
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
You can do this. Adapt it to your situation:
for l in Nlist:
for item in l:
print item
I had similar problem extracting certificates from a file. This might not be the most best way to do it but it worked for me.
openssl pkcs7 -inform DER -print_certs -in <path of the file> | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'
Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
Here are the simple steps to create a GitHub Tag, when you release build from master.
Open source_tree tab
Right click on Tag sections from Tag which appear on left navigation section
Click on New Tag()
Click on Add Tag from give name to tag (preferred version name of the code)
If you want to push the TAG on remote, while creating the TAG ref: step 5 which gives checkbox push TAG to origin check it and pushed tag appears on remote repository
In case while creating the TAG if you have forgotten to check the box Push to origin, you can do it later by right-clicking on the created TAG, click on Push to origin.
By default, the access modifier for a class is internal
. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.
** PHP >= 5.5
simply u can use this
$key = array_search(40489, array_column($userdb, 'uid'));
Let's suppose this multi dimensional array:
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
$key = array_search(40489, array_column($userdb, 'uid'));
You have various possibilies. The most simple and the most ugly is:
XAML
<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/>
Code Behind
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((YourClass)fe.DataContext).DoYourCommand();
}
Another solution (better) is to provide a ICommand-property on your YourClass
. This command will have already a reference to your YourClass
-object and therefore can execute an action on this class.
XAML
<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>
Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.
It means that a process or script you have created is sending mail to an account on your local machine (for example, a mail server running on localhost application).
Manage this mail with these commands:
t <message list> type messages
n goto and type next message
e <message list> edit messages
f <message list> give head lines of messages
d <message list> delete messages
s <message list> file append messages to file
u <message list> undelete messages
R <message list> reply to message senders
r <message list> reply to message senders and all recipients
pre <message list> make messages go back to /var/mail
m <user list> mail to specific users
q quit, saving unresolved messages in mbox
x quit, do not remove system mailbox
h print out active message headers
! shell escape
cd [directory] chdir to directory or home if none given
A consists of integers, ranges of same, or user names separated by spaces. If omitted, Mail uses the last message typed.
A consists of user names or aliases separated by spaces. Aliases are defined in .mailrc in your home directory.
Solution in Android Java:
Start your EditText, the ID is come to your xml id.
EditText myText = (EditText)findViewById(R.id.my_text_id);
in your OnCreate Method, just set the text by the name defined.
String text = "here put the text that you want"
use setText method from your editText.
myText.setText(text); //variable from point 2
Better yet:
for i in xa*; do
sed -i 's/asd/dfg/g' $i
done
because nobody knows how many files are there, and it's easy to break command line limits.
Here's what happens when there are too many files:
# grep -c aaa *
-bash: /bin/grep: Argument list too long
# for i in *; do grep -c aaa $i; done
0
... (output skipped)
#
I'm using this simple code for this task:
CSS Code
.demo {
background: tomato;
color: white;
}
Javascript code
function myFunction() {
/* Assign element to x variable by id */
var x = document.getElementById('para);
if (x.hasAttribute('class') {
x.removeAttribute('class');
} else {
x.setAttribute('class', 'demo');
}
}
in ARC (advanced rest client) - specify as below to make it work
Content-Type multipart/form-data
(this is header name and header value)
this allows you to add form data as key and values
you can specify you field name now as per your REST specification and select your file to upload from file selector.
I had this problem, this worked for me:
Install the postgresql-devel package, this will solve the issue of pg_config missing.
sudo apt-get install libpq-dev
It works for me:
=SUMPRODUCT(NOT(ISBLANK(F2:F)))
Count of all non-empty cells from F2 to the end of the column
You can use the excellent jquery-Json plugin:
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
Solution works very well,
public List<String> savePerson(@RequestBody Person[] personArray)
For this signature you can pass Person
array from postman like
[
{
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}, {
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}
]
Don't forget to add consumes
tag:
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public List<Employee> getEmployeeDataList(@RequestBody Employee[] employeearray) { ... }
There is a:not selector in css3. Use :not() with :last-child inside to select all children except last one. For example, to select all li in ul except last li, use following code.
ul li:not(:last-child){ }
As stated in dotnet CLI issue 6583 the issue should be solved with dotnet nuget locals --clear all
command.
According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts:
2.3.1. Debugging on the entire script
$ bash -x script1.sh
...
There is now a full-fledged debugger for Bash, available at SourceForge. These debugging features are available in most modern versions of Bash, starting from 3.x.
2.3.2. Debugging on part(s) of the script
set -x # Activate debugging from here w set +x # Stop debugging from here
...
Table 2-1. Overview of set debugging options
Short | Long notation | Result
-------+---------------+--------------------------------------------------------------
set -f | set -o noglob | Disable file name generation using metacharacters (globbing).
set -v | set -o verbose| Prints shell input lines as they are read.
set -x | set -o xtrace | Print command traces before executing command.
...
Alternatively, these modes can be specified in the script itself, by adding the desired options to the first line shell declaration. Options can be combined, as is usually the case with UNIX commands:
#!/bin/bash -xv
Use toArray(T[] a) method:
String[] array = set.toArray(new String[0]);
To add to Kevin's answer, I find that in practice nearly all of your non-trivial Spring MVC applications will require an application context (as opposed to only the spring MVC dispatcher servlet context). It is in the application context that you should configure all non-web related concerns such as:
To make this a bit more concrete, here's an example of the Spring configuration I've used when setting up a modern (Spring version 4.1.2) Spring MVC application. Personally, I prefer to still use a WEB-INF/web.xml
file but that's really the only xml configuration in sight.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.company.config.WebConfig</param-value>
</init-param>
</servlet>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.company.config.AppConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
</web-app>
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.company.controller")
public class WebConfig {
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
@Configuration
@ComponentScan(basePackages = "com.company")
@Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class})
public class AppConfig {
// application domain @Beans here...
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private LdapUserDetailsMapper ldapUserDetailsMapper;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/js/**").permitAll()
.antMatchers("/**/images/**").permitAll()
.antMatchers("/**").access("hasRole('ROLE_ADMIN')")
.and().formLogin();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchBase("OU=App Users")
.userSearchFilter("sAMAccountName={0}")
.groupSearchBase("OU=Development")
.groupSearchFilter("member={0}")
.userDetailsContextMapper(ldapUserDetailsMapper)
.contextSource(getLdapContextSource());
}
private LdapContextSource getLdapContextSource() {
LdapContextSource cs = new LdapContextSource();
cs.setUrl("ldaps://ldapServer:636");
cs.setBase("DC=COMPANY,DC=COM");
cs.setUserDn("CN=administrator,CN=Users,DC=COMPANY,DC=COM");
cs.setPassword("password");
cs.afterPropertiesSet();
return cs;
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(transactionManagerRef = "getTransactionManager", entityManagerFactoryRef = "getEntityManagerFactory", basePackages = "com.company")
public class PersistenceConfig {
@Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
lef.setPackagesToScan("com.company");
return lef;
}
private HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabase(Database.ORACLE);
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(false);
return hibernateJpaVendorAdapter;
}
@Bean
public JndiObjectFactoryBean getDataSource() {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("java:comp/env/jdbc/AppDS");
return jndiFactoryBean;
}
@Bean
public JpaTransactionManager getTransactionManager(DataSource dataSource) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(getEntityManagerFactory(dataSource).getObject());
jpaTransactionManager.setDataSource(dataSource);
return jpaTransactionManager;
}
}
@Configuration
@EnableScheduling
public class ScheduleConfig {
@Autowired
private EmployeeSynchronizer employeeSynchronizer;
// cron pattern: sec, min, hr, day-of-month, month, day-of-week, year (optional)
@Scheduled(cron="0 0 0 * * *")
public void employeeSync() {
employeeSynchronizer.syncEmployees();
}
}
As you can see, the web configuration is only a small part of the overall spring web application configuration. Most web applications I've worked with have many concerns that lie outside of the dispatcher servlet configuration that require a full-blown application context bootstrapped via the org.springframework.web.context.ContextLoaderListener
in the web.xml
.
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
One way of finding all data attributes is using element.attributes
. Using .attributes
, you can loop through all of the element attributes, filtering out the items which include the string "data-".
let element = document.getElementById("element");
function getDataAttributes(element){
let elementAttributes = {},
i = 0;
while(i < element.attributes.length){
if(element.attributes[i].name.includes("data-")){
elementAttributes[element.attributes[i].name] = element.attributes[i].value
}
i++;
}
return elementAttributes;
}
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
With a .rdl, .rdlc or similar file selected, you can either:
Don't bother with open/readdir and use glob
instead:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
I'm not sure what you're going for here--by the time jQuery(document).ready()
has executed, it has already loaded, and thus document
's load event will already have been called. Attaching the load
event handler at this point will have no effect and it will never be called. If you're attempting to alert
"started" once the document has loaded, just put it right in the (document).ready()
call, like this:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
alert('started');
});?
If, as your code also appears to insinuate, you want to fire the alert when .abc
has loaded, put it in an individual .load
handler:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
$(".abc").on("load", function() {
alert('started');
}
});?
Finally, I see little point in using jQuery
in one place and $
in another. It's generally better to keep your code consistent, and either use jQuery
everywhere or $
everywhere, as the two are generally interchangeable.