HTML:
<input type="text" id="address" name="address" value=""> //Autocomplete input address
<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
Javascript:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');
var originAutocomplete = new google.maps.places.Autocomplete(input);
originAutocomplete.addListener('place_changed', function(event) {
var place = originAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
originLatitude.value = place.geometry.location.lat();
originLongitude.value = place.geometry.location.lng();
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
originLatitude.value = results[0].geometry.location.lat();
originLongitude.value = results[0].geometry.location.lng();
}
});
}
});
</script>
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
autocomplete="off"
on the input now working on Chrome V44 (and Canary V47)
<input type="password" placeholder="Enter Password" class="form-control" autocomplete="new-password">
Here you go.
When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:
# finds all .java files starting in current directory
find . -print | grep '\.java'
#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'
Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
I use this script for autocomplete...
$('#custmoers_name').autocomplete({
source: function (request, response) {
// $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
$.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
console.log(data);
response($.map(data, function (value, key) {
console.log(value);
return {
label: value.label,
value: value.value
};
}));
});
},
minLength: 1,
delay: 100
});
My json return :- [{"label":"Mahesh Arun Wani","value":"1"}]
after search m
but it display in dropdown [object object]
...
Select2 for Bootstrap 3 native plugin
https://fk.github.io/select2-bootstrap-css/index.html
this plugin uses select2 jquery plugin
nuget
PM> Install-Package Select2-Bootstrap
Did someone mention code_complete?
But you did not like ctags, so this is probably not what you are looking for...
If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
Basically same as the accepted answer, but updated with new type and multiple country restrictions:
function initialize() {
var options = {
types: ['(regions)'],
componentRestrictions: {country: ["us", "de"]}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
Using '(regions)'
instead of '(cities)'
allows to search by postal code as well as city name.
See official documentation, Table 3: https://developers.google.com/places/supported_types
or you can add the AutoCompleteBox into the toolbox by clicking on it and then Choose Items, go to WPF Components, type in the filter AutoCompleteBox, which is on the System.Windows.Controls namespace and the just drag into your xaml file. This is way much easier than doing these other stuff, since the AutoCompleteBox is a native control.
If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.
To have a transparent background while not using a time delay (especially needed in modern web applications where people can stop using it for a while and want a predictable behavior of the interface), use this:
input:-webkit-autofill {
-webkit-background-clip: text;
}
body {
background: lightblue;
}
input {
background: transparent;
}
input.no-autofill-bkg:-webkit-autofill {
-webkit-background-clip: text;
}
_x000D_
<input type="text" name="email" />
<input type="text" name="email" class="no-autofill-bkg" />
_x000D_
Working on: Chrome 83 / 84.0.4147.89, Edge 84.0.522.44
If you decide to re-post my solution, I only ask that you include my name or link to this.
I've came up with the following solution that queries all fields with the attribute autocomple="off"
then set it's value to a single space then set a timer for around 200ms and set the value back to an empty string.
Example:
// hack to prevent auto fill on chrome
var noFill = document.querySelectorAll("input[autocomplete=off]");
noFill.forEach(function(el) {
el.setAttribute("value", " ");
setTimeout(function() {
el.setAttribute("value", "");
}, 200);
});
I choose 200ms for the timer because after some experimentation 200ms seems to be the amount of time it takes on my computer for chrome to give up on trying to autocomplete the fields. I'm welcome to hear what other times seem to work better for other people.
If the results come from a mysql query, it is more efficient to limit directly the mysql result:
select [...] from [...] order by [...] limit 0,10
where 10 is the max numbers of rows you want
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
private void TurnOnAutocomplete()
{
textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
string[] arrayOfWowrds = new string[];
try
{
//Read in data Autocomplete list to a string[]
string[] arrayOfWowrds = new string[];
}
catch (Exception err)
{
MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
collection.AddRange(arrayOFWords);
textBox.AutoCompleteCustomSource = collection;
}
You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.
This worked for me like a charm.
<form autocomplete="off"> <input type="text" autocomplete="off" style="display:none"> </form>
Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.
In a script LearnerNameTypeAhead.coffee
(convertible of course to JS) I have:
$ ->
learners = new Bloodhound(
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
queryTokenizer: Bloodhound.tokenizers.whitespace
remote: "/learner/namelike?nameLikeStr=%QUERY"
)
learners.initialize()
$("#firstName").typeahead
minLength: 3
hint: true
highlight:true
,
name: "learners"
displayKey: "value"
source: learners.ttAdapter()
I included the typeahead bundle and my script on the page, and there is a div
around my input field as follows:
<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
<input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>
The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr=
plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:
[ {
"id": "109",
"value": "Graham Jones"
},
{
"id": "5833",
"value": "Hezekiah Jones"
} ]
For play I need something in the routes file:
GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)
And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head>
(or accessible .css)
.tt-dropdown-menu {
width: 252px;
margin-top: 12px;
padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
background-color: #fff;
}
.typeahead:focus {
border: 2px solid #0097cf;
}
.tt-query {
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
color: #999
}
.tt-suggestion {
padding: 3px 20px;
font-size: 18px;
line-height: 24px;
}
.tt-suggestion.tt-cursor {
color: #fff;
background-color: #0097cf;
}
.tt-suggestion p {
margin: 0;
}
For my case, my another team member included another version of jquery.js when he add in bootstrap.min.js. After remove the extra jquery.js, the problem is solved
All the answers were missing Ctrl-J (which enables and disables autocomplete).
JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters
HTML:
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
Javascript:
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});
This works great for me and I'm doing more, writing less with jQuery's example modified.
I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.
$(function() {
var mySource = [];
$("#mySelect").children("option").map(function() {
mySource.push($(this).text());
});
$("#myInput").autocomplete({
source: mySource,
minLength: 3
});
}
For Objects
try this:
function sortBy(field) {
return function(a, b) {
if (a[field] > b[field]) {
return -1;
} else if (a[field] < b[field]) {
return 1;
}
return 0;
};
}
The link provided by Mark no longer works, but you can go to:
Notpad++ 6.6.9
I find it very annoying though, since a big autocomplete block is always coming up and I would just like to see autocomplete when I press tab or a key combination. I am fairly new to Notepad++ though. If you know of such a key combination, please feel free to reply. I found this question via Google, so we can always help others.
last time I checked Google updated their autofill in JAN 2017, the solution that worked for me was adding another input and hiding it after it has been populated.
<input type="text" id="phone_number" name="phone_number" value="">
<input type="text" id="dummy_autocomplete">
<script type="text/javascript">
$('#dummy_autocomplete').hide();
</script>
This post is pretty old, but for thoses who got here in 2016. None of the example here worked for me. Using keyup
instead of autocompletechange
did the job. Using jquery-ui 10.4
$("#CompanyList").on("keyup", function (event, ui) {
console.log($(this).val());
});
Hope this help!
Working Solution that listens to if the user has started to navigate down the list with the keyboard rather than triggering the false navigation each time
https://codepen.io/callam/pen/RgzxZB
Here are the important bits
// search input
const searchInput = document.getElementById('js-search-input');
// Google Maps autocomplete
const autocomplete = new google.maps.places.Autocomplete(searchInput);
// Has user pressed the down key to navigate autocomplete options?
let hasDownBeenPressed = false;
// Listener outside to stop nested loop returning odd results
searchInput.addEventListener('keydown', (e) => {
if (e.keyCode === 40) {
hasDownBeenPressed = true;
}
});
// GoogleMaps API custom eventlistener method
google.maps.event.addDomListener(searchInput, 'keydown', (e) => {
// Maps API e.stopPropagation();
e.cancelBubble = true;
// If enter key, or tab key
if (e.keyCode === 13 || e.keyCode === 9) {
// If user isn't navigating using arrows and this hasn't ran yet
if (!hasDownBeenPressed && !e.hasRanOnce) {
google.maps.event.trigger(e.target, 'keydown', {
keyCode: 40,
hasRanOnce: true,
});
}
}
});
// Clear the input on focus, reset hasDownBeenPressed
searchInput.addEventListener('focus', () => {
hasDownBeenPressed = false;
searchInput.value = '';
});
// place_changed GoogleMaps listener when we do submit
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// Get the place info from the autocomplete Api
const place = autocomplete.getPlace();
//If we can find the place lets go to it
if (typeof place.address_components !== 'undefined') {
// reset hasDownBeenPressed in case they don't unfocus
hasDownBeenPressed = false;
}
});
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:
//I like min length set to 3, to not give too many options
//after the first character or two the user types
public Int32 AutoCompleteMinLength {get; set;}
private void HandleTextChanged() {
var txt = comboBox.Text;
if (txt.Length < AutoCompleteMinLength)
return;
//The GetMatches method can be whatever you need to filter
//table rows or some other data source based on the typed text.
var matches = GetMatches(comboBox.Text.ToUpper());
if (matches.Count() > 0) {
//The inside of this if block has been changed to allow
//users to continue typing after the auto-complete results
//are found.
comboBox.Items.Clear();
comboBox.Items.AddRange(matches);
comboBox.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox.Select(txt.Length, 0);
return;
}
else {
comboBox.DroppedDown = false;
comboBox.SelectionStart = txt.Length;
}
}
hope this helps someone:
$('#id')
.autocomplete({
source: hints_array,
minLength: 0, //how many chars to start search for
position: { my: "left bottom", at: "left top", collision: "flip" } // so that it automatically flips the autocomplete above the input if at the bottom
})
.focus(function() {
$(this).autocomplete('search', $(this).val()) //auto trigger the search with whatever's in the box
})
The real problem is much deeper than just adding attributes to your HTML - this is common security concern, that's why people invented hardware keys and other crazy things for security.
Imagine you have autocomplete="off" perfectly working in all browsers. Would that help with security? Of course, no. Users will write down their passwords in textbooks, on stickers attached to their monitor where every office visitor can see them, save them to text files on the desktop and so on.
Generally, web application and web developer isn't responsible in any way for end-user security. End-users can protect themselves only. Ideally, they MUST keep all passwords in their head and use password reset functionality (or contact administrator) in case they forgot it. Otherwise there always will be a risk that password can be seen and stolen somehow.
So either you have some crazy security policy with hardware keys (like, some banks offer for Internet-banking which basically employs two-factor authentication) or NO SECURITY basically. Well, this is a bit over exaggerated of course. It's important to understand what are you trying to protect against:
In this particular post, I can see inadequate requirements put on developer which he will never be able to resolve due to the nature of the problem - end-user security. My subjective point is that developer should basically say NO and point on requirement problem rather than wasting time on such tasks, honestly. This does not absolutely make your system more secure, it will rather lead to the cases with stickers on monitors. Unfortunately, some bosses hear only what they want to hear. However, if I was you I would try to explain where the actual problem is coming from, and that autocomplete="off" would not resolve it unless it will force users to keep all their passwords exclusively in their head! Developer on his end cannot protect users completely, users need to know how to use system and at the same time do not expose their sensitive/secure information and this goes far beyond authentication.
In order of activity, demos/examples available, and simplicity:
Related:
I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.
Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete
So basically you have to return a promise
when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $q
service/directive/controller where you issue your HTTP Request.
Example:
function getMyHttpData(){
var deferred = $q.defer();
$http.jsonp(request).success(function(data){
// the promise gets resolved with the data from HTTP
deferred.resolve(data);
});
// return the promise
return deferred.promise;
}
I hope this helps.
On Servlet 3.0 or newer you could just specify
<web-app ...>
<error-page>
<location>/general-error.html</location>
</error-page>
</web-app>
But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.
<error-page>
<!-- Missing login -->
<error-code>401</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Forbidden directory listing -->
<error-code>403</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Missing resource -->
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
<error-page>
<!-- Uncaught exception -->
<error-code>500</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Unsupported servlet method -->
<error-code>503</error-code>
<location>/general-error.html</location>
</error-page>
That should cover the most common ones.
The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
If MySql is running on the same computer as your webserver, you can just use "localhost" as the host
For narrowing the type of the property, simple extend
works perfect, as in Nitzan's answer:
interface A {
x: string | number;
}
interface B extends A {
x: number;
}
For widening, or generally overriding the type, you can do Zskycat's solution:
interface A {
x: string
}
export type B = Omit<A, 'x'> & { x: number };
But, if your interface A
is extending a general interface, you will lose the custom types of A
's remaining properties when using Omit
.
e.g.
interface A extends Record<string | number, number | string | boolean> {
x: string;
y: boolean;
}
export type B = Omit<A, 'x'> & { x: number };
let b: B = { x: 2, y: "hi" }; // no error on b.y!
The reason is, Omit
internally only goes over Exclude<keyof A, 'x'>
keys which will be the general string | number
in our case. So, B
would become {x: number; }
and accepts any extra property with the type of number | string | boolean
.
To fix that, I came up with a different OverrideProps
utility type as following:
type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };
Example:
type OverrideProps<M, N> = { [P in keyof M]: P extends keyof N ? N[P] : M[P] };
interface A extends Record<string | number, number | string | boolean> {
x: string;
y: boolean;
}
export type B = OverrideProps<A, { x: number }>;
let b: B = { x: 2, y: "hi" }; // error: b.y should be boolean!
make sure ,use this 404 route wrote on the bottom of the code.
syntax will be like
{
path: 'page-not-found',
component: PagenotfoundComponent
},
{
path: '**',
redirectTo: '/page-not-found'
},
Thank you
Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
Even better, how about OnPause():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code here
not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.
This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
While there is still some truth to most of the answers above, I think they deserve an update:
Over the years the performance of SVG has improved a lot and now there is hardware-accelerated CSS transitions and animations for SVG that do not depend on JavaScript performance at all. Of course JavaScript performance has improved, too and with it the performance of Canvas, but not as much as SVG got improved. Also there is a "new kid" on the block that is available in almost all browsers today and that is WebGL. To use the same words that Simon used above: It beats both Canvas and SVG hands down. This doesn't mean it should be the go-to technology, though, since it's a beast to work with and it is only faster in very specific use-cases.
IMHO for most use-cases today, SVG gives the best performance/usability ratio. Visualizations need to be really complex (with respect to number of elements) and really simple at the same time (per element) so that Canvas and even more so WebGL really shine.
In this answer to a similar question I am providing more details, why I think that the combination of all three technologies sometimes is the best option you have.
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
You can pass an ArrayList<E>
the same way, if the E
type is Serializable
.
You would call the putExtra (String name, Serializable value)
of Intent
to store, and getSerializableExtra (String name)
for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
Inside public folder create an assets folder and place image path accordingly.
<img className="img-fluid"
src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`}
alt="logo"/>
I had the same problem after upgrading to Xcode 5.1 and fixed it by setting Architectures to armv7 armv7s
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
I followed this procedure to get ride of a similar/same error.
mvn idea:clean
mvn idea:idea
After that I could build both from the IDE intellij and from command line.
Why it can be good to store pictures in the database an not in a catalog on the web server.
You have made an application with lots of pictures stored in a folder on the server, that the client has used for years.
Now they come to you. They server has been destroyed and they need to restore it on a new server. They have no access to the old server anymore. The only backup they have is the database backup.
You have of course the source and can simple deploy it to the new server, install SqlServer and restore the database. But now all the pictures are gone.
If you have saved the pictures in SqlServer everything will work as before.
Just my 2 cents.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
I suspect Steven A. Lowe's rolled up newspaper therapy is required for the designer of the original data structure.
As an aside, GUIDs as a primary key can be a performance hog. I wouldn't recommend it.
Some C++ algorithms are faster than C, and some implementations of algorithms or design patterns in other languages can be faster than C.
When people say that C is fast, and then move on to talking about some other language, they are generally using C's performance as a benchmark.
An answer using css flex layout and justify-content
p {
display: flex;
justify-content: space-between;
}
_x000D_
<p>
<span>This text is left aligned</span>
<span>This text is right aligned</span>
</p>
_x000D_
//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is @myItem.i and a value is @myItem.value.Name</li>
}
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
A easy way to install pyodbc is by using 'conda'. As conda automatically installs required dependencies including unixodbc.
conda --ugrade all
(optional)
then
conda install pyodbc
it will install following packages:
libgfortran-ng: 7.2.0-hdf63c60_3 defaults
mkl: 2018.0.3-1 defaults
mkl_fft: 1.0.2-py36_0 conda-forge
mkl_random: 1.0.1-py36_0 conda-forge
numpy-base: 1.14.5-py36hdbf6ddf_0 defaults
pyodbc: 4.0.17-py36_0 conda-forge
unixodbc: 2.3.4-1 conda-forge
It exists, but it's hard to search for. I think most people call it the "splat" operator.
It's in the documentation as "Unpacking argument lists".
You'd use it like this: foo(*values)
. There's also one for dictionaries:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)
But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:
Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified
by POSIX.)
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
Just put a pair of double quotes around your file name like this:
this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");
You can use css and the :hover pseudo-property. Here is a simple demo. It uses the following css:
a span.tooltip {display:none;}
a:hover span.tooltip {position:absolute;top:30px;left:20px;display:inline;border:2px solid green;}
Note that older browsers have limited support for :hover.
Just click on form and go to JFrame properties, then Code tab and check Generate Center
.
This is also found in the UINavigationController class documentation:
navigationItem.hidesBackButton = true
I use something like this in my document.ready
var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device
$("#container").width(width+"px");
$("#container").height(height+"px");
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
There is Firebug Lite which gives a lot of Firebug functionality in IE.
FYI you dont have string datatype in C. Use array of characters to store the value and manipulate it. Change your variable c into an array of characters and use it inside a loop to get values.
char c[10];
int i=0;
while(i!=10)
{
c[i]=fgetc(fp);
i++;
}
The other way to do is to use pointers and allocate memory dynamically and assign values.
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
If you don't like Math.round() you can use this simple approach as well:
int a = (int) (doubleVar + 0.5);
When you use php CLI argument -q doesn't exist.
I had the same problem when I wrote script in the Windows (eclipse) and I tried run them on Linux. Every line in file from Windows is ended by \r\n. I had to delete \r in first line that contained parser path:
When \r was deleted from first line (mcedit shown \r as ^M) script ran correctly.
Referencing Qwerty's answer, you can avoid to inflate XL size by re-using cellStyle
.
And when the type is CELL_TYPE_BLANK
, getStringCellValue
returns ""
instead of null
.
private static void copyRow(Sheet worksheet, int sourceRowNum, int destinationRowNum) {
// Get the source / new row
Row newRow = worksheet.getRow(destinationRowNum);
Row sourceRow = worksheet.getRow(sourceRowNum);
// If the row exist in destination, push down all rows by 1 else create a new row
if (newRow != null) {
worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
} else {
newRow = worksheet.createRow(destinationRowNum);
}
// Loop through source columns to add to new row
for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
// Grab a copy of the old/new cell
Cell oldCell = sourceRow.getCell(i);
Cell newCell = newRow.createCell(i);
// If the old cell is null jump to next cell
if (oldCell == null) {
newCell = null;
continue;
}
// Use old cell style
newCell.setCellStyle(oldCell.getCellStyle());
// If there is a cell comment, copy
if (newCell.getCellComment() != null) {
newCell.setCellComment(oldCell.getCellComment());
}
// If there is a cell hyperlink, copy
if (oldCell.getHyperlink() != null) {
newCell.setHyperlink(oldCell.getHyperlink());
}
// Set the cell data type
newCell.setCellType(oldCell.getCellType());
// Set the cell data value
switch (oldCell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getRichStringCellValue());
break;
}
}
}
**A problem occurred evaluating project ':app'.
Could not resolve all files for configuration 'classpath'.**
Solution: Platform->cordova-support-google-services
In this file Replace classpath 'com.android.tools.build:gradle:+' to this classpath 'com.android.tools.build:gradle:3.+'
Set IFS to newline, like this:
IFS='
'
for x in `ls -l $1`; do echo $x; done
Put a sub-shell around it if you don't want to set IFS permanently:
(IFS='
'
for x in `ls -l $1`; do echo $x; done)
Or use while | read instead:
ls -l $1 | while read x; do echo $x; done
One more option, which runs the while/read at the same shell level:
while read x; do echo $x; done << EOF
$(ls -l $1)
EOF
You can use these kind of programs to emulate an apache web server and run PHP on your computer:
To get the iframe to always load fresh content, add the current Unix timestamp to the end of the GET parameters. The browser then sees it as a 'different' request and will seek new content.
In Javascript, it might look like:
frames['my_iframe'].location.href='load_iframe_content.php?group_ID=' + group_ID + '×tamp=' + timestamp;
Use:
setTimeout(startTimer,startInterval);
You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().
If you would like a software tool to do this, you might like to check out this step-by-step guide:
"How to Validate and Import Excel spreadsheet to SQL Server database"
window.onload = function() {
... etc. is not a great answer.
This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.
A more robust answer here:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Some code I have been using, I forget where I found it to give the author credit.
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
Hope this helps :)
string.Substring(0,n); // 0 - start index and n - number of characters
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
You could also set the default format for float :
pd.options.display.float_format = '{:.2%}'.format
Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)
Your PersonSheets has a property int Id
, Id
isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .
In a system I am developing, the string to be replaced by sed is input text from a user which is stored in a variable and passed to sed.
As noted earlier on this post, if the string contained within the sed command block contains the actual delimiter used by sed - then sed terminates on syntax error. Consider the following example:
This works:
$ VALUE=12345
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345
This breaks:
$ VALUE=12345/6
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
sed: -e expression #1, char 21: unknown option to `s'
Replacing the default delimiter is not a robust solution in my case as I did not want to limit the user from entering specific characters used by sed as the delimiter (e.g. "/").
However, escaping any occurrences of the delimiter in the input string would solve the problem. Consider the below solution of systematically escaping the delimiter character in the input string before having it parsed by sed. Such escaping can be implemented as a replacement using sed itself, this replacement is safe even if the input string contains the delimiter - this is since the input string is not part of the sed command block:
$ VALUE=$(echo ${VALUE} | sed -e "s#/#\\\/#g")
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345/6
I have converted this to a function to be used by various scripts:
escapeForwardSlashes() {
# Validate parameters
if [ -z "$1" ]
then
echo -e "Error - no parameter specified!"
return 1
fi
# Perform replacement
echo ${1} | sed -e "s#/#\\\/#g"
return 0
}
SELECT DISTINCT Contract, Activity
FROM Contract WHERE Contract IN (
SELECT Contract
FROM Contract
GROUP BY Contract
HAVING COUNT( DISTINCT Activity ) = 1 )
If you are comfortable with Visual Studio environment,
Small project: jGRASP with gcc Large project: Cocotron
I heard there are emulators, but I could find only Apple II Emulator http://virtualapple.org/. It looks like limited to games.
As supplementary, like @Pointy said
The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere).
It's supposed to add System.loadLibrary("I_am_native_library")
into static block.
static{
System.loadLibrary("I_am_a_library");
}
It will guarantee no native method be called before the related library is loaded into memory.
According to loadLibrary from oracle:
If this method is called more than once with the same library name, the second and subsequent calls are ignored.
So quite unexpectedly, putting System.loadLibrary is not used to avoid library be loaded multi-times.
There is only one way from what I am aware.
Have 2 images, first a jpeg with first frame(or whatever you want) of the gif and the actual gif.
Load the page with the jpeg in place and on mouse over replace the jpeg with the gif. You can preload the gifs if you want or if they are of big size show a loading while the gif is loading and then replace the jpeg with it.
If you whant it to bi linear as in have the gif play on mouse over, stop it on mouse out and then resume play from the frame you stopped, then this cannot be done with javascript+gif combo.
Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).
The code: Print the last name of the person only if the middle name is less than four characters.
func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
guard let Name = name.last where name.middle?.characters.count < 4 else {
print("Hi there)")
return
}
print("Hey \(Name)!")
}
Until I declared last as an optional parameter I was seeing the same error.
You can use Google S2 Converter.
http://www.google.com/s2/favicons?domain=google.com
Source: http://www.labnol.org/internet/get-favicon-image-of-websites-with-google/4404/
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.
This is one way to do it (in Python 3.x):
escaped = a_string.translate(str.maketrans({"-": r"\-",
"]": r"\]",
"\\": r"\\",
"^": r"\^",
"$": r"\$",
"*": r"\*",
".": r"\."}))
For reference, for escaping strings to use in regex:
import re
escaped = re.escape(a_string)
This can happens when:
e.g. something like this happened:
$ cd submodule
$ emacs my_source_file # edit some file(s)
$ git commit -am "Making some changes but will forget to push!"
Should have submodule pushed at this point.
$ cd .. # back to parent repository
$ git commit -am "updates to parent repository"
$ git push origin master
As a result, the missing commits could not possibly be found by the remote user because they are still on the local disk.
Informa the person who modified the submodule to push, i.e.
$ cd submodule
$ git push
The refresh_token
is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh_token
again. :)
refresh_token
(providing that it also includes the 'access_type=offline' query parameter.Alternatively, you can add the query parameters prompt=consent&access_type=offline
to the OAuth redirect (see Google's OAuth 2.0 for Web Server Applications page).
This will prompt the user to authorize the application again and will always return a refresh_token
.
function setToggleInputsinPnl(pnlName) {
var domCount = pnlName.length;
for (var i = 0; i < domCount; i++) {
if (pnlName[i].type == 'text') {
pnlName[i].value = '';
} else if (pnlName[i].type == 'select-one') {
pnlName[i].value = '';
}
}
}
This is what I was looking for here:
declare -A hashmap
hashmap["key"]="value"
hashmap["key2"]="value2"
echo "${hashmap["key"]}"
for key in ${!hashmap[@]}; do echo $key; done
for value in ${hashmap[@]}; do echo $value; done
echo hashmap has ${#hashmap[@]} elements
This did not work for me with bash 4.1.5:
animals=( ["moo"]="cow" )
Try using template and document.importNode. Here is an example:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Sample</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1 id="hello_world">Sample</h1>_x000D_
<script type="text/javascript">_x000D_
var div = document.createElement("div");_x000D_
var t = document.createElement('template');_x000D_
t.innerHTML = "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";_x000D_
_x000D_
for (var i=0; i < t.content.childNodes.length; i++){_x000D_
var node = document.importNode(t.content.childNodes[i], true);_x000D_
div.appendChild(node);_x000D_
}_x000D_
document.body.appendChild(div);_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The answer marked here suggests using HttpClient directly and the disposing of it. This might work, but it's quite easy to run in to problems with HttpClient if you don't use it correctly.
If you're going to use HttpClient, you're better off handing over the creation/disposal of HttpClients to a third-party library that uses the factory pattern. RestClient.Net is one such library.
It comes with a very basic HttpClient factory so that you don't run in to the socket exhaustion problem,
public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
#region Fields
private bool disposed;
private readonly ConcurrentDictionary<string, Lazy<HttpClient>> _httpClients;
private readonly Func<string, Lazy<HttpClient>> _createClientFunc;
#endregion
#region Constructor
public DefaultHttpClientFactory() : this(null)
{
}
public DefaultHttpClientFactory(Func<string, Lazy<HttpClient>> createClientFunc)
{
_createClientFunc = createClientFunc;
_httpClients = new ConcurrentDictionary<string, Lazy<HttpClient>>();
if (_createClientFunc != null) return;
_createClientFunc = name =>
{
return new Lazy<HttpClient>(() => new HttpClient(), LazyThreadSafetyMode.ExecutionAndPublication);
};
}
#endregion
#region Implementation
public HttpClient CreateClient(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return _httpClients.GetOrAdd(name, _createClientFunc).Value;
}
public void Dispose()
{
if (disposed) return;
disposed = true;
foreach (var name in _httpClients.Keys)
{
_httpClients[name].Value.Dispose();
}
}
#endregion
}
But Microsoft's IHttpClientFactory implementation can also be used for the latest and greatest:
var serviceCollection = new ServiceCollection();
var baseUri = new Uri("http://www.test.com");
serviceCollection.AddSingleton(typeof(ISerializationAdapter), typeof(NewtonsoftSerializationAdapter));
serviceCollection.AddSingleton(typeof(ILogger), typeof(ConsoleLogger));
serviceCollection.AddSingleton(typeof(IClient), typeof(Client));
serviceCollection.AddDependencyInjectionMapping();
serviceCollection.AddTransient<TestHandler>();
//Make sure the HttpClient is named the same as the Rest Client
serviceCollection.AddSingleton<IClient>(x => new Client(name: clientName, httpClientFactory: x.GetRequiredService<IHttpClientFactory>()));
serviceCollection.AddHttpClient(clientName, (c) => { c.BaseAddress = baseUri; })
.AddHttpMessageHandler<TestHandler>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var client = serviceProvider.GetService<IClient>();
await client.GetAsync<object>();
RestClient.Net takes in to account dependency injection, mocking, IoC containers, unit testability, and above all is fast. I've hunted around and the only the other client that seems to work in a similar capacity is Flurl.Http.
I have got similar pep8 warning W291 trailing whitespace
long_text = '''Lorem Ipsum is simply dummy text <-remove whitespace
of the printing and typesetting industry.'''
Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.
<VirtualHost 64.65.66.67>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 64.65.66.67>
ServerAdmin [email protected]
ServerName www.example.com
DocumentRoot /var/www/example
.
.
. etc
So, the separate VirtualHost
for "example.com" captures those requests and then permanently redirects them to your main VirtualHost
. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.
Note, the trailing slash in Redirect permanent / http://www.example.com/
.
Without it, a redirect from example.com/asdf
would redirect to http://www.example.comasdf
instead of http://www.example.com/asdf
.
Try this:
$('.datepicker').datepicker('update', new Date(year,month,day));
With C++11 and std::chrono::high_resolution_clock
you can do this:
#include <iostream>
#include <chrono>
#include <thread>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
std::chrono::milliseconds three_milliseconds{3};
auto t1 = Clock::now();
std::this_thread::sleep_for(three_milliseconds);
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
<< " milliseconds" << std::endl;
}
Output:
Delta t2-t1: 3 milliseconds
Link to demo: http://cpp.sh/2zdtu
Basically here we are dealing with communication between Fragments. Communication between fragments can never be directly possible. It involves activity under the context of which both the fragments are created.
You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.
There is no difference between these two declarations, and both have the same performance.
We can summarize by using summarize_at
, summarize_all
and summarize_if
on dplyr 0.7.4
. We can set the multiple columns and functions by using vars
and funs
argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4
, summarise_each
(and mutate_each
) is already deprecated, so we cannot use these functions.
options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)
library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’
set.seed(123)
df <- data_frame(
a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)
df %>% group_by(grp) %>%
summarise_each(.vars = letters[1:4],
.funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean
You should change to the following code. The following codes all have the same result.
# summarise_at
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = names(.)[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = vars(a,b,c,d),
.funs = c(mean="mean"))
# summarise_all
df %>% group_by(grp) %>%
summarise_all(.funs = c(mean="mean"))
# summarise_if
df %>% group_by(grp) %>%
summarise_if(.predicate = function(x) is.numeric(x),
.funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 3.6 3.00
# 2 2 4.25 2.75 4.0 3.75
# 3 3 3.00 5.00 1.0 2.00
You can also have multiple functions.
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:2],
.funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean a_Sd b_Sd
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 1.4832397 1.870829
# 2 2 4.25 2.75 0.9574271 1.258306
# 3 3 3.00 5.00 NA NA
try
{
DataTable sheet1 = new DataTable("Excel Sheet");
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = @"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
This worked for me. Please try it and let me know for queries.
There is no "convention" that requires table names to be singular.
For example, we had a table called "REJECTS" on a db used by a rating process, containing the records rejected from one run of the program, and I don't see any reason in not using plural for that table (naming it "REJECT" would have been just funny, or too optimistic).
About the other problem (quotes) it depends on the SQL dialect. Oracle doesn't require quotes around table names.
Unfortunately for you this is "something fancy". Normally it's not the web authors place to redesign form elements. Many browsers purposely don't let you style them, in order for the user to see the OS controls they are used to.
The only way to do this consistently over browsers and operating systems, is use JavaScript and replace the select
elements with "DHTML" ones.
Following article show three jQuery based plugins that allow you to do that (it is a bit old, but I couldn't find anything current right now)
http://www.queness.com/post/204/25-jquery-plugins-that-enhance-and-beautify-html-form-elements#1
For Windows. Run these commands in Git Bash:
git config --global diff.tool meld
git config --global difftool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global difftool.prompt false
git config --global merge.tool meld
git config --global mergetool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global mergetool.prompt false
(Update the file path for Meld.exe if yours is different.)
For Linux. Run these commands in Git Bash:
git config --global diff.tool meld
git config --global difftool.meld.path "/usr/bin/meld"
git config --global difftool.prompt false
git config --global merge.tool meld
git config --global mergetool.meld.path "/usr/bin/meld"
git config --global mergetool.prompt false
You can verify Meld's path using this command:
which meld
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n
string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe";
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();
clients.get
will return a ClientThread
and not a String
, and it will bomb with an IndexOutOfBoundsException
if it would compile as Java is zero based for indexing.
Similarly I think you should call remove
on the clients
list.
ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
I would use the stack functions of a LinkedList
in this case though.
ClientThread hey = clients.removeLast()
instead of using object.getClass().getName()
you can use object.getClass().getSimpleName()
, because it returns a simple class name without a package name included.
for instance,
Object[] intArray = { 1 };
for (Object object : intArray) {
System.out.println(object.getClass().getName());
System.out.println(object.getClass().getSimpleName());
}
gives,
java.lang.Integer
Integer
If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex
instance method. Such as
int index = list.FindIndex(f => f.Bar == 17);
Where f => f.Bar == 17
is a predicate with the matching criteria.
In your case you might write
int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0)
{
// element exists, do what you need
}
One option is to make two plots side by side. ggplot2
provides a nice option for this with facet_wrap()
:
dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
, y = c(rnorm(100), rlnorm(100, 9, 2))
, index = rep(1:2, each = 100)
)
require(ggplot2)
ggplot(dat, aes(x,y)) +
geom_point() +
facet_wrap(~ index, scales = "free_y")
In Chrome Canary now you can limit the network throughput. This can be done in the "Network" options of the "Emulation" tab of the Console in the Dev Tools.
You might need to activate the Chrome flag "Enable Developer Tools experiments" (chrome://flags/#enable-devtools-experiments) (chrome://flags) to see this new feature. You can simulate some low bandwidth (GSM, GPRS, EDGE, 3G) for mobile connections.
Yes a correct sign()
function should be at least in the math module - as it is in numpy. Because one frequently needs it for math oriented code.
But math.copysign()
is also useful independently.
cmp()
and obj.__cmp__()
... have generally high importance independently. Not just for math oriented code. Consider comparing/sorting tuples, date objects, ...
The dev arguments at http://bugs.python.org/issue1640 regarding the omission of math.sign()
are odd, because:
-NaN
sign(nan) == nan
without worry (like exp(nan)
)sign(-0.0) == sign(0.0) == 0
without worrysign(-inf) == -1
without worry-- as it is in numpy
The error message is pretty self-explanatory: your application needs the Oracle Client installed on the machine it's running on. Your development PC already has it. Make sure your target PC has it, too.
Edit: The System.Data.OracleClient namespace is deprecated. Make sure you use the driver native to your database system, that would be ODP.NET from Oracle.
Here is creating a ComboBox adding a listener for item selection change:
JComboBox comboBox = new JComboBox();
comboBox.setBounds(84, 45, 150, 20);
contentPane.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
contentPane.add(comboBox_1);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
//Do Something
}
});
Thanks for sharing.
By reading all the solutions. I came up with a solution that uses the url hash or localStorage depending on the availability of the latter with below code:
$(function(){
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
})
var hash = window.location.hash;
var activeTab = localStorage.getItem('activeTab');
if(hash){
$('#project-tabs a[href="' + hash + '"]').tab('show');
}else if (activeTab){
$('#project-tabs a[href="' + activeTab + '"]').tab('show');
}
});
Best general purpose - Especially short arrays (1000 items or less) and coders that are unsure of what optimizations best suit their needs.
# $value can be any regex. be safe
if ( grep( /^$value$/, @array ) ) {
print "found it";
}
It has been mentioned that grep passes through all values even if the first value in the array matches. This is true, however grep is still extremely fast for most cases. If you're talking about short arrays (less than 1000 items) then most algorithms are going to be pretty fast anyway. If you're talking about very long arrays (1,000,000 items) grep is acceptably quick regardless of whether the item is the first or the middle or last in the array.
Optimization Cases for longer arrays:
If your array is sorted, use a "binary search".
If the same array is repeatedly searched many times, copy it into a hash first and then check the hash. If memory is a concern, then move each item from the array into the hash. More memory efficient but destroys the original array.
If same values are searched repeatedly within the array, lazily build a cache. (as each item is searched, first check if the search result was stored in a persisted hash. if the search result is not found in the hash, then search the array and put the result in the persisted hash so that next time we'll find it in the hash and skip the search).
Note: these optimizations will only be faster when dealing with long arrays. Don't over optimize.
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myName%'
Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.
This question makes me nervous. It indicates that maybe you don't understand how using server-side code will impact you're page's DOM state.
Whenever you run server-side code the entire page is rebuilt from scratch. This has several implications:
If you can get away with it, you might want to push this down to javascript and avoid the postback. Perhaps use an XmlHttpRequest() call to trigger any server-side action you need.
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
The following JavaScript could work:
var page = $doc.getElementsByTagName('body')[0];
To disable Scroll use:
page.classList.add('noscroll');
To enable Scroll use:
page.classList.remove('noscroll');
In the CSS file, add:
.noscroll {
position: fixed!important
}
var clist = document.getElementsByTagName("input");
for (var i = 0; i < clist.length; ++i) { clist[i].checked = false; }
$('input:checkbox').each(function() { this.checked = false; });
To do opposite, see: Select All Checkboxes By ID/Class
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.
opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check Apache Portable Runtime
Thanks @gniourf_gniourf for detailed comments on my combination of best worlds so far. Sorry for posting code not thoroughly designed and tested. Here is a better try.
# join with separator
join_ws() { local d=$1 s=$2; shift 2 && printf %s "$s${@/#/$d}"; }
This beauty by conception is
Additional examples:
$ join_ws '' a b c
abc
$ join_ws ':' {1,7}{A..C}
1A:1B:1C:7A:7B:7C
$ join_ws -e -e
-e
$ join_ws $'\033[F' $'\n\n\n' 1. 2. 3. $'\n\n\n\n'
3.
2.
1.
$ join_ws $
$
If you are using form data to upload file,in which a parameter name must be specified , you can use:
curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx
import java.io.PrintWriter;
import java.io.StringWriter;
public class PrintStackTrace {
public static void main(String[] args) {
try {
int division = 0 / 0;
} catch (ArithmeticException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
System.out.println(exceptionAsString);
}
}
}
When you run the program, the output will be something similar:
java.lang.ArithmeticException: / by zero
at PrintStackTrace.main(PrintStackTrace.java:9)
This is the best thing I've found so far - shows you the symlinks in the current directory, recursively, but without following them, displayed with full paths and other information:
find ./ -type l -print0 | xargs -0 ls -plah
outputs looks about like this:
lrwxrwxrwx 1 apache develop 99 Dec 5 12:49 ./dir/dir2/symlink1 -> /dir3/symlinkTarget
lrwxrwxrwx 1 apache develop 81 Jan 10 14:02 ./dir1/dir2/dir4/symlink2 -> /dir5/whatever/symlink2Target
etc...
If you need something quick, datetime_object.date()
gives you a date of a datetime object.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.
Basic Steps to Debug a Procedure in Toad
Reference:Toad Debugger
Or you can just use this:
<?
function TestHtml() {
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->
<? } ?>
to get content from this function , use this :
<?= file_get_contents(TestHtml()); ?>
That's it :)
If your input is a character and the characters you are checking against are mostly consecutive you could try this:
if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
// ...
}
However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:
if (symbol.matches("[A-Z?]")) {
// ...
}
If you have a character you'll first need to convert it to a string before you can use a regular expression:
if (Character.toString(symbol).matches("[A-Z?]")) {
// ...
}
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
On my newer EC2 instance, simply adding the new value to the Jenkins user's .profile's PATH and then restarting tomcat worked for me.
On an older instance where the config is different, using #2 from Sagar's answer was the only thing that worked (i.e. .profile, .bash* didn't work).
If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.
Add $scope.$broadcast("variable_name_here");
after the desired external resource or long running controller/directive has completed.
Then add the below after your external resource has loaded.
$scope.$on("variable_name_here", function(){
// DOM manipulation here
jQuery('selector').height();
}
For example in the promise of a deferred HTTP request.
MyHttpService.then(function(data){
$scope.MyHttpReturnedImage = data.image;
$scope.$broadcast("imageLoaded");
});
$scope.$on("imageLoaded", function(){
jQuery('img').height(80).width(80);
}
I just got done doing this exact thing in a project. The HTML side looked a bit like this:
<a href="[fullsize]" class="gallerypic" title="">
<img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
<span class="zoom-icon">
<img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
</span>
</a>
Then using CSS:
a.gallerypic{
width:140px;
text-decoration:none;
position:relative;
display:block;
border:1px solid #666;
padding:3px;
margin-right:5px;
float:left;
}
a.gallerypic span.zoom-icon{
visibility:hidden;
position:absolute;
left:40%;
top:35%;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
a.gallerypic:hover span.zoom-icon{
visibility:visible;
}
I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.
Hope this helps.
EDIT: To clarify for your example - you could ignore the visibility:hidden;
and kill the :hover
execution if you wanted, this was just the way I did it.
For anyone who wants to loop through all query strings from a string
foreach (var item in new Uri(urlString).Query.TrimStart('?').Split('&'))
{
var subStrings = item.Split('=');
var key = subStrings[0];
var value = subStrings[1];
// do something with values
}
If you can't REINDEX a workaround is to use aliases. From the official documentation:
APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.
Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560
This class does the trick. You can add new prefixes to the _prefixes static string array.
public static class StringExtensions
{
public static string ToProperCase( this string original )
{
if( String.IsNullOrEmpty( original ) )
return original;
string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
return result;
}
public static string WordToProperCase( this string word )
{
if( String.IsNullOrEmpty( word ) )
return word;
if( word.Length > 1 )
return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );
return word.ToUpper( CultureInfo.CurrentCulture );
}
private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
private static readonly string[] _prefixes = {
"mc"
};
private static string HandleWord( Match m )
{
string word = m.Groups[1].Value;
foreach( string prefix in _prefixes )
{
if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
}
return word.WordToProperCase();
}
}
You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.
var x = somePossiblyNullValue ?? valueIfNull;
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
A summary.lm
object stores these values in a matrix
called 'coefficients'
. So the value you are after can be accessed with:
a2Pval <- summary(mg)$coefficients[2, 4]
Or, more generally/readably, coef(summary(mg))["a2","Pr(>|t|)"]
. See here for why this method is preferred.
They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.
How are you setting up the SqlParameter
? You should set the SqlDbType
property to SqlDbType.DateTime
and then pass the DateTime
directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).
You should be able to get the value into the DB. If not, here is a very simple example of how to do it:
static void Main(string[] args)
{
// Create the connection.
using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
{
// Open the connection.
connection.Open();
// Create the command.
using (SqlCommand command = new SqlCommand("xsp_Test", connection))
{
// Set the command type.
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add the parameter.
SqlParameter parameter = command.Parameters.Add("@dt",
System.Data.SqlDbType.DateTime);
// Set the value.
parameter.Value = DateTime.Now;
// Make the call.
command.ExecuteNonQuery();
}
}
}
I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.
If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime
, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime
struct will easily do).
All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime
method, not by converting to a string) to the stored procedure.
And when you get the value back, call the ToLocalTime
method to get the time in the local time zone.
system_profiler SPUSBDataType
it your need command on macos
I solved this problem very simply using a little hack in the adapter. Here is my code:
public class MyPagerAdapter extends FragmentStatePagerAdapter
{
public static int LOOPS_COUNT = 1000;
private ArrayList<Product> mProducts;
public MyPagerAdapter(FragmentManager manager, ArrayList<Product> products)
{
super(manager);
mProducts = products;
}
@Override
public Fragment getItem(int position)
{
if (mProducts != null && mProducts.size() > 0)
{
position = position % mProducts.size(); // use modulo for infinite cycling
return MyFragment.newInstance(mProducts.get(position));
}
else
{
return MyFragment.newInstance(null);
}
}
@Override
public int getCount()
{
if (mProducts != null && mProducts.size() > 0)
{
return mProducts.size()*LOOPS_COUNT; // simulate infinite by big number of products
}
else
{
return 1;
}
}
}
And then, in the ViewPager, we set current page to the middle:
mAdapter = new MyPagerAdapter(getSupportFragmentManager(), mProducts);
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(mViewPager.getChildCount() * MyPagerAdapter.LOOPS_COUNT / 2, false); // set current item in the adapter to middle
Best way is to wrap the Image and Paragraph text with a DIV and assign a class.
<div class="image1">
<div class="imgWrapper">
<img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
<p>It's my first Image</p>
</div>
...
...
...
...
</div>
This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.
Some possible alternatives:
Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.
Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If your Dialog is creating on the adapter:
Pass the Activity to the Adapter Constructor:
adapter = new MyAdapter(getActivity(),data);
Receive on the Adapter:
public MyAdapter(Activity activity, List<Data> dataList){
this.activity = activity;
}
Now you can use on your Builder
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
Same holds true for this discussion as well.
It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
The difference is that Any is an extension method for any IEnumerable<T>
defined on System.Linq.Enumerable. It can be used on any IEnumerable<T>
instance.
Exists does not appear to be an extension method. My guess is that coll is of type List<T>
. If so Exists is an instance method which functions very similar to Any.
In short, the methods are essentially the same. One is more general than the other.
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
xCode just copy all crashes logs. If you want to speed-up: delete number of crash reports after you analyze it, directly in this window.
Devices -> View Device Logs -> All Logs
I had the same problem after I upgraded my macOS
to version 10.13.6
. I can't run composer
and php
commands. After researching for a while and trying various solutions posted online, reinstalling php using homebrew
worked.
brew reinstall [email protected]
Added on March 14th based on Ryan's comment
get the version you are currently using by running php -v
and get the right formulae (which you can find here: https://formulae.brew.sh/formula/php) to replace @7.1
in the above command.
I've been looking into this myself and can't find a strong difference between the two. I think the big choice is in which implementation you use. For myself I've been considering the DataNucleus platform as it is a data-store agnostic implementation of both.
In this line:
const char* cstr2 = ss.str().c_str();
ss.str()
will make a copy of the contents of the stringstream. When you call c_str()
on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char*
to point to unowned memory.
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
Although I am commenting late. But I have used this method to do the job. Here when I am running my spring application I am providing the application yaml file via -Dspring.config.location=file:/location-to-file/config-server-vault-application.yml
which contains all of my properties
config-server-vault-application.yml
***********************************
server:
port: 8888
ssl:
trust-store: /trust-store/config-server-trust-store.jks
trust-store-password: config-server
trust-store-type: pkcs12
************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) throws IOException {
setUpTrustStoreForApplication();
SpringApplication.run(ConfigServerApplication.class, args);
}
private static void setUpTrustStoreForApplication() throws IOException {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
List<PropertySource<?>> applicationYamlPropertySource = loader.load(
"config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
}
}
It's not enough to install the certificate itself, instead you need to install the root certificate of your certification authority. Say if you use Win Server's Certificate Services, its root certificate which was created when CS was installed on that server is the one to be installed. It must be installed to the "Trusted Root Certification Authorities" as described earlier.
window.onload = function() {
var el = document.documentElement,
rfs = el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen;
rfs.call(el);
};
The above answers will position the inner element at the top of the overflow element even if it's in view inside the overflow element. I didn't want that so I modified it to not change the scroll position if the element is in view.
jQuery.fn.scrollTo = function(elem, speed) {
var $this = jQuery(this);
var $this_top = $this.offset().top;
var $this_bottom = $this_top + $this.height();
var $elem = jQuery(elem);
var $elem_top = $elem.offset().top;
var $elem_bottom = $elem_top + $elem.height();
if ($elem_top > $this_top && $elem_bottom < $this_bottom) {
// in view so don't do anything
return;
}
var new_scroll_top;
if ($elem_top < $this_top) {
new_scroll_top = {scrollTop: $this.scrollTop() - $this_top + $elem_top};
} else {
new_scroll_top = {scrollTop: $elem_bottom - $this_bottom + $this.scrollTop()};
}
$this.animate(new_scroll_top, speed === undefined ? 100 : speed);
return this;
};
LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".
Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row. Reading it again you just want that rows culled, so you should an inner join rather than a left join.
Update:
Newer versions of Sql Server also have the LAG and LEAD Windowing functions that can be used for this, too.
Google Firebase is Google's latest(2016) way to provide you with crash/error data on your phone. Include it in your build.gradle file :
compile 'com.google.firebase:firebase-crash:9.0.0'
Fatal crashes are logged automatically without requiring user input and you can also log non-fatal crashes or other events like so :
try
{
}
catch(Exception ex)
{
FirebaseCrash.report(new Exception(ex.toString()));
}
Any crawler or spider will read your index.htm
or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm
or equivalent file, it will not list all the files in such folder.
If by mistake, the programmer never included an index.htm
file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/
and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.
Except, of course, if they can enter your FTP or access your site control panel.
Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:
package main
import (
"os"
"bufio"
"bytes"
"io"
"fmt"
"strings"
)
// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
func writeLines(lines []string, path string) (err error) {
var (
file *os.File
)
if file, err = os.Create(path); err != nil {
return
}
defer file.Close()
//writer := bufio.NewWriter(file)
for _,item := range lines {
//fmt.Println(item)
_, err := file.WriteString(strings.TrimSpace(item) + "\n");
//file.Write([]byte(item));
if err != nil {
//fmt.Println("debug")
fmt.Println(err)
break
}
}
/*content := strings.Join(lines, "\n")
_, err = writer.WriteString(content)*/
return
}
func main() {
lines, err := readLines("foo.txt")
if err != nil {
fmt.Println("Error: %s\n", err)
return
}
for _, line := range lines {
fmt.Println(line)
}
//array := []string{"7.0", "8.5", "9.1"}
err = writeLines(lines, "foo2.txt")
fmt.Println(err)
}
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
I wrote my own export to Excel writer because nothing else quite met my needs. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
dict = {}
for i in set(str):
b = str.count(i, 0, len(str))
dict[i] = b
print dict
If my string is:
str = "this is string!"
Above code will print:
{'!': 1, ' ': 2, 'g': 1, 'i': 3, 'h': 1, 'n': 1, 's': 3, 'r': 1, 't': 2}
You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head()
is called, holding the template URL. Like:
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):
Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
PUT /testIndex
{
"mappings": {
"properties": { <--ADD THIS
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
},
"settings": {
bla
bla
bla
}
}
Here's a similar command I know works:
curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex
The breakdown for the above curl command is:
PUT /manzanaIndex
{
"mappings":{
"properties":{
"city":{
"type": "text"
}
}
}
}
If you're looking to build a GUI interface to trace an IP address, I would recommend VB.
But if you insist on sticking with Python, TkInter and wxPython are the best choices.
This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool
function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.
.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):
Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.
It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:
>>> import csv >>> >>> >>> limit0 = csv.field_size_limit() >>> limit0 131072 >>> "0x{0:016X}".format(limit0) '0x0000000000020000'
However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).
Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:
When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):
>>> import sys, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('win32', 9223372036854775807, 64, 32) >>> >>> csv.field_size_limit(sys.maxsize) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: Python int too large to convert to C long
To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 2147483647 >>> "0x{0:016X}".format(limit1) '0x000000007FFFFFFF'
64bit Python on a Nix like OS:
>>> import sys, csv, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('linux', 9223372036854775807, 64, 64) >>> >>> csv.field_size_limit() 131072 >>> >>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 9223372036854775807 >>> "0x{0:016X}".format(limit1) '0x7FFFFFFFFFFFFFFF'
For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.
Check the following resources for more details on:
There is a easiest way to create .Pem file if you have already apns p12 file in your key chain access.
Open terminal and enter the below command:
For Devlopment openssl pkcs12 -in apns-div-cert.p12 -out apns-div-cert.pem -nodes -clcerts
For Production openssl pkcs12 -in apns-dist-cert.p12 -out apns-dist-cert.pem -nodes -clcerts
Rename your P12 file with this name : apns-div-cert.p12 otherwise instead of this you need to enter your filename. Thanks!!
A slight variation on the indexOf
method, if you need to filter multiple arrays:
function unique(item, index, array) {
return array.indexOf(item) == index;
}
Use as such:
arr.filter(unique);
If you are on Windows, try this:
"C:\Program Files\RStudio\bin\rstudio.exe" http_proxy=http://host:port/
Just a small adittion to @johnharris85's great answer,
when you are running a docker compose file, a "default
" network is created
so you can just add it to the other compose file as an external network:
# front/docker-compose.yml
version: '2'
services:
front_service:
...
...
# api/docker-compose.yml
version: '2'
services:
api_service:
...
networks:
- front_default
networks:
front_default:
external: true
For me this approach was more suited because I did not own the first docker-compose file and wanted to communicate with it.
strcat(str1, str2)
appends str2 after str1. It requires str1 to have enough space to hold str2. In you code, str1 and str2 are all string constants, so it should not work. You may try this way:
char str1[1024];
char *str2 = "kkkk";
strcpy(str1, "ssssss");
strcat(str1, str2);
printf("%s", str1);
run psql -E
and then \d student_details
From MSDN:
Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0–59.
SQL uses a different system than C# for DateTime values.
You can use your MinValue as a sentinel value - and if it is MinValue - pass null into your object (and store the date as nullable in the DB).
if(date == dateTime.Minvalue)
objinfo.BirthDate = null;
I think you make a bare repository on the remote side, git init --bare
, add the remote side as the push/pull tracker for your local repository (git remote add origin URL
), and then locally you just say git push origin master
. Now any other repository can pull
from the remote repository.
First of all, input
element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden
).
Second thing, you need the after()
, not append()
function.
Really simple answer in bootstrap 4, change this
<row>
...
</row>
to this
<row justify-content-center>
...
</row>
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
Actually, there is a way. You just need to copy DeviceSupport folder for iOS 7.1 from Older Xcode to the new one. It's located in:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1
If you don't have the 7.1 files anymore, you can download a previous version of XCode on https://developer.apple.com/download/more/, extract it, and then copy these files to following path
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
Broken pipe means you wrote to a connection that is already closed by the other end.
isConnected()
does not detect this condition. Only a write does.
is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()
It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.
public bool ValueExists(RegistryKey Key, string Value)
{
try
{
return Key.GetValue(Value) != null;
}
catch
{
return false;
}
}
This simple function will return true only if a value is found but it is not null, else will return false if the value exists but it is null or the value doesn't exists in the key.
USAGE for your question:
if (ValueExists(winLogonKey, "Start")
{
// The values exists
}
else
{
// The values does not exists
}
hr {_x000D_
display: block;_x000D_
height: 1px;_x000D_
border: 0;_x000D_
border-top: 1px solid #ccc;_x000D_
margin: 1em 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
Here is how html5boilerplate does it:
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
Use the background-size attribute in CSS3:
.class {
background-image: url(bg.gif);
background-size: 100%;
}
EDIT: Modernizr supports detection of background-size support. You can use a JavaScript workaround written to work however you need it and load it dynamically when there is no support. This will keep the code maintainable without resorting to intrusive CSS hacks for certain browsers.
Personally I use a script to deal with it using jQuery, its an adaption of imgsizer. As most designs I do now use width %'s for fluid layouts across devices there is a slight adaptation to one of the loops (accounting for sizes that aren't always 100%):
for (var i = 0; i < images.length; i++) {
var image = images[i],
width = String(image.currentStyle.width);
if (width.indexOf('%') == -1) {
continue;
}
image.origWidth = image.offsetWidth;
image.origHeight = image.offsetHeight;
imgCache.push(image);
c.ieAlpha(image);
image.style.width = width;
}
EDIT: You may also be interested in jQuery CSS3 Finaliz[s]e.
Using plain javascript:
element.parentNode
In jQuery:
element.parent()
I think modifying a "selected text" in a RichTextBox isn't the right way to add colored text. So here a method to add a "color block" :
Run run = new Run("This is my text");
run.Foreground = new SolidColorBrush(Colors.Red); // My Color
Paragraph paragraph = new Paragraph(run);
MyRichTextBlock.Document.Blocks.Add(paragraph);
From MSDN :
The Blocks property is the content property of RichTextBox. It is a collection of Paragraph elements. Content in each Paragraph element can contain the following elements:
Inline
InlineUIContainer
Run
Span
Bold
Hyperlink
Italic
Underline
LineBreak
So I think you have to split your string depending on parts color, and create as many Run
objects as needed.
The simplest way of doing this would be to add
include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib
The modern CMake version that doesn't add the -I and -L
flags to every compiler invocation would be to use imported libraries:
add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)
set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path
If setting the INTERFACE_INCLUDE_DIRECTORIES
doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include)
. However, this no longer works with CMake 3.6 or newer.
With a class & AudioToolbox:
import AudioToolbox
class Sound {
var soundEffect: SystemSoundID = 0
init(name: String, type: String) {
let path = NSBundle.mainBundle().pathForResource(name, ofType: type)!
let pathURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
}
func play() {
AudioServicesPlaySystemSound(soundEffect)
}
}
Usage:
testSound = Sound(name: "test", type: "caf")
testSound.play()
C++20 std::format
options <
, ^
and >
According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:
// left: "42 "
std::cout << std::format("{:<6}", 42);
// right: " 42"
std::cout << std::format("{:>6}", 42);
// center: " 42 "
std::cout << std::format("{:^6}", 42);
More information at: std::string formatting like sprintf
Some time ago I wrote a format_date
function as this gives many options on how you want your date:
function format_date($date, $type, $seperator="-")
{
if($date)
{
$day = date("j", strtotime($date));
$month = date("n", strtotime($date));
$year = date("Y", strtotime($date));
$hour = date("H", strtotime($date));
$min = date("i", strtotime($date));
$sec = date("s", strtotime($date));
switch($type)
{
case 0: $date = date("Y".$seperator."m".$seperator."d",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 1: $date = date("D, F j, Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 2: $date = date("d".$seperator."m".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 3: $date = date("d".$seperator."M".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 4: $date = date("d".$seperator."M".$seperator."Y h:i A",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 5: $date = date("m".$seperator."d".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 6: $date = date("M",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 7: $date = date("Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 8: $date = date("j",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 9: $date = date("n",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 10:
$diff = abs(strtotime($date) - strtotime(date("Y-m-d h:i:s")));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$date = $years . " years, " . $months . " months, " . $days . "days";
}
}
return($date);
}
...and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.
Thank you guys! :-)
Basically the error was because I was using old version of aws-sdk and I updated the version so this error occured.
in my case with node js i was using signatureVersion
in parmas object like this :
const AWS_S3 = new AWS.S3({
params: {
Bucket: process.env.AWS_S3_BUCKET,
signatureVersion: 'v4',
region: process.env.AWS_S3_REGION
}
});
Then I put signature out of params object and worked like charm :
const AWS_S3 = new AWS.S3({
params: {
Bucket: process.env.AWS_S3_BUCKET,
region: process.env.AWS_S3_REGION
},
signatureVersion: 'v4'
});
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
start all daemons and run the command as "hadoop namenode -recover -force" stop the daemons and start again.. wait some time to recover data.
If you are using windows there is something different sort of situation
First open c:/apache24/conf/httpd.conf
.
The Apache folder is enough not specifically above path
After that you have to configure httpd.conf file.
Just after few lines there is pattern like:
#Listen _____________:80
Listen 80
Here You have to change for the localhost
.
You have to enter ipv4 address for that you can open localhost.
Refer this video link and after that just bit more.
Change your environment variables:
In which you have to enter path:
c:apache24/bin
and
same in the SYSTEM variables
If any query feel free to ask.
IPv6
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()
IPv4
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
I'd rather initialize inside the constructor so I don't need to keep the order.
Scale can be used for both full data frame and specific columns. For specific columns, following code can be used:
trainingSet[, 3:7] = scale(trainingSet[, 3:7]) # For column 3 to 7
trainingSet[, 8] = scale(trainingSet[, 8]) # For column 8
Full data frame
trainingSet <- scale(trainingSet)
Why wouldn't this be possible?
var theNameOfTheVar = (TheType)null;
eg:
var name = (string)null;
Simple as that.
I had an issue with connected repository. What's how I fixed:
I deleted manually .git folder under my project folder, run git init and then it all worked.
Have a blank full-screen scene
Add a scroll view. Control-drag from the scroll view to the base view, add left-right-top-bottom, all zero.
Add a stack view in the scroll view. Control-drag from the stack view to the scroll view, add left-right-top-bottom, all zero.
Put two or three labels inside the stack view.
For clarity, make the background color of the label red. Set the label height to 100.
Now set the width of each UILabel:
Surprisingly, control-drag from the UILabel
to the scroll view, not to the stack view, and select equal widths.
To repeat:
It's that simple. That's the secret.
Secret tip - Apple bug:
It will not work with only one item! Add a few labels to make the demo work.
You're done.
Tip: You must add a height to every new item. Every item in any scrolling stack view must have either an intrinsic size (such as a label) or add an explicit height constraint.
The alternative approach:
In the above: surprisingly, set the widths of the UILabels to the width of the scroll view (not the stack view).
Alternately...
So you have two options:
or
To be clear, do ONE of those methods, do NOT do both.
With jQuery, I've done it this way:
function checkKey(e){
switch (e.keyCode) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keypress (checkKey);
} else {
$(document).keydown (checkKey);
}
Also, try these plugins, which looks like they do all that work for you:
http://www.openjs.com/scripts/events/keyboard_shortcuts
http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
The goal here is to use ADL to do customization of how we pretty print.
You pass in a formatter tag, and override 4 functions (before, after, between and descend) in the tag's namespace. This changes how the formatter prints 'adornments' when iterating over containers.
A default formatter that does {(a->b),(c->d)}
for maps, (a,b,c)
for tupleoids, "hello"
for strings, [x,y,z]
for everything else included.
It should "just work" with 3rd party iterable types (and treat them like "everything else").
If you want custom adornments for your 3rd party iterables, simply create your own tag. It will take a bit of work to handle map descent (you need to overload pretty_print_descend( your_tag
to return pretty_print::decorator::map_magic_tag<your_tag>
). Maybe there is a cleaner way to do this, not sure.
A little library to detect iterability, and tuple-ness:
namespace details {
using std::begin; using std::end;
template<class T, class=void>
struct is_iterable_test:std::false_type{};
template<class T>
struct is_iterable_test<T,
decltype((void)(
(void)(begin(std::declval<T>())==end(std::declval<T>()))
, ((void)(std::next(begin(std::declval<T>()))))
, ((void)(*begin(std::declval<T>())))
, 1
))
>:std::true_type{};
template<class T>struct is_tupleoid:std::false_type{};
template<class...Ts>struct is_tupleoid<std::tuple<Ts...>>:std::true_type{};
template<class...Ts>struct is_tupleoid<std::pair<Ts...>>:std::true_type{};
// template<class T, size_t N>struct is_tupleoid<std::array<T,N>>:std::true_type{}; // complete, but problematic
}
template<class T>struct is_iterable:details::is_iterable_test<std::decay_t<T>>{};
template<class T, std::size_t N>struct is_iterable<T(&)[N]>:std::true_type{}; // bypass decay
template<class T>struct is_tupleoid:details::is_tupleoid<std::decay_t<T>>{};
template<class T>struct is_visitable:std::integral_constant<bool, is_iterable<T>{}||is_tupleoid<T>{}> {};
A library that lets us visit the contents of an iterable or tuple type object:
template<class C, class F>
std::enable_if_t<is_iterable<C>{}> visit_first(C&& c, F&& f) {
using std::begin; using std::end;
auto&& b = begin(c);
auto&& e = end(c);
if (b==e)
return;
std::forward<F>(f)(*b);
}
template<class C, class F>
std::enable_if_t<is_iterable<C>{}> visit_all_but_first(C&& c, F&& f) {
using std::begin; using std::end;
auto it = begin(c);
auto&& e = end(c);
if (it==e)
return;
it = std::next(it);
for( ; it!=e; it = std::next(it) ) {
f(*it);
}
}
namespace details {
template<class Tup, class F>
void visit_first( std::index_sequence<>, Tup&&, F&& ) {}
template<size_t... Is, class Tup, class F>
void visit_first( std::index_sequence<0,Is...>, Tup&& tup, F&& f ) {
std::forward<F>(f)( std::get<0>( std::forward<Tup>(tup) ) );
}
template<class Tup, class F>
void visit_all_but_first( std::index_sequence<>, Tup&&, F&& ) {}
template<size_t... Is,class Tup, class F>
void visit_all_but_first( std::index_sequence<0,Is...>, Tup&& tup, F&& f ) {
int unused[] = {0,((void)(
f( std::get<Is>(std::forward<Tup>(tup)) )
),0)...};
(void)(unused);
}
}
template<class Tup, class F>
std::enable_if_t<is_tupleoid<Tup>{}> visit_first(Tup&& tup, F&& f) {
details::visit_first( std::make_index_sequence< std::tuple_size<std::decay_t<Tup>>{} >{}, std::forward<Tup>(tup), std::forward<F>(f) );
}
template<class Tup, class F>
std::enable_if_t<is_tupleoid<Tup>{}> visit_all_but_first(Tup&& tup, F&& f) {
details::visit_all_but_first( std::make_index_sequence< std::tuple_size<std::decay_t<Tup>>{} >{}, std::forward<Tup>(tup), std::forward<F>(f) );
}
A pretty printing library:
namespace pretty_print {
namespace decorator {
struct default_tag {};
template<class Old>
struct map_magic_tag:Old {}; // magic for maps
// Maps get {}s. Write trait `is_associative` to generalize:
template<class CharT, class Traits, class...Xs >
void pretty_print_before( default_tag, std::basic_ostream<CharT, Traits>& s, std::map<Xs...> const& ) {
s << CharT('{');
}
template<class CharT, class Traits, class...Xs >
void pretty_print_after( default_tag, std::basic_ostream<CharT, Traits>& s, std::map<Xs...> const& ) {
s << CharT('}');
}
// tuples and pairs get ():
template<class CharT, class Traits, class Tup >
std::enable_if_t<is_tupleoid<Tup>{}> pretty_print_before( default_tag, std::basic_ostream<CharT, Traits>& s, Tup const& ) {
s << CharT('(');
}
template<class CharT, class Traits, class Tup >
std::enable_if_t<is_tupleoid<Tup>{}> pretty_print_after( default_tag, std::basic_ostream<CharT, Traits>& s, Tup const& ) {
s << CharT(')');
}
// strings with the same character type get ""s:
template<class CharT, class Traits, class...Xs >
void pretty_print_before( default_tag, std::basic_ostream<CharT, Traits>& s, std::basic_string<CharT, Xs...> const& ) {
s << CharT('"');
}
template<class CharT, class Traits, class...Xs >
void pretty_print_after( default_tag, std::basic_ostream<CharT, Traits>& s, std::basic_string<CharT, Xs...> const& ) {
s << CharT('"');
}
// and pack the characters together:
template<class CharT, class Traits, class...Xs >
void pretty_print_between( default_tag, std::basic_ostream<CharT, Traits>&, std::basic_string<CharT, Xs...> const& ) {}
// map magic. When iterating over the contents of a map, use the map_magic_tag:
template<class...Xs>
map_magic_tag<default_tag> pretty_print_descend( default_tag, std::map<Xs...> const& ) {
return {};
}
template<class old_tag, class C>
old_tag pretty_print_descend( map_magic_tag<old_tag>, C const& ) {
return {};
}
// When printing a pair immediately within a map, use -> as a separator:
template<class old_tag, class CharT, class Traits, class...Xs >
void pretty_print_between( map_magic_tag<old_tag>, std::basic_ostream<CharT, Traits>& s, std::pair<Xs...> const& ) {
s << CharT('-') << CharT('>');
}
}
// default behavior:
template<class CharT, class Traits, class Tag, class Container >
void pretty_print_before( Tag const&, std::basic_ostream<CharT, Traits>& s, Container const& ) {
s << CharT('[');
}
template<class CharT, class Traits, class Tag, class Container >
void pretty_print_after( Tag const&, std::basic_ostream<CharT, Traits>& s, Container const& ) {
s << CharT(']');
}
template<class CharT, class Traits, class Tag, class Container >
void pretty_print_between( Tag const&, std::basic_ostream<CharT, Traits>& s, Container const& ) {
s << CharT(',');
}
template<class Tag, class Container>
Tag&& pretty_print_descend( Tag&& tag, Container const& ) {
return std::forward<Tag>(tag);
}
// print things by default by using <<:
template<class Tag=decorator::default_tag, class Scalar, class CharT, class Traits>
std::enable_if_t<!is_visitable<Scalar>{}> print( std::basic_ostream<CharT, Traits>& os, Scalar&& scalar, Tag&&=Tag{} ) {
os << std::forward<Scalar>(scalar);
}
// for anything visitable (see above), use the pretty print algorithm:
template<class Tag=decorator::default_tag, class C, class CharT, class Traits>
std::enable_if_t<is_visitable<C>{}> print( std::basic_ostream<CharT, Traits>& os, C&& c, Tag&& tag=Tag{} ) {
pretty_print_before( std::forward<Tag>(tag), os, std::forward<C>(c) );
visit_first( c, [&](auto&& elem) {
print( os, std::forward<decltype(elem)>(elem), pretty_print_descend( std::forward<Tag>(tag), std::forward<C>(c) ) );
});
visit_all_but_first( c, [&](auto&& elem) {
pretty_print_between( std::forward<Tag>(tag), os, std::forward<C>(c) );
print( os, std::forward<decltype(elem)>(elem), pretty_print_descend( std::forward<Tag>(tag), std::forward<C>(c) ) );
});
pretty_print_after( std::forward<Tag>(tag), os, std::forward<C>(c) );
}
}
Test code:
int main() {
std::vector<int> x = {1,2,3};
pretty_print::print( std::cout, x );
std::cout << "\n";
std::map< std::string, int > m;
m["hello"] = 3;
m["world"] = 42;
pretty_print::print( std::cout, m );
std::cout << "\n";
}
This does use C++14 features (some _t
aliases, and auto&&
lambdas), but none are essential.
Floated elements do not occupy the space inside of the parent element, As the name suggests they float! Thus if a height is explicitly not provided to an element having its child elements floated, then the parent element will appear to shrink & appear to not accepting dimensions of the child element, also if its given overflow:hidden;
its children may not appear on screen. There are multiple ways to deal with this problem:
Insert another element below the floated element with clear:both;
property, or use clear:both;
on :after
of the floated element.
Use display:inline-block;
or flex-box
instead of float
.
Here it is:
function call_func(input) {
var evaled = eval('(' + input + ')');
var newDiv = document.createElement('div');
var id = evaled.id;
var name = evaled.Student_name;
var dob = evaled.student_dob;
var html = '<b>ID:</b>';
html += '<a href="/learningyii/index.php?r=student/view& id=' + id + '">' + id + '</a>';
html += '<br/>';
html += '<b>Student Name:</b>';
html += name;
html += '<br/>';
html += '<b>Student DOB:</b>';
html += dob;
html += '<br/>';
newDiv.innerHTML = html;
newDiv.setAttribute('class', 'view');
$('#StudentGridViewId').find('.items').prepend(newDiv);
};
For what it's worth, here's a general solution to positioning the image centered above the text without using any magic numbers. Note that the following code is outdated and you should probably use one of the updated versions below:
// the space between the image and text
CGFloat spacing = 6.0;
// lower the text and push it left so it appears centered
// below the image
CGSize imageSize = button.imageView.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);
// raise the image and push it right so it appears centered
// above the text
CGSize titleSize = button.titleLabel.frame.size;
button.imageEdgeInsets = UIEdgeInsetsMake(
- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
The following version contains changes to support iOS 7+ that have been recommended in comments below. I haven't tested this code myself, so I'm not sure how well it works or whether it would break if used under previous versions of iOS.
// the space between the image and text
CGFloat spacing = 6.0;
// lower the text and push it left so it appears centered
// below the image
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);
// raise the image and push it right so it appears centered
// above the text
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
button.imageEdgeInsets = UIEdgeInsetsMake(
- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
// increase the content height to avoid clipping
CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
Swift 5.0 version
extension UIButton {
func alignVertical(spacing: CGFloat = 6.0) {
guard let imageSize = imageView?.image?.size,
let text = titleLabel?.text,
let font = titleLabel?.font
else { return }
titleEdgeInsets = UIEdgeInsets(
top: 0.0,
left: -imageSize.width,
bottom: -(imageSize.height + spacing),
right: 0.0
)
let titleSize = text.size(withAttributes: [.font: font])
imageEdgeInsets = UIEdgeInsets(
top: -(titleSize.height + spacing),
left: 0.0,
bottom: 0.0,
right: -titleSize.width
)
let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0
contentEdgeInsets = UIEdgeInsets(
top: edgeOffset,
left: 0.0,
bottom: edgeOffset,
right: 0.0
)
}
}
If you are using Bootstrap 2.0+
This can make the div centered to the page.
<div class="row">
<div class="span4 offset4">
//your content here gets centered of the page
</div>
</div>
package main
import (
"fmt"
"strconv"
)
func main(){
//First question: how to get int string?
intValue := 123
// keeping it in separate variable :
strValue := strconv.Itoa(intValue)
fmt.Println(strValue)
//Second question: how to concat two strings?
firstStr := "ab"
secondStr := "c"
s := firstStr + secondStr
fmt.Println(s)
}
If you are using boot2docker and ntp doesn't work inside the docker VM (you are behind a proxy which does not forward ntp packets) but your host is time-synced, you can run the following from your host:
docker-machine ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"
This way you are sending your machine's current time (in UTC timezone) as a string to set the docker VM time using date
(again in UTC timezone).
NOTE: in Windows, inside a bash shell (from the msys git), use:
docker-machine.exe ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
function gitcheckoutall() {
git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}
I've added this function in .zshrc file.
Use them this way:
gitcheckoutall theirs
or gitcheckoutall ours
In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;
In package body:
initialize the table in declarations:
exch_rt exch_tbl := exch_tbl();
in order to add record to the local collection, in begin - end block you can do:
exch_rt.extend;
one_row.exch_rt_usd := 2;
one_row.exch_rt_eur := 1;
one_row.currency_cd := 'dollar';
exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop
in order to get data from this table , inside package body you can use:
select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)
enjoy!
P.S. sorry for a late answer :D