It can also occur if you leave an element with a null or empty attribute in your XML layout file else if your java file's path of objects creation such as specifying improper ID for the object
here frombottom= AnimationUtils.loadAnimation(this,R.anim);
in which anim. the id or filename is left blank can lead to such problem.
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.
import React, {useState, useEffect, useRef} from 'react';
export default App = () => {
const [width, setWidth] = useState(0);
const elementRef = useRef(null);
useEffect(() => {
setWidth(elementRef.current.getBoundingClientRect().width);
}, []); //empty dependency array so it only runs once at render
return (
<div ref={elementRef}>
{width}
</div>
)
}
You can use the official Slider
in the Material Components Library.
Use the app:trackHeight="xxdp"
(default value is 4dp
) to change the height of the track bar.
Also use these attributes to customize the colors:
app:activeTrackColor
: the active track colorapp:inactiveTrackColor
: the inactive track colorapp:thumbColor
: to fill the thumbSomething like:
<com.google.android.material.slider.Slider
android:id="@+id/slider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:activeTrackColor="#ffd400"
app:inactiveTrackColor="#e7e7e7"
app:thumbColor="#ffb300"
app:trackHeight="12dp"
.../>
It requires the version 1.2.0 of the library.
1.Create a custom pipe to get keys.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'keys'
})
export class KeysPipe implements PipeTransform {
transform(value: any, args?: any): any {
return Object.keys(value);
}
}
- In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
{{key}}
{{Obj[key].property}
<div>
You can use the pathinfo() function built into PHP for that:
$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];
Or more concisely, you can pass an option get get it directly;
$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);
On Xiaomi Mi5s with MIUI8.3 (Android 6) Xiaomi.EU Rom:
Settings/ Other Settings / Developer Options / Switch on: Allow USB Debug, Allow USB install and Allow USB Debug (Security options)
{Sorry for the translation, my device has spanish}
If you are using Sass:
$card-column-sizes: (
xs: 2,
sm: 3,
md: 4,
lg: 5,
);
@each $breakpoint-size, $column-count in $card-column-sizes {
@include media-breakpoint-up($breakpoint-size) {
.card-columns {
column-count: $column-count;
column-gap: 1.25rem;
.card {
display: inline-block;
width: 100%; // Don't let them exceed the column width
}
}
}
}
In WC 3.0+ versions the image can get by below code.
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $item->get_product_id() ), 'single-post-thumbnail' );
echo $image_url[0]
I think you are trying to check whether the array is empty or not.You can do like this :
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
Reference isEmpty()
HttpClient was deprecated in API Level 22 and removed in API Level 23.
You have to use URLConnection
.
well, there are many ways to do this in javascript just like other says. I don't think there's a way to do it in react. here's what I would do:
in a js file:
module.exports = {
small_square: 's',
large_square: 'q'
}
in your react file:
'use strict';
var Constant = require('constants');
....
var something = Constant.small_square;
something for you to consider, hope this helps
User doesn't have write permission for some Python installation paths. You can give the permission by:
sudo chown -R $USER /absolute/path/to/directory
So you should give permission, then try to install it again, if you have new paths you should also give permission:
sudo chown -R $USER /usr/local/lib/python2.7/
Throwing in here my version of the accepted answer to work nicely with Swift 5. This solution does not force unwrap the resulting image making it a bit safer and overall cleaner solution.
extension UIImage {
public func resized(to target: CGSize) -> UIImage? {
let ratio = min(
target.height / size.height, target.width / size.width
)
let new = CGSize(
width: size.width * ratio, height: size.height * ratio
)
UIGraphicsBeginImageContextWithOptions(new, false, 1.0)
draw(in: CGRect(origin: .zero, size: new))
defer { UIGraphicsEndImageContext() }
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Once I designed an API which main resource was people
. Usually users would request filtered people
so, to prevent users to call something like /people?settlement=urban
every time, I implemented /people/urban
which later enabled me to easily add /people/rural
. Also this allows to access the full /people
list if it would be of any use later on. In short, my reasoning was to add a path to common subsets
From here:
Aliases for common queries
To make the API experience more pleasant for the average consumer, consider packaging up sets of conditions into easily accessible RESTful paths. For example, the recently closed tickets query above could be packaged up as
GET /tickets/recently_closed
You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:
class ModelAttachment {
var id: String?
var url: String?
var thumb: String?
}
var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"
var imgs: Array<ModelAttachment> = [modelAttachementObj]
for img in imgs {
let url = img.url
NSLog(url!)
}
We have the following string which is a valid JSON ...
Clearly the JSON parser disagrees!
However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.
You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException
... then find out what is in the ByteArrayInputStream
that it is attempting to parse.
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
Use the -ss
option:
ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
For JPEG output use -q:v
to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.
The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.
Placing -ss
before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg
cli tool documentation:
-ss
position (input/output)When used as an input option (before
-i
), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, soffmpeg
will seek to the closest seek point before position. When transcoding and-accurate_seek
is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when-noaccurate_seek
is used, it will be preserved.When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.
position may be either in seconds or in
hh:mm:ss[.xxx]
form.
Final working solution:
public static String getFileName(Uri uri) {
try {
String path = uri.getLastPathSegment();
return path != null ? path.substring(path.lastIndexOf("/") + 1) : "unknown";
} catch (Exception e) {
e.printStackTrace();
}
return "unknown";
}
Just use another container to wrap last two divs. Don't forget to use CSS prefixes.
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
display: flex;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
background-color: red;_x000D_
flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
background-color: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle">1</div>_x000D_
<div id="anotherContainer">_x000D_
<div id="productShowcaseDetail">2</div>_x000D_
<div id="productShowcaseThumbnailContainer">3</div>_x000D_
</div>_x000D_
</div>
_x000D_
If anyone finds that any of the suggested:
python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb
fail, you may need to add a folder named "migrations
" inside the app directory, and create an empty __init__.py
file.
For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.
Only these 3 tags seem to be required (og:title
, twitter:description
, rel="icon"
):
<meta property="og:title" content="San Roque 2014 Pollos" />
<meta name="twitter:description" property="og:description" itemprop="description" content="Programa de fiestas" />
<link rel="icon" type="image/png" href="https://images.weserv.nl/?url=http://pollosweb.wesped.es/programa_pollos/play.png&w=192&height=192" sizes="192x192" />
The easiest way to experiment for me was with CodeSandbox following these steps:
index.html
filectrl+s
) which would fork the app and generate its own unique urlJust be sure to ALWAYS have quotes and closing quotes because WhatsApp is sensitive to that. Your above example does not have a closing quote for your og:description
.
Try this one, it works fine for me.
In CSS:
::-webkit-scrollbar
{
width: 0px;
}
::-webkit-scrollbar-track-piece
{
background-color: transparent;
-webkit-border-radius: 6px;
}
and here is the working demo: https://jsfiddle.net/qpvnecz5/
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">
<script type"text/javascript">
function preview_image(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]
## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
This works for me in Outlook:
<img src="image.jpg" width="120" style="display:block;width:100%" />
I hope it works for you.
<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
die("error");
}
$data = $matches[2];
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'text.jpg';
$dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
var videos = <?= json_encode($videos); ?>;
var video = document.getElementById('video');
video.addEventListener('canplay', function () {
this.currentTime = this.duration / 2;
}, false);
var seek = true;
video.addEventListener('seeked', function () {
if (seek) {
getThumb();
}
}, false);
function getThumb() {
seek = false;
var filename = video.src;
var w = video.videoWidth;//video.videoWidth * scaleFactor;
var h = video.videoHeight;//video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var data = canvas.toDataURL("image/jpg");
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("POST", location.href, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
}
function failed(e) {
// video playback failed - show a message saying why
switch (e.target.error.code) {
case e.target.error.MEDIA_ERR_ABORTED:
console.log('You aborted the video playback.');
break;
case e.target.error.MEDIA_ERR_NETWORK:
console.log('A network error caused the video download to fail part-way.');
break;
case e.target.error.MEDIA_ERR_DECODE:
console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
break;
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
break;
default:
console.log('An unknown error occurred.');
break;
}
}
</script>
//Html
<div>
<video id="video" src="1499752288.mp4" autoplay="true" onerror="failed(event)" controls="controls" preload="none"></video>
</div>
You can install PIL using apt install
:
For Python 3 use:
sudo apt install python3-pil
For Python 2 use:
sudo apt install python-pil
Where pil
should be lowercase as Clarkey252 points out
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %}
(wrong) instead of {% url 'my_view' %}
(correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %}
syntax.
But there's no reason why the django admin site would throw this, since it would know it's own syntax. My best guess is therefore that grapelli
is causing your problem since it changes the admin templates. Does removing grappelli from installed apps help?
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.
It’s more hassle than it’s worth.
Just found out a great plugin for this:
http://flexslider.woothemes.com/
Regards
Here is another nice and easy solution:
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
Reference: PHP resize image proportionally with max width or weight
Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.
Is this what you're after?
I added :text-align:center
to the div and image
Main point you are looking for is:
.tag-remove::before {
content: 'x'; // here is your X(cross) sign.
color: #fff;
font-weight: 300;
font-family: Arial, sans-serif;
}
FYI, you can make a close button by yourself very easily:
#mdiv {_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
background-color: red;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.mdiv {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
margin-left: 12px;_x000D_
background-color: black;_x000D_
transform: rotate(45deg);_x000D_
Z-index: 1;_x000D_
}_x000D_
_x000D_
.md {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
background-color: black;_x000D_
transform: rotate(90deg);_x000D_
Z-index: 2;_x000D_
}
_x000D_
<div id="mdiv">_x000D_
<div class="mdiv">_x000D_
<div class="md"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:
<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->
If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:
<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>
(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
<c:if test="#{not empty user or user.userId eq 0}">
<a href="Images/thumb_02.jpg" target="_blank" ></a>
<img src="Images/thumb_02.jpg" />
</c:if>
<c:if test="#{empty user or user.userId eq 0}">
<a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
<img src="/DisplayBlobExample?userId=#{user.userId}" />
</c:if>
</html>
Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:
<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>
replace your image tag with
<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3" style="width:640px;height:360px" />
use style attribute and make sure there is no css class for image which set image height and width
With Kotlin, you can avoid a loop by wrapping the JSONArray with a MutableList, e.g.
val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}
In your main styles.css
file change height/auto to whatever settings you desire. For example, 500px
:
#myCarousel {
height: auto;
width: auto;
overflow: hidden;
}
++ This worked for me. It's vanilla javascirpt
and good for use cases such as de-cluttering when testing with ngMocks
library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript
file that contains the JSON
data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js
accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development
environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function
at the bottom of the code returning whatever JSON
.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
If the above solutions are not working just delete this entire line from XML
android:src="@drawable/image"
& only try
imageView.setBackgroundResource(R.drawable.image);
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
This error happens when you have a __unicode__
method that is a returning a field that is not entered. Any blank field is None
and Python cannot convert None
, so you get the error.
In your case, the problem most likely is with the PCE
model's __unicode__
method, specifically the field its returning.
You can prevent this by returning a default value:
def __unicode__(self):
return self.some_field or u'None'
If you are using default SeekBar provided by android Sdk then their is a simple way to change the color of that . just go to color.xml inside /res/values/colors.xml and change the colorAccent.
<resources>
<color name="colorPrimary">#212121</color>
<color name="colorPrimaryDark">#1e1d1d</color>
<!-- change below line -->
<color name="colorAccent">#FF4081</color>
</resources>
Create folder path image/thumbs on your hard disk => Problem solved!
It is not best practise to mix up content with style, but a solution could be
<div class="thumb" style="background-image: url('images/img.jpg')"></div>
And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?
Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.
Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.
Is it correct to say that everywhere recursion is used a for loop could be used?
Yes. This thread has a very good answer for this.
And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?
Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.
Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.
Put it as a background on your holder e.g.
<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">
</div>
This will center your image inside a 120x120 div chopping off any excess of the image
You can do it with a simple jquery code.
$('#Mymodal').modal('hide');
You can register another directive on top of ng-click
which amends the default behaviour of ng-click
and stops the event propagation. This way you wouldn't have to add $event.stopPropagation
by hand.
app.directive('ngClick', function() {
return {
restrict: 'A',
compile: function($element, attr) {
return function(scope, element, attr) {
element.on('click', function(event) {
event.stopPropagation();
});
};
}
}
});
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
Try to pass the serializable list using Bundle.Serializable:
Bundle bundle = new Bundle();
bundle.putSerializable("value", all_thumbs);
intent.putExtras(bundle);
And in SomeClass Activity get it as:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
List<Thumbnail> thumbs=
(List<Thumbnail>)bundle.getSerializable("value");
This is what I use to make the text appear on hover:
* {_x000D_
box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
position: relative;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border-radius: 50%;_x000D_
overflow: hidden;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
position: absolute;_x000D_
border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
opacity: 0;_x000D_
transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
line-height: 40px;_x000D_
font-weight: bold;_x000D_
font-family: "Trebuchet MS";_x000D_
text-align: center;_x000D_
position: absolute;_x000D_
display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
z-index: -1;_x000D_
width: 420px;_x000D_
line-height: 20px;_x000D_
display: inline-block;_x000D_
padding: 200px 0px;_x000D_
vertical-align: middle;_x000D_
font-family: "Trebuchet MS";_x000D_
height: 450px_x000D_
}
_x000D_
<div>_x000D_
<img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
</p>_x000D_
</div>
_x000D_
Well, you should think about one more thing.
If you have a really big dataset, like 1,000,000 examples, split 80/10/10 may be unnecessary, because 10% = 100,000 examples may be just too much for just saying that model works fine.
Maybe 99/0.5/0.5 is enough because 5,000 examples can represent most of the variance in your data and you can easily tell that model works good based on these 5,000 examples in test and dev.
Don't use 80/20 just because you've heard it's ok. Think about the purpose of the test set.
.className{
width: auto;
height: 200px;
max-height: 200px;
max-width:200px
object-fit: contain;
}
Its possible, we can specify onclick event in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>
You can simply get HQ youtube thumbnails..
<?php _x000D_
_x000D_
$terms = get_terms( array(_x000D_
'taxonomy' => 'product_cat',_x000D_
'hide_empty' => false,_x000D_
) ); // Get Terms_x000D_
_x000D_
foreach ($terms as $key => $value) _x000D_
{_x000D_
$metaterms = get_term_meta($value->term_id);_x000D_
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );_x000D_
$image = wp_get_attachment_url( $thumbnail_id );_x000D_
echo '<img src="'.$image.'" alt="" />';_x000D_
} // Get Images from woocommerce term meta_x000D_
_x000D_
?>
_x000D_
global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = new WC_product($cart_item['product_id']);
var_dump($product);
}
The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:
$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';
The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}
This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.
if you have many tables you want to change collation on run this query:
select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM
information_schema.tables where table_schema='SCHRMA') t;
this will output the queries needed to convert all the tables to use the correct collation per column
If you have not too much data, you can definitely do pagination by just storing all the data in the browser and filtering what's visible at a certain time.
Here's a simple pagination example: http://jsfiddle.net/2ZzZB/56/
That example was on the list of fiddles on the angular.js github wiki, which should be helpful: https://github.com/angular/angular.js/wiki/JsFiddle-Examples
EDIT: http://jsfiddle.net/2ZzZB/16/ to http://jsfiddle.net/2ZzZB/56/ (won't show "1/4.5" if there is 45 results)
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
If the post is an image and we already know what the image is, it's possible to get the thumbnail URL without too much hassle:
echo pathinfo($image->guid, PATHINFO_DIRNAME);
Apart from accepted answer, following is also valid
Model.find()
can accept array of ids, and will return all records which matches.
Model.find_by_id(123)
also accept array but will only process first id value present in array
Model.find([1,2,3])
Model.find_by_id([1,2,3])
Put the picture inside a newDiv
.
Make the width of the containing div
the same as the image.
Apply margin: 0 auto;
to the newDiv
.
That should center the div
within the container.
Ok, Here's what I found out.
What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)
What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
Log.d(TAG, "constructor: detaching fragment " + mTag);
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab"));
Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number"));
}
When the tab was selected it would be reattached in the onTabSelected callback.
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
Log.d(TAG, "onTabSelected adding fragment " + mTag);
ft.add(android.R.id.content, mFragment, mTag);
} else {
Log.d(TAG, "onTabSelected attaching fragment " + mTag);
ft.attach(mFragment);
}
}
The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time.
The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
Log.d(TAG, "onTabSelected adding fragment " + mTag);
ft.add(android.R.id.content, mFragment, mTag);
} else {
if(mFragment.isDetached()) {
Log.d(TAG, "onTabSelected attaching fragment " + mTag);
ft.attach(mFragment);
} else {
Log.d(TAG, "onTabSelected fragment already attached " + mTag);
}
}
}
$('html,body').animate({
scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);
From w3 schools:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<img src="/pathtoimage" class="tooltiptext">
</div>
Sounds like about what you want
You could try:
$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');
For z-index to work, you also need to give it a position:
header {
width: 100%;
height: 100px;
background: url(../img/top.png) repeat-x;
z-index: 110;
position: relative;
}
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.
You can define the drawables that are used for the background, and the switcher part like this:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/switch_thumb_holo_light" />
</selector>
This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:
The deactivated version (xhdpi version that Android is using)
The pressed slider:
The activated slider (on state):
The default version (off state):
There are also three different states for the background that are defined in the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" />
<item android:drawable="@drawable/switch_bg_holo_dark" />
</selector>
The deactivated version:
The focused version:
And the default version:
To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.
If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.
Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/
EDIT
Your code should look like this:
.img_thumb {
float: left;
height: 120px;
margin-bottom: 5px;
margin-left: 9px;
position: relative;
width: 147px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 3px;
line-height:120px;
text-align:center;
}
.img_thumb img {
vertical-align: middle;
}
The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:
http://jsfiddle.net/Cthulhu/QHEnL/6/
http://jsfiddle.net/Cthulhu/QHEnL/7/
UPDATE
It's now 2016 (the future!) and looks like a few things are changing (finally!!).
Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).
Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.
With that being said, here's an updated way of aligning elements, both horizontally and vertically:
.container {
position: relative;
}
.container .element {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Using this transform: translate();
method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.
If you only need to center in one dimension, you can use translateY
or translateX
. Just try it for a while and you'll see how it works. Also, try to change the values of the translate
, you will find it useful for a bunch of different situations.
Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/
For more information on transform
, here's a good resource.
Happy coding.
To get rid of the if/else awkwardness you could use a using block:
@{
var count = 0;
foreach (var item in Model)
{
using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
{
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.Truncate(item.Details, 75)
</td>
<td>
<img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()"
alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
@Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
</td>
}
}
}
Reusable element that make it easier to add attributes:
//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
private object _htmlAttributes;
private TagBuilder _tr;
public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
{
_htmlAttributes = htmlAttributes;
}
public override void BeginBlock()
{
_tr = new TagBuilder("tr");
_tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
}
protected override void EndBlock()
{
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
}
}
Helper method to make razor syntax clearer:
public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
var tableRow = new TableRow(self, htmlAttributes);
tableRow.BeginBlock();
return tableRow;
}
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
jQuery needs to be the first script you import. The first script on your page
<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>
appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.
I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.
<meta property="og:url" content="<?
$url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];;
echo htmlentities($url,ENT_QUOTES); ?>"/>
There is no built-in auto_increment in Oracle.
You need to use sequences
and triggers
.
Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")
You can define a a click function and then set the onclick
attribute for the element.
function imageClick(url) {
window.location = url;
}
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />
This approach lets you get rid of the surrounding <a>
element. If you want to keep it, then define the onclick
attribute on <a>
instead of on <img>
.
I remember my CompSci professor saying never to use floats for currency.
The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2
). Because of that, it is impossible to store fractions and decimals in Float exactly.
That's why there is a Decimal format. If you do this:
irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!
whereas if you just do
irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you
So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10
is exactly 0.1.
However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:
require "benchmark"
require "bigdecimal"
d = BigDecimal.new(3)
f = Float(3)
time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } }
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }
puts time_decimal
#=> 6.770960 seconds
puts time_float
#=> 0.988070 seconds
Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.
Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.
Have a look at jQuery scroll view (demo here). Here is the git hub repository for that experimental project. Look at their html to see what files need to be included and what attributes to add to the elements you want to be scrollable.
I have used this to be able to scroll div elements horizontally on touch devices.
Not different for other answers, my framework have almost the same levels:
You can use code below if you don't want to modify block mode:
img{vertical-align:text-bottom}
Or you can use following as Stuart suggests:
img{vertical-align:bottom}
Instead of writing this,
<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a.src;
}
</script>
try:
<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a;
}
</script>
This solution will play the video upon clicking. You'll need to edit your picture to add a button image yourself.
You're going to need the URL of your picture and the YouTube video ID. The YouTube video id is the part of the URL after the v=
parameter, so for https://www.youtube.com/watch?v=DODLEX4zzLQ the ID would be DODLEX4zzLQ
.
<div width="560px" height="315px" style="position: static; clear: both; width: 560px; height: 315px;"> <div style="position: relative"><img id="vidimg" width="560px" height="315px" src="URL_TO_PICTURE" style="position: absolute; top: 0; left: 0; cursor: pointer; pointer-events: none; z-index: 2;" /><iframe id="unlocked-video" style="position: absolute; top: 0; left: 0; z-index: 1;" src="https://www.youtube.com/embed/YOUTUBE_VIDEO_ID" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div></div>
<script type="application/javascript">
// Adapted from https://stackoverflow.com/a/32138108
var monitor = setInterval(function(){
var elem = document.activeElement;
if(elem && elem.id == 'unlocked-video'){
document.getElementById('vidimg').style.display='none';
clearInterval(monitor);
}
}, 100);
</script>
Be sure to replace URL_TO_PICTURE and YOUTUBE_VIDEO_ID in the above snippet.
To clarify what's going on here, this displays the image on top of the video, but allows clicks to pass through the image. The script monitors for clicks in the video iframe, and then hides the image if a click occurs. You may not need the float: clear
.
I haven't compared this to the other answers here, but this is what I have used.
Javascript now give a very useful functionnality to handle url parameters: URLSearchParams
var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()
Also remember that all info()
, error()
, and debug()
logging calls provide internal documentation within any application.
A solution is to use background-position to mimic the gradient transition. This solution was used in Twitter Bootstrap a few months ago.
Update
http://codersblock.blogspot.fr/2013/12/gradient-animation-trick.html?showComment=1390287622614
Here is a quick example:
Link state
.btn {
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 12px;
font-weight: 300;
position: relative;
display: inline-block;
text-decoration: none;
color: #fff;
padding: 20px 40px;
background-image: -moz-linear-gradient(top, #50abdf, #1f78aa);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#50abdf), to(#1f78aa));
background-image: -webkit-linear-gradient(top, #50abdf, #1f78aa);
background-image: -o-linear-gradient(top, #50abdf, #1f78aa);
background-image: linear-gradient(to bottom, #50abdf, #1f78aa);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50abdf', endColorstr='#ff1f78aa', GradientType=0);
background-repeat: repeat-y;
background-size: 100% 90px;
background-position: 0 -30px;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
Hover state
.btn:hover {
background-position: 0 0;
}
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
Year 2020 this works
/* Thin Scrollbar */
:root{
scrollbar-color: rgb(210,210,210) rgb(46,54,69) !important;
scrollbar-width: thin !important;
}
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.
A simple get started:
Create test.cpp: (This will be built and run to verify you got things set up right.)
#include <X11/Xlib.h>
#include <unistd.h>
main()
{
// Open a display.
Display *d = XOpenDisplay(0);
if ( d )
{
// Create the window
Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
100, 0, CopyFromParent, CopyFromParent,
CopyFromParent, 0, 0);
// Show the window
XMapWindow(d, w);
XFlush(d);
// Sleep long enough to see the window.
sleep(10);
}
return 0;
}
Try: g++ test.cpp -lX11
If it builds to a.out
, try running it.
If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.
If your response is:
test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
compilation terminated.
you need to install X11 development libraries.
sudo apt-get install libx11-dev
Retry g++ test.cpp -lX11
If it works, you're golden.
Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb
.post-container{_x000D_
margin: 20px 20px 0 0; _x000D_
border:5px solid #333;_x000D_
width:600px;_x000D_
overflow:hidden;_x000D_
}_x000D_
_x000D_
.post-thumb img {_x000D_
float: left;_x000D_
clear:left;_x000D_
width:50px;_x000D_
height:50px;_x000D_
border:1px solid red;_x000D_
}_x000D_
_x000D_
.post-title {_x000D_
float:left; _x000D_
margin-left:10px;_x000D_
}_x000D_
_x000D_
.post-content {_x000D_
float:right;_x000D_
}
_x000D_
<div class="post-container"> _x000D_
<div class="post-thumb"><img src="thumb.jpg" /></div>_x000D_
<div class="post-title">Post title</div>_x000D_
<div class="post-content"><p>post description description description etc etc etc</p></div>_x000D_
</div>
_x000D_
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
If you are using Android studio and you are still seeing the message "error: vector: No such file or directory" (or other stl related errors) when you're compiling using ndk, then this might help you.
In your project, open the module's build.gradle file (not your project's build.grade, but the one that is for your module) and add 'stl "stlport_shared"' within the ndk element in defaultConfig.
For eg:
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.domain.app"
minSdkVersion 15
targetSdkVersion 21
versionCode 1
versionName "1.0"
ndk {
moduleName "myModuleName"
stl "stlport_shared"
}
}
}
If you have renamed a file locally and then do a pull
, it will display that error message.
SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.
You should definitely go with MySQL or PostgreSQL.
If it is for a single-person project, SQLite will be easier to setup though.
I'm not sure what jQuery api you're looking at, but you should only have to specify id
.
$('#thumb').removeAttr('id');
"Only conventions? Or is there more behind the underscore prefix?"
Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.
Example ( from https://github.com/mmikowski/urianchor ) :
$.uriAnchor.setAnchor({
page : 'profile',
_page : {
uname : 'wendy',
online : 'today'
}
});
The URI anchor on the browser search field is changed to:
\#!page=profile:uname,wendy|online,today
This is a convention used to drive an application state based on hash changes.
What I did to achieve the goal was to make this..
# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):
and below the save() method is this..
# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
# your logic here
so when i edit some fields but not editing the image, I put this..
Model.save("skip creating photo thumbnail")
you can replace the "skip creating photo thumbnail"
with "im just editing the description"
or a more formal text.
Hope this one helps!
The function expects a string.
file_exists()
does not work properly with HTTP URLs.
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5)
and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5)
to check where your mistake is.
If you wish to use CV2, you need to use the resize
function.
For example, this will resize both axes by half:
small = cv2.resize(image, (0,0), fx=0.5, fy=0.5)
and this will resize the image to have 100 cols (width) and 50 rows (height):
resized_image = cv2.resize(image, (100, 50))
Another option is to use scipy
module, by using:
small = scipy.misc.imresize(image, 0.5)
There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).
Update:
According to the SciPy documentation:
imresize
is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Useskimage.transform.resize
instead.
Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale
.
I use this, if you want only one view to be bring to front when needed:
containerView.bringChildToFront(topView);
containerView is container of views to be sorted, topView is view which i want to have as top most in container.
for multiple views to arrange is about to use setChildrenDrawingOrderEnabled(true) and overriding getChildDrawingOrder(int childCount, int i) as mentioned above.
Actually...
To hide an absolute positioned element, the container position
must be anything except for static
. It can be relative
or fixed
in addition to absolute
.
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
the shortest code is :
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL is PATH of image .
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
I have found it best to add viewBox
and preserveAspectRatio
attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h
:
<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>
The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.
Let's say you have a list of integers, and want to find the items that match those integers.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var items = from p in context.Items
where numbers.Contains(p.ItemId)
select p;
Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0
Because Firefox does not support mp3 format. To make this work with Firefox, you should use the ogg format.
Here is a version based on the accepted answer. It fixes two problems...
I found this tool to be fast and effective for both JPG and PNG files.
private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
const int thumbnailSize = 150;
using (var image = Image.FromFile(imageFileName))
{
var imageHeight = image.Height;
var imageWidth = image.Width;
if (imageHeight > imageWidth)
{
imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
imageHeight = thumbnailSize;
}
else
{
imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
imageWidth = thumbnailSize;
}
using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
//Save off the new thumbnail
thumb.Save(thumbnailFileName);
}
return new FileInfo(thumbnailFileName);
}
You can try this also:
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
(this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
}
Found the solution myself in the end. The problem was not with the LinearLayout
, but with the ScrollView
(seems weird, considering the fact that the ScrollView
was expanding, while the LinearLayout
wasn't).
The solution was to use android:fillViewport="true"
on the ScrollView
.
I think this is the clearest way:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
document.getScroll = function() {
if (window.pageYOffset != undefined) {
return [pageXOffset, pageYOffset];
} else {
var sx, sy, d = document,
r = d.documentElement,
b = d.body;
sx = r.scrollLeft || b.scrollLeft || 0;
sy = r.scrollTop || b.scrollTop || 0;
return [sx, sy];
}
}
returns an array with two integers- [scrollLeft, scrollTop]
2016 Update
Use the Sharing Debugger to figure out what your problems are.
Make sure you're following the Facebook Sharing Best Practices.
Make sure you're using the Open Graph Markup correctly.
Original Answer
I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.
i got this image by right clicking the canvas element in firefox and saving as.
var img = new Image();
img.onload = function () {
console.debug(this.width,this.height);
var canvas = document.createElement('canvas'), ctx;
canvas.width = 188;
canvas.height = 150;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0,188,150);
};
img.src = 'original.jpg';
so anyway, here is a 'fixed' version of your example:
var img = new Image();
// added cause it wasnt defined
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
// adding it to the body
document.body.appendChild(canvasCopy);
var copyContext = canvasCopy.getContext("2d");
img.onload = function()
{
var ratio = 1;
// defining cause it wasnt
var maxWidth = 188,
maxHeight = 150;
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
// the line to change
// ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
// the method signature you are using is for slicing
ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
};
// changed for example
img.src = 'original.jpg';
If all you want to do is search YouTube and get associated properties:
Get a public API -- This link gives a good direction
Use below query string. The search query (denoted by q=) in the URL string is stackoverflow for example purposes. YouTube will then send you back a JSON reply where you can then parse for Thumbnail, Snippet, Author, etc.
There are a lot of jQuery plugins available for this
Thickbox Examples
For a single image
- Create a link element ()
- Give the link a class attribute with a value of thickbox (class="thickbox")
- Provide a path in the href attribute to an image file (.jpg .jpeg .png .gif .bmp)
For anyone who is also trying to call .format()
on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format(
call, you can do str.format("", 1, 2)
instead of "".format(1, 2)
. This lets you break the string with whatever technique you like. For example:
logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))
can be
logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))
Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
If you simply want to reduce your button image:
yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
I tried many different ways and this way is the only one worked for me
//check all images on the page
$('img').each(function(){
var img = new Image();
img.onload = function() {
console.log($(this).attr('src') + ' - done!');
}
img.src = $(this).attr('src');
});
You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/
If you have at least PHP 5.5, you can use json_last_error_msg(), which will return a string describing the problem.
If you don't have 5.5, but are on/above 5.3, you can use json_last_error() to see what the problem is.
It will return an integer, that you can use to identify the problem in the function's documentation. Currently (2012.01.19), the identifiers are:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
These can change in future versions, so it's better to consult the manual.
If you are below 5.3, you are out of luck, there is no way to ask what the error was.
I use the following method to calculate the desired image size:
using System.Drawing;
public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
{
maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
}
This puts the problem of aspect ratio and dimensions in a separate method.
The Google Testing Blog discussed this problem recently:
So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.
(snip)
These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.
You have it right. The stack pointer points to the top item on the stack and the base pointer points to the "previous" top of the stack before the function was called.
When you call a function, any local variable will be stored on the stack and the stack pointer will be incremented. When you return from the function, all the local variables on the stack go out of scope. You do this by setting the stack pointer back to the base pointer (which was the "previous" top before the function call).
Doing memory allocation this way is very, very fast and efficient.
function parseVideo(url) {
// - Supported YouTube URL formats:
// - http://www.youtube.com/watch?v=My2FRPA3Gf8
// - http://youtu.be/My2FRPA3Gf8
// - https://youtube.googleapis.com/v/My2FRPA3Gf8
// - Supported Vimeo URL formats:
// - http://vimeo.com/25451551
// - http://player.vimeo.com/video/25451551
// - Also supports relative URLs:
// - //player.vimeo.com/video/25451551
url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
if (RegExp.$3.indexOf('youtu') > -1) {
var type = 'youtube';
} else if (RegExp.$3.indexOf('vimeo') > -1) {
var type = 'vimeo';
}
return {
type: type,
id: RegExp.$6
};
}
function getVideoThumbnail(url, cb) {
var videoObj = parseVideo(url);
if (videoObj.type == 'youtube') {
cb('//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg');
} else if (videoObj.type == 'vimeo') {
$.get('http://vimeo.com/api/v2/video/' + videoObj.id + '.json', function(data) {
cb(data[0].thumbnail_large);
});
}
}
If you are using API 2.0 or newer this will work.
int id = **"The Video's ID"**
ImageView iv = (ImageView ) convertView.findViewById(R.id.imagePreview);
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
iv.setImageBitmap(curThumb);
So, if you have a model with an imagefield with an upload_to attribute set, such as:
class Avatar(models.Model):
image_file = models.ImageField(upload_to=user_directory_path_avatar)
then it is reasonably easy to change the image, at least in django 3.15.
In the view, when you process the image, you can obtain the image from:
self.request.FILES['avatar']
which is an instance of type InMemoryUploadedFile, as long as your html form has the enctype set and a field for avatar...
<form method="post" class="avatarform" id="avatarform" action="{% url avatar_update_view' %}" enctype="multipart/form-data">
{% csrf_token %}
<input id="avatarUpload" class="d-none" type="file" name="avatar">
</form>
Then, setting the new image in the view is as easy as the following (where profile is the profile model for the self.request.user)
profile.avatar.image_file.save(self.request.FILES['avatar'].name, self.request.FILES['avatar'])
There is no need to save the profile.avatar, the image_field already saves, and into the correct location because of the 'upload_to' callback function.
Why not use properly formulated geospatial queries???
Here is the SQL server reference page on the STContains geospatial function:
or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:
DECLARE @CurrentLocation geography;
SET @CurrentLocation = geography::Point(12.822222, 80.222222, 4326)
SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km
There should be similar functionality for almost any database out there.
If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using
Old question but recently I seemed to be running into same issue with thumbnail images from my link not showing in status updates on Facebook. I post for many clients and this is relatively new.
FB doesn't seem to like long URLs anymore — if you use a URL shortener such as goo.gl or bitly.com, the thumbnail from your link/post will appear in your FB update.
My company has about 24million images come in from manufacturers every month. I was looking for a fast solution to ensure that the images we upload to our catalog are new images.
I want to say that I have searched the internet far and wide to attempt to find an ideal solution. I even developed my own edge detection algorithm.
I have evaluated speed and accuracy of multiple models.
My images, which have white backgrounds, work extremely well with phashing. Like redcalx said, I recommend phash or ahash. DO NOT use MD5 Hashing or anyother cryptographic hashes. Unless, you want only EXACT image matches. Any resizing or manipulation that occurs between images will yield a different hash.
For phash/ahash, Check this out: imagehash
I wanted to extend *redcalx'*s post by posting my code and my accuracy.
What I do:
from PIL import Image
from PIL import ImageFilter
import imagehash
img1=Image.open(r"C:\yourlocation")
img2=Image.open(r"C:\yourlocation")
if img1.width<img2.width:
img2=img2.resize((img1.width,img1.height))
else:
img1=img1.resize((img2.width,img2.height))
img1=img1.filter(ImageFilter.BoxBlur(radius=3))
img2=img2.filter(ImageFilter.BoxBlur(radius=3))
phashvalue=imagehash.phash(img1)-imagehash.phash(img2)
ahashvalue=imagehash.average_hash(img1)-imagehash.average_hash(img2)
totalaccuracy=phashvalue+ahashvalue
Here are some of my results:
item1 item2 totalsimilarity
desk1 desk1 3
desk1 phone1 22
chair1 desk1 17
phone1 chair1 34
Hope this helps!
Use the following code to float the items and make sure they are displayed inline.
ul.myclass li{float:left;display:inline}
Also make sure that the container you put them in is floated with width 100% or some other technique to ensure the floated items are contained within it and following items below it.
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!
I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:
The markup relies on a wrapper element:
<div id="wrap"><img src="test.png" /></div>
Given the above markup you then use these rules:
#wrap {
height: 100px;
width: 100px;
}
#wrap img {
min-height: 100%;
min-width: 100%;
}
If you then control the size of wrapper you get the interesting scale effects that I list above.
To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.
So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.
This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.
Sharing on Facebook: How to Improve Your Results by Customizing the Image, Title, and Text
From the link above. For the best possible share, you'll want to suggest 3 pieces of data in your HTML:
This accomplished by the following, placed inside the 'head' tag of your HTML:
<title>INSERT POST TITLE</title>
<meta property=og:image content="http://site.com/YOUR_IMAGE.jpg"/>
<meta name=description content="INSERT YOUR SUMMARY TEXT"/>
If you website is static HTML, you'll have to do this for every page using your HTML editor.
If you're using a CMS like Drupal, you can automate a lot of it (see above link). If you use wordpress, you can probably implement something similar using the Drupal example as a guideline. I hope you found these useful.
Finally, you can always manually edit your share posts. See this example with illustrations.
Use the "not" selector.
For example, instead of:
$(".thumbs").hover()
try:
$(".thumbs:not(.selected)").hover()
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/
In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.
Hope this helps!
-Dave
Try Stretch="UniformToFill" on the Image
The following script creates nice thumbnails of all JPEG images preserving aspect ratios with 128x128 max resolution.
from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")
The new
and delete
operators can operate on classes and structures, whereas malloc
and free
only work with blocks of memory that need to be cast.
Using new/delete
will help to improve your code as you will not need to cast allocated memory to the required data structure.
There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.
Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.
Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.
This is actually one of the cases where I advise to read what Knuth has to say in The Art of Computer Programming, vol. 3. Another good read is Julienne Walker's The Art of Hashing.
I had the app with multiple subdomains and session cookie was the problem between those. Clearing the cookies resolved my problem.
Also, try setting the SESSION_DOMAIN
in .env file. Use the exact subdomain you are browsing.
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
try this
provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);
Bye.
You can use pmap to report memory usage.
Synopsis:
pmap [ -x | -d ] [ -q ] pids...
I have a better way:
http
.authorizeRequests()
.antMatchers("/api/v1/signup/**").permitAll()
.anyRequest().authenticated()
It depends on the nature of your site.
I happen to work on a bit of software where IP tracking is important, and within a field consumed by parter sites I'd guess some 20% - 40% of requests are either detectably spoofed IPs or headers blanked out, depending on the time of day and where they came from. For a site which gets organic traffic (i.e. not through partners) I'd expect a much higher ratio of good IPs.
As Kosi said, be careful what you're doing with this - IPs are in no way a reliable way to identify unique visitors.
First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)
Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with />
instead of just >
?
Given
<div id="This-is-the-real-id"></div>
then
function setText(id,newvalue) {
var s= document.getElementById(id);
s.innerHTML = newvalue;
}
window.onload=function() { // or window.addEventListener("load",function() {
setText("This-is-the-real-id","Hello there");
}
will do what you want
Given
<input id="This-is-the-real-id" type="text" value="">
then
function setValue(id,newvalue) {
var s= document.getElementById(id);
s.value = newvalue;
}
window.onload=function() {
setValue("This-is-the-real-id","Hello there");
}
will do what you want
function setContent(id, newvalue) {_x000D_
var s = document.getElementById(id);_x000D_
if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;_x000D_
else s.innerHTML = newvalue;_x000D_
_x000D_
}_x000D_
window.addEventListener("load", function() {_x000D_
setContent("This-is-the-real-id-div", "Hello there");_x000D_
setContent("This-is-the-real-id-input", "Hello there");_x000D_
})
_x000D_
<div id="This-is-the-real-id-div"></div>_x000D_
<input id="This-is-the-real-id-input" type="text" value="">
_x000D_
Select count(*) from table_name into @var1;
Select @var1;
No behaviors can be set by CSS. The only way to disable something in CSS is to make it invisible by either setting display:none
or simply putting div with transparent img all over it and changing their z-orders to disable user focusing on it with mouse. Even though, user will still be able to focus with tab from another field.
You can use JQuery also
$(document).ready(function () {
$('#personlist').val("10");
}
I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.
First, create a page with all the navigation bar's HTML content.
Next, use jQuery's $.get
method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html
and added a placeholder tag (Like <div id="nav-placeholder">
) in your index.html
, then you would use the following code:
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
$("#nav-placeholder").replaceWith(data);
});
</script>
No, there isn't.
<br>
is an HTML ELEMENT. It can't be replaced by a text node or part of a text node.
You can create a new-line effect using CR/LF inside a <pre>
element like below:
<pre>Line 1_x000D_
Line 2</pre>
_x000D_
But this is not the same as a <br>
.
Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)
I was able to apply a background below the Scaffold
(and even it's AppBar
) by putting the Scaffold
under a Stack
and setting a Container
in the first "layer" with the background image set and fit: BoxFit.cover
property.
Both the Scaffold
and AppBar
has to have the backgroundColor
set as Color.transparent
and the elevation
of AppBar
has to be 0 (zero).
Voilà! Now you have a nice background below the whole Scaffold and AppBar! :)
import 'package:flutter/material.dart';
import 'package:mynamespace/ui/shared/colors.dart';
import 'package:mynamespace/ui/shared/textstyle.dart';
import 'package:mynamespace/ui/shared/ui_helpers.dart';
import 'package:mynamespace/ui/widgets/custom_text_form_field_widget.dart';
class SignUpView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack( // <-- STACK AS THE SCAFFOLD PARENT
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"), // <-- BACKGROUND IMAGE
fit: BoxFit.cover,
),
),
),
Scaffold(
backgroundColor: Colors.transparent, // <-- SCAFFOLD WITH TRANSPARENT BG
appBar: AppBar(
title: Text('NEW USER'),
backgroundColor: Colors.transparent, // <-- APPBAR WITH TRANSPARENT BG
elevation: 0, // <-- ELEVATION ZEROED
),
body: Padding(
padding: EdgeInsets.all(spaceXS),
child: Column(
children: [
CustomTextFormFieldWidget(labelText: 'Email', hintText: 'Type your Email'),
UIHelper.verticalSpaceSM,
SizedBox(
width: double.maxFinite,
child: RaisedButton(
color: regularCyan,
child: Text('Finish Registration', style: TextStyle(color: white)),
onPressed: () => {},
),
),
],
),
),
),
],
);
}
}
While there are two excellent answers telling you how to do it, I feel that another answer is missing: In most cases you shouldn't do it at all.
Arrays are cumbersome, in most cases you are better off using the Collection API.
With Collections, you can add and remove elements and there are specialized Collections for different functionality (index-based lookup, sorting, uniqueness, FIFO-access, concurrency etc.).
While it's of course good and important to know about Arrays and their usage, in most cases using Collections makes APIs a lot more manageable (which is why new libraries like Google Guava hardly use Arrays at all).
So, for your scenario, I'd prefer a List of Lists, and I'd create it using Guava:
List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
The original conio.h was implemented by Borland, so its not a part of the C Standard Library nor is defined by POSIX.
But here is an implementation for Linux that uses ncurses to do the job.
Here's a good article on how to use selectors with lists.
Instead of setting it to be the android:background of the ListView, I believe you want to set android:listSelector as shown below:
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:divider="@null"
android:dividerHeight="0dip"
android:listSelector="@drawable/list_selector" />
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
Take a look at Phil Haack's post on model binding JSON data. The problem is that the default model binder doesn't serialize JSON properly. You need some sort of ValueProvider OR you could write a custom model binder:
using System.IO;
using System.Web.Script.Serialization;
public class JsonModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if(!IsJSONRequest(controllerContext)) {
return base.BindModel(controllerContext, bindingContext);
}
// Get the JSON data that's been posted
var request = controllerContext.HttpContext.Request;
//in some setups there is something that already reads the input stream if content type = 'application/json', so seek to the begining
request.InputStream.Seek(0, SeekOrigin.Begin);
var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();
// Use the built-in serializer to do the work for us
return new JavaScriptSerializer()
.Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
// -- REQUIRES .NET4
// If you want to use the .NET4 version of this, change the target framework and uncomment the line below
// and comment out the above return statement
//return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
}
private static bool IsJSONRequest(ControllerContext controllerContext) {
var contentType = controllerContext.HttpContext.Request.ContentType;
return contentType.Contains("application/json");
}
}
public static class JavaScriptSerializerExt {
public static object Deserialize(this JavaScriptSerializer serializer, string input, Type objType) {
var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
// internal static method to do the work for us
//Deserialize(this, input, null, this.RecursionLimit);
return deserializerMethod.Invoke(serializer,
new object[] { serializer, input, objType, serializer.RecursionLimit });
}
}
And tell MVC to use it in your Global.asax file:
ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
Also, this code makes use of the content type = 'application/json' so make sure you set that in jquery like so:
$.ajax({
dataType: "json",
contentType: "application/json",
type: 'POST',
url: '/Controller/Action',
data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});
Try to run either
SELECT USER();
or
SELECT CURRENT_USER();
It can sometimes be different, USER() will return by which login you attempted to authenticate and CURRENT_USER() will return how you were actually allowed to authenticate.
$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)
I tried scrolling="no" in my current browser (Google Chrome Version 60.0.3112.113 (Official Build) (64-bit)) and that didn't work. However, scroll="no" did work. Might be worth trying
<iframe src="<<URL>>" height="800" width="800" sandbox="allow-same-origin allow-scripts allow-forms" scroll="no" style="overflow: hidden"></iframe>
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.
If you don't want to be dependent on static timezone list, or want to display the offset along with timezone.
Here is what I came up with
function timezones()
{
$timezones = \DateTimeZone::listIdentifiers();
$items = array();
foreach($timezones as $timezoneId) {
$timezone = new \DateTimeZone($timezoneId);
$offsetInSeconds = $timezone->getOffset(new \DateTime());
$items[$timezoneId] = $offsetInSeconds;
}
asort($items);
array_walk ($items, function (&$offsetInSeconds, &$timezoneId) {
$offsetPrefix = $offsetInSeconds < 0 ? '-' : '+';
$offset = gmdate('H:i', abs($offsetInSeconds));
$offset = "(GMT${offsetPrefix}${offset}) ".$timezoneId;
$offsetInSeconds = $offset;
});
return $items;
}
Which gives me the following result
Array
(
[Pacific/Midway] => (GMT-11:00) Pacific/Midway
[Pacific/Pago_Pago] => (GMT-11:00) Pacific/Pago_Pago
[Pacific/Niue] => (GMT-11:00) Pacific/Niue
[America/Adak] => (GMT-10:00) America/Adak
[Pacific/Tahiti] => (GMT-10:00) Pacific/Tahiti
[Pacific/Rarotonga] => (GMT-10:00) Pacific/Rarotonga
[Pacific/Honolulu] => (GMT-10:00) Pacific/Honolulu
[Pacific/Marquesas] => (GMT-09:30) Pacific/Marquesas
[America/Sitka] => (GMT-09:00) America/Sitka
[Pacific/Gambier] => (GMT-09:00) Pacific/Gambier
[America/Yakutat] => (GMT-09:00) America/Yakutat
[America/Juneau] => (GMT-09:00) America/Juneau
[America/Nome] => (GMT-09:00) America/Nome
[America/Anchorage] => (GMT-09:00) America/Anchorage
[America/Metlakatla] => (GMT-09:00) America/Metlakatla
[America/Los_Angeles] => (GMT-08:00) America/Los_Angeles
[America/Tijuana] => (GMT-08:00) America/Tijuana
[America/Whitehorse] => (GMT-08:00) America/Whitehorse
[America/Vancouver] => (GMT-08:00) America/Vancouver
[America/Dawson] => (GMT-08:00) America/Dawson
[Pacific/Pitcairn] => (GMT-08:00) Pacific/Pitcairn
[America/Mazatlan] => (GMT-07:00) America/Mazatlan
[America/Fort_Nelson] => (GMT-07:00) America/Fort_Nelson
[America/Yellowknife] => (GMT-07:00) America/Yellowknife
[America/Inuvik] => (GMT-07:00) America/Inuvik
[America/Edmonton] => (GMT-07:00) America/Edmonton
[America/Denver] => (GMT-07:00) America/Denver
[America/Chihuahua] => (GMT-07:00) America/Chihuahua
[America/Boise] => (GMT-07:00) America/Boise
[America/Ojinaga] => (GMT-07:00) America/Ojinaga
[America/Cambridge_Bay] => (GMT-07:00) America/Cambridge_Bay
[America/Dawson_Creek] => (GMT-07:00) America/Dawson_Creek
[America/Phoenix] => (GMT-07:00) America/Phoenix
[America/Hermosillo] => (GMT-07:00) America/Hermosillo
[America/Creston] => (GMT-07:00) America/Creston
[America/Matamoros] => (GMT-06:00) America/Matamoros
[America/Menominee] => (GMT-06:00) America/Menominee
[America/Indiana/Knox] => (GMT-06:00) America/Indiana/Knox
[America/Managua] => (GMT-06:00) America/Managua
[America/Bahia_Banderas] => (GMT-06:00) America/Bahia_Banderas
[America/Indiana/Tell_City] => (GMT-06:00) America/Indiana/Tell_City
[America/Belize] => (GMT-06:00) America/Belize
[America/Chicago] => (GMT-06:00) America/Chicago
[America/Guatemala] => (GMT-06:00) America/Guatemala
[America/El_Salvador] => (GMT-06:00) America/El_Salvador
[America/Merida] => (GMT-06:00) America/Merida
[America/Costa_Rica] => (GMT-06:00) America/Costa_Rica
[America/Mexico_City] => (GMT-06:00) America/Mexico_City
[America/Winnipeg] => (GMT-06:00) America/Winnipeg
[Pacific/Galapagos] => (GMT-06:00) Pacific/Galapagos
[America/Resolute] => (GMT-06:00) America/Resolute
[America/Regina] => (GMT-06:00) America/Regina
[America/Rankin_Inlet] => (GMT-06:00) America/Rankin_Inlet
[America/Rainy_River] => (GMT-06:00) America/Rainy_River
[America/North_Dakota/New_Salem] => (GMT-06:00) America/North_Dakota/New_Salem
[America/North_Dakota/Beulah] => (GMT-06:00) America/North_Dakota/Beulah
[America/North_Dakota/Center] => (GMT-06:00) America/North_Dakota/Center
[America/Tegucigalpa] => (GMT-06:00) America/Tegucigalpa
[America/Swift_Current] => (GMT-06:00) America/Swift_Current
[America/Monterrey] => (GMT-06:00) America/Monterrey
[America/Pangnirtung] => (GMT-05:00) America/Pangnirtung
[America/Indiana/Petersburg] => (GMT-05:00) America/Indiana/Petersburg
[America/Indiana/Marengo] => (GMT-05:00) America/Indiana/Marengo
[America/Bogota] => (GMT-05:00) America/Bogota
[America/Toronto] => (GMT-05:00) America/Toronto
[America/Detroit] => (GMT-05:00) America/Detroit
[America/Panama] => (GMT-05:00) America/Panama
[America/Cancun] => (GMT-05:00) America/Cancun
[America/Rio_Branco] => (GMT-05:00) America/Rio_Branco
[America/Port-au-Prince] => (GMT-05:00) America/Port-au-Prince
[America/Cayman] => (GMT-05:00) America/Cayman
[America/Grand_Turk] => (GMT-05:00) America/Grand_Turk
[America/Havana] => (GMT-05:00) America/Havana
[America/Indiana/Indianapolis] => (GMT-05:00) America/Indiana/Indianapolis
[America/Indiana/Vevay] => (GMT-05:00) America/Indiana/Vevay
[America/Guayaquil] => (GMT-05:00) America/Guayaquil
[America/Nipigon] => (GMT-05:00) America/Nipigon
[America/Indiana/Vincennes] => (GMT-05:00) America/Indiana/Vincennes
[America/Atikokan] => (GMT-05:00) America/Atikokan
[America/Indiana/Winamac] => (GMT-05:00) America/Indiana/Winamac
[America/New_York] => (GMT-05:00) America/New_York
[America/Iqaluit] => (GMT-05:00) America/Iqaluit
[America/Jamaica] => (GMT-05:00) America/Jamaica
[America/Nassau] => (GMT-05:00) America/Nassau
[America/Kentucky/Louisville] => (GMT-05:00) America/Kentucky/Louisville
[America/Kentucky/Monticello] => (GMT-05:00) America/Kentucky/Monticello
[America/Eirunepe] => (GMT-05:00) America/Eirunepe
[Pacific/Easter] => (GMT-05:00) Pacific/Easter
[America/Lima] => (GMT-05:00) America/Lima
[America/Thunder_Bay] => (GMT-05:00) America/Thunder_Bay
[America/Guadeloupe] => (GMT-04:00) America/Guadeloupe
[America/Manaus] => (GMT-04:00) America/Manaus
[America/Guyana] => (GMT-04:00) America/Guyana
[America/Halifax] => (GMT-04:00) America/Halifax
[America/Puerto_Rico] => (GMT-04:00) America/Puerto_Rico
[America/Porto_Velho] => (GMT-04:00) America/Porto_Velho
[America/Port_of_Spain] => (GMT-04:00) America/Port_of_Spain
[America/Montserrat] => (GMT-04:00) America/Montserrat
[America/Moncton] => (GMT-04:00) America/Moncton
[America/Martinique] => (GMT-04:00) America/Martinique
[America/Kralendijk] => (GMT-04:00) America/Kralendijk
[America/La_Paz] => (GMT-04:00) America/La_Paz
[America/Marigot] => (GMT-04:00) America/Marigot
[America/Lower_Princes] => (GMT-04:00) America/Lower_Princes
[America/Grenada] => (GMT-04:00) America/Grenada
[America/Santo_Domingo] => (GMT-04:00) America/Santo_Domingo
[America/Goose_Bay] => (GMT-04:00) America/Goose_Bay
[America/Caracas] => (GMT-04:00) America/Caracas
[America/Anguilla] => (GMT-04:00) America/Anguilla
[America/St_Barthelemy] => (GMT-04:00) America/St_Barthelemy
[America/Barbados] => (GMT-04:00) America/Barbados
[America/St_Kitts] => (GMT-04:00) America/St_Kitts
[America/Blanc-Sablon] => (GMT-04:00) America/Blanc-Sablon
[America/Boa_Vista] => (GMT-04:00) America/Boa_Vista
[America/St_Lucia] => (GMT-04:00) America/St_Lucia
[America/St_Thomas] => (GMT-04:00) America/St_Thomas
[America/Antigua] => (GMT-04:00) America/Antigua
[America/St_Vincent] => (GMT-04:00) America/St_Vincent
[America/Thule] => (GMT-04:00) America/Thule
[America/Curacao] => (GMT-04:00) America/Curacao
[America/Tortola] => (GMT-04:00) America/Tortola
[America/Dominica] => (GMT-04:00) America/Dominica
[Atlantic/Bermuda] => (GMT-04:00) Atlantic/Bermuda
[America/Glace_Bay] => (GMT-04:00) America/Glace_Bay
[America/Aruba] => (GMT-04:00) America/Aruba
[America/St_Johns] => (GMT-03:30) America/St_Johns
[America/Argentina/Tucuman] => (GMT-03:00) America/Argentina/Tucuman
[America/Belem] => (GMT-03:00) America/Belem
[America/Santiago] => (GMT-03:00) America/Santiago
[America/Santarem] => (GMT-03:00) America/Santarem
[America/Recife] => (GMT-03:00) America/Recife
[America/Punta_Arenas] => (GMT-03:00) America/Punta_Arenas
[Atlantic/Stanley] => (GMT-03:00) Atlantic/Stanley
[America/Paramaribo] => (GMT-03:00) America/Paramaribo
[America/Fortaleza] => (GMT-03:00) America/Fortaleza
[America/Argentina/San_Luis] => (GMT-03:00) America/Argentina/San_Luis
[Antarctica/Palmer] => (GMT-03:00) Antarctica/Palmer
[America/Montevideo] => (GMT-03:00) America/Montevideo
[America/Cuiaba] => (GMT-03:00) America/Cuiaba
[America/Miquelon] => (GMT-03:00) America/Miquelon
[America/Cayenne] => (GMT-03:00) America/Cayenne
[America/Campo_Grande] => (GMT-03:00) America/Campo_Grande
[Antarctica/Rothera] => (GMT-03:00) Antarctica/Rothera
[America/Godthab] => (GMT-03:00) America/Godthab
[America/Bahia] => (GMT-03:00) America/Bahia
[America/Asuncion] => (GMT-03:00) America/Asuncion
[America/Argentina/Ushuaia] => (GMT-03:00) America/Argentina/Ushuaia
[America/Argentina/La_Rioja] => (GMT-03:00) America/Argentina/La_Rioja
[America/Araguaina] => (GMT-03:00) America/Araguaina
[America/Argentina/Buenos_Aires] => (GMT-03:00) America/Argentina/Buenos_Aires
[America/Argentina/Rio_Gallegos] => (GMT-03:00) America/Argentina/Rio_Gallegos
[America/Argentina/Catamarca] => (GMT-03:00) America/Argentina/Catamarca
[America/Maceio] => (GMT-03:00) America/Maceio
[America/Argentina/San_Juan] => (GMT-03:00) America/Argentina/San_Juan
[America/Argentina/Salta] => (GMT-03:00) America/Argentina/Salta
[America/Argentina/Mendoza] => (GMT-03:00) America/Argentina/Mendoza
[America/Argentina/Cordoba] => (GMT-03:00) America/Argentina/Cordoba
[America/Argentina/Jujuy] => (GMT-03:00) America/Argentina/Jujuy
[Atlantic/South_Georgia] => (GMT-02:00) Atlantic/South_Georgia
[America/Noronha] => (GMT-02:00) America/Noronha
[America/Sao_Paulo] => (GMT-02:00) America/Sao_Paulo
[Atlantic/Cape_Verde] => (GMT-01:00) Atlantic/Cape_Verde
[Atlantic/Azores] => (GMT-01:00) Atlantic/Azores
[America/Scoresbysund] => (GMT-01:00) America/Scoresbysund
[Europe/Lisbon] => (GMT+00:00) Europe/Lisbon
[Europe/London] => (GMT+00:00) Europe/London
[Europe/Jersey] => (GMT+00:00) Europe/Jersey
[Europe/Isle_of_Man] => (GMT+00:00) Europe/Isle_of_Man
[Atlantic/Faroe] => (GMT+00:00) Atlantic/Faroe
[Europe/Guernsey] => (GMT+00:00) Europe/Guernsey
[Europe/Dublin] => (GMT+00:00) Europe/Dublin
[Atlantic/St_Helena] => (GMT+00:00) Atlantic/St_Helena
[Atlantic/Reykjavik] => (GMT+00:00) Atlantic/Reykjavik
[Atlantic/Madeira] => (GMT+00:00) Atlantic/Madeira
[Atlantic/Canary] => (GMT+00:00) Atlantic/Canary
[Africa/Accra] => (GMT+00:00) Africa/Accra
[Antarctica/Troll] => (GMT+00:00) Antarctica/Troll
[Africa/Abidjan] => (GMT+00:00) Africa/Abidjan
[UTC] => (GMT+00:00) UTC
[America/Danmarkshavn] => (GMT+00:00) America/Danmarkshavn
[Africa/Monrovia] => (GMT+00:00) Africa/Monrovia
[Africa/Dakar] => (GMT+00:00) Africa/Dakar
[Africa/Conakry] => (GMT+00:00) Africa/Conakry
[Africa/Casablanca] => (GMT+00:00) Africa/Casablanca
[Africa/Lome] => (GMT+00:00) Africa/Lome
[Africa/Freetown] => (GMT+00:00) Africa/Freetown
[Africa/El_Aaiun] => (GMT+00:00) Africa/El_Aaiun
[Africa/Bissau] => (GMT+00:00) Africa/Bissau
[Africa/Nouakchott] => (GMT+00:00) Africa/Nouakchott
[Africa/Banjul] => (GMT+00:00) Africa/Banjul
[Africa/Ouagadougou] => (GMT+00:00) Africa/Ouagadougou
[Africa/Bamako] => (GMT+00:00) Africa/Bamako
[Europe/Gibraltar] => (GMT+01:00) Europe/Gibraltar
[Africa/Bangui] => (GMT+01:00) Africa/Bangui
[Europe/Ljubljana] => (GMT+01:00) Europe/Ljubljana
[Africa/Ceuta] => (GMT+01:00) Africa/Ceuta
[Africa/Algiers] => (GMT+01:00) Africa/Algiers
[Europe/Busingen] => (GMT+01:00) Europe/Busingen
[Europe/Copenhagen] => (GMT+01:00) Europe/Copenhagen
[Europe/Madrid] => (GMT+01:00) Europe/Madrid
[Europe/Budapest] => (GMT+01:00) Europe/Budapest
[Europe/Brussels] => (GMT+01:00) Europe/Brussels
[Europe/Bratislava] => (GMT+01:00) Europe/Bratislava
[Europe/Berlin] => (GMT+01:00) Europe/Berlin
[Europe/Belgrade] => (GMT+01:00) Europe/Belgrade
[Europe/Andorra] => (GMT+01:00) Europe/Andorra
[Europe/Amsterdam] => (GMT+01:00) Europe/Amsterdam
[Europe/Luxembourg] => (GMT+01:00) Europe/Luxembourg
[Europe/Monaco] => (GMT+01:00) Europe/Monaco
[Europe/Malta] => (GMT+01:00) Europe/Malta
[Europe/Tirane] => (GMT+01:00) Europe/Tirane
[Europe/Zurich] => (GMT+01:00) Europe/Zurich
[Europe/Zagreb] => (GMT+01:00) Europe/Zagreb
[Europe/Warsaw] => (GMT+01:00) Europe/Warsaw
[Europe/Vienna] => (GMT+01:00) Europe/Vienna
[Europe/Vatican] => (GMT+01:00) Europe/Vatican
[Europe/Vaduz] => (GMT+01:00) Europe/Vaduz
[Europe/Stockholm] => (GMT+01:00) Europe/Stockholm
[Africa/Brazzaville] => (GMT+01:00) Africa/Brazzaville
[Europe/Skopje] => (GMT+01:00) Europe/Skopje
[Europe/Sarajevo] => (GMT+01:00) Europe/Sarajevo
[Europe/San_Marino] => (GMT+01:00) Europe/San_Marino
[Europe/Rome] => (GMT+01:00) Europe/Rome
[Europe/Prague] => (GMT+01:00) Europe/Prague
[Europe/Paris] => (GMT+01:00) Europe/Paris
[Europe/Oslo] => (GMT+01:00) Europe/Oslo
[Europe/Podgorica] => (GMT+01:00) Europe/Podgorica
[Africa/Douala] => (GMT+01:00) Africa/Douala
[Arctic/Longyearbyen] => (GMT+01:00) Arctic/Longyearbyen
[Africa/Malabo] => (GMT+01:00) Africa/Malabo
[Africa/Kinshasa] => (GMT+01:00) Africa/Kinshasa
[Africa/Libreville] => (GMT+01:00) Africa/Libreville
[Africa/Ndjamena] => (GMT+01:00) Africa/Ndjamena
[Africa/Lagos] => (GMT+01:00) Africa/Lagos
[Africa/Niamey] => (GMT+01:00) Africa/Niamey
[Africa/Porto-Novo] => (GMT+01:00) Africa/Porto-Novo
[Africa/Sao_Tome] => (GMT+01:00) Africa/Sao_Tome
[Africa/Luanda] => (GMT+01:00) Africa/Luanda
[Africa/Tunis] => (GMT+01:00) Africa/Tunis
[Europe/Uzhgorod] => (GMT+02:00) Europe/Uzhgorod
[Africa/Harare] => (GMT+02:00) Africa/Harare
[Europe/Mariehamn] => (GMT+02:00) Europe/Mariehamn
[Africa/Lubumbashi] => (GMT+02:00) Africa/Lubumbashi
[Asia/Nicosia] => (GMT+02:00) Asia/Nicosia
[Africa/Windhoek] => (GMT+02:00) Africa/Windhoek
[Europe/Tallinn] => (GMT+02:00) Europe/Tallinn
[Europe/Zaporozhye] => (GMT+02:00) Europe/Zaporozhye
[Africa/Gaborone] => (GMT+02:00) Africa/Gaborone
[Africa/Mbabane] => (GMT+02:00) Africa/Mbabane
[Africa/Khartoum] => (GMT+02:00) Africa/Khartoum
[Africa/Johannesburg] => (GMT+02:00) Africa/Johannesburg
[Europe/Vilnius] => (GMT+02:00) Europe/Vilnius
[Africa/Maseru] => (GMT+02:00) Africa/Maseru
[Africa/Lusaka] => (GMT+02:00) Africa/Lusaka
[Europe/Riga] => (GMT+02:00) Europe/Riga
[Africa/Kigali] => (GMT+02:00) Africa/Kigali
[Europe/Helsinki] => (GMT+02:00) Europe/Helsinki
[Africa/Maputo] => (GMT+02:00) Africa/Maputo
[Europe/Chisinau] => (GMT+02:00) Europe/Chisinau
[Europe/Sofia] => (GMT+02:00) Europe/Sofia
[Asia/Beirut] => (GMT+02:00) Asia/Beirut
[Africa/Blantyre] => (GMT+02:00) Africa/Blantyre
[Asia/Jerusalem] => (GMT+02:00) Asia/Jerusalem
[Asia/Gaza] => (GMT+02:00) Asia/Gaza
[Asia/Amman] => (GMT+02:00) Asia/Amman
[Asia/Famagusta] => (GMT+02:00) Asia/Famagusta
[Europe/Athens] => (GMT+02:00) Europe/Athens
[Africa/Bujumbura] => (GMT+02:00) Africa/Bujumbura
[Asia/Hebron] => (GMT+02:00) Asia/Hebron
[Europe/Kaliningrad] => (GMT+02:00) Europe/Kaliningrad
[Africa/Cairo] => (GMT+02:00) Africa/Cairo
[Europe/Kiev] => (GMT+02:00) Europe/Kiev
[Europe/Bucharest] => (GMT+02:00) Europe/Bucharest
[Asia/Damascus] => (GMT+02:00) Asia/Damascus
[Africa/Tripoli] => (GMT+02:00) Africa/Tripoli
[Asia/Baghdad] => (GMT+03:00) Asia/Baghdad
[Africa/Djibouti] => (GMT+03:00) Africa/Djibouti
[Asia/Aden] => (GMT+03:00) Asia/Aden
[Asia/Bahrain] => (GMT+03:00) Asia/Bahrain
[Europe/Istanbul] => (GMT+03:00) Europe/Istanbul
[Africa/Juba] => (GMT+03:00) Africa/Juba
[Europe/Kirov] => (GMT+03:00) Europe/Kirov
[Europe/Moscow] => (GMT+03:00) Europe/Moscow
[Antarctica/Syowa] => (GMT+03:00) Antarctica/Syowa
[Europe/Minsk] => (GMT+03:00) Europe/Minsk
[Africa/Kampala] => (GMT+03:00) Africa/Kampala
[Africa/Dar_es_Salaam] => (GMT+03:00) Africa/Dar_es_Salaam
[Europe/Simferopol] => (GMT+03:00) Europe/Simferopol
[Asia/Riyadh] => (GMT+03:00) Asia/Riyadh
[Indian/Antananarivo] => (GMT+03:00) Indian/Antananarivo
[Asia/Kuwait] => (GMT+03:00) Asia/Kuwait
[Africa/Nairobi] => (GMT+03:00) Africa/Nairobi
[Indian/Mayotte] => (GMT+03:00) Indian/Mayotte
[Africa/Mogadishu] => (GMT+03:00) Africa/Mogadishu
[Asia/Qatar] => (GMT+03:00) Asia/Qatar
[Europe/Volgograd] => (GMT+03:00) Europe/Volgograd
[Africa/Asmara] => (GMT+03:00) Africa/Asmara
[Africa/Addis_Ababa] => (GMT+03:00) Africa/Addis_Ababa
[Indian/Comoro] => (GMT+03:00) Indian/Comoro
[Asia/Tehran] => (GMT+03:30) Asia/Tehran
[Europe/Saratov] => (GMT+04:00) Europe/Saratov
[Indian/Reunion] => (GMT+04:00) Indian/Reunion
[Europe/Astrakhan] => (GMT+04:00) Europe/Astrakhan
[Asia/Baku] => (GMT+04:00) Asia/Baku
[Asia/Dubai] => (GMT+04:00) Asia/Dubai
[Indian/Mauritius] => (GMT+04:00) Indian/Mauritius
[Indian/Mahe] => (GMT+04:00) Indian/Mahe
[Asia/Tbilisi] => (GMT+04:00) Asia/Tbilisi
[Asia/Yerevan] => (GMT+04:00) Asia/Yerevan
[Asia/Muscat] => (GMT+04:00) Asia/Muscat
[Europe/Samara] => (GMT+04:00) Europe/Samara
[Europe/Ulyanovsk] => (GMT+04:00) Europe/Ulyanovsk
[Asia/Kabul] => (GMT+04:30) Asia/Kabul
[Antarctica/Mawson] => (GMT+05:00) Antarctica/Mawson
[Asia/Samarkand] => (GMT+05:00) Asia/Samarkand
[Asia/Aqtobe] => (GMT+05:00) Asia/Aqtobe
[Indian/Maldives] => (GMT+05:00) Indian/Maldives
[Asia/Ashgabat] => (GMT+05:00) Asia/Ashgabat
[Asia/Atyrau] => (GMT+05:00) Asia/Atyrau
[Asia/Dushanbe] => (GMT+05:00) Asia/Dushanbe
[Asia/Yekaterinburg] => (GMT+05:00) Asia/Yekaterinburg
[Asia/Oral] => (GMT+05:00) Asia/Oral
[Asia/Aqtau] => (GMT+05:00) Asia/Aqtau
[Asia/Karachi] => (GMT+05:00) Asia/Karachi
[Asia/Tashkent] => (GMT+05:00) Asia/Tashkent
[Indian/Kerguelen] => (GMT+05:00) Indian/Kerguelen
[Asia/Colombo] => (GMT+05:30) Asia/Colombo
[Asia/Kolkata] => (GMT+05:30) Asia/Kolkata
[Asia/Kathmandu] => (GMT+05:45) Asia/Kathmandu
[Antarctica/Vostok] => (GMT+06:00) Antarctica/Vostok
[Indian/Chagos] => (GMT+06:00) Indian/Chagos
[Asia/Almaty] => (GMT+06:00) Asia/Almaty
[Asia/Omsk] => (GMT+06:00) Asia/Omsk
[Asia/Dhaka] => (GMT+06:00) Asia/Dhaka
[Asia/Bishkek] => (GMT+06:00) Asia/Bishkek
[Asia/Urumqi] => (GMT+06:00) Asia/Urumqi
[Asia/Thimphu] => (GMT+06:00) Asia/Thimphu
[Asia/Qyzylorda] => (GMT+06:00) Asia/Qyzylorda
[Indian/Cocos] => (GMT+06:30) Indian/Cocos
[Asia/Yangon] => (GMT+06:30) Asia/Yangon
[Asia/Novokuznetsk] => (GMT+07:00) Asia/Novokuznetsk
[Asia/Barnaul] => (GMT+07:00) Asia/Barnaul
[Antarctica/Davis] => (GMT+07:00) Antarctica/Davis
[Asia/Novosibirsk] => (GMT+07:00) Asia/Novosibirsk
[Asia/Krasnoyarsk] => (GMT+07:00) Asia/Krasnoyarsk
[Asia/Phnom_Penh] => (GMT+07:00) Asia/Phnom_Penh
[Asia/Pontianak] => (GMT+07:00) Asia/Pontianak
[Asia/Jakarta] => (GMT+07:00) Asia/Jakarta
[Asia/Hovd] => (GMT+07:00) Asia/Hovd
[Asia/Tomsk] => (GMT+07:00) Asia/Tomsk
[Asia/Ho_Chi_Minh] => (GMT+07:00) Asia/Ho_Chi_Minh
[Asia/Vientiane] => (GMT+07:00) Asia/Vientiane
[Indian/Christmas] => (GMT+07:00) Indian/Christmas
[Asia/Bangkok] => (GMT+07:00) Asia/Bangkok
[Asia/Choibalsan] => (GMT+08:00) Asia/Choibalsan
[Asia/Taipei] => (GMT+08:00) Asia/Taipei
[Asia/Makassar] => (GMT+08:00) Asia/Makassar
[Asia/Macau] => (GMT+08:00) Asia/Macau
[Asia/Kuching] => (GMT+08:00) Asia/Kuching
[Asia/Kuala_Lumpur] => (GMT+08:00) Asia/Kuala_Lumpur
[Asia/Shanghai] => (GMT+08:00) Asia/Shanghai
[Asia/Singapore] => (GMT+08:00) Asia/Singapore
[Asia/Brunei] => (GMT+08:00) Asia/Brunei
[Asia/Irkutsk] => (GMT+08:00) Asia/Irkutsk
[Asia/Ulaanbaatar] => (GMT+08:00) Asia/Ulaanbaatar
[Australia/Perth] => (GMT+08:00) Australia/Perth
[Asia/Hong_Kong] => (GMT+08:00) Asia/Hong_Kong
[Antarctica/Casey] => (GMT+08:00) Antarctica/Casey
[Asia/Manila] => (GMT+08:00) Asia/Manila
[Australia/Eucla] => (GMT+08:45) Australia/Eucla
[Asia/Jayapura] => (GMT+09:00) Asia/Jayapura
[Asia/Khandyga] => (GMT+09:00) Asia/Khandyga
[Pacific/Palau] => (GMT+09:00) Pacific/Palau
[Asia/Dili] => (GMT+09:00) Asia/Dili
[Asia/Yakutsk] => (GMT+09:00) Asia/Yakutsk
[Asia/Tokyo] => (GMT+09:00) Asia/Tokyo
[Asia/Seoul] => (GMT+09:00) Asia/Seoul
[Asia/Chita] => (GMT+09:00) Asia/Chita
[Asia/Pyongyang] => (GMT+09:00) Asia/Pyongyang
[Australia/Darwin] => (GMT+09:30) Australia/Darwin
[Asia/Ust-Nera] => (GMT+10:00) Asia/Ust-Nera
[Pacific/Chuuk] => (GMT+10:00) Pacific/Chuuk
[Antarctica/DumontDUrville] => (GMT+10:00) Antarctica/DumontDUrville
[Pacific/Guam] => (GMT+10:00) Pacific/Guam
[Pacific/Port_Moresby] => (GMT+10:00) Pacific/Port_Moresby
[Asia/Vladivostok] => (GMT+10:00) Asia/Vladivostok
[Australia/Brisbane] => (GMT+10:00) Australia/Brisbane
[Australia/Lindeman] => (GMT+10:00) Australia/Lindeman
[Pacific/Saipan] => (GMT+10:00) Pacific/Saipan
[Australia/Adelaide] => (GMT+10:30) Australia/Adelaide
[Australia/Broken_Hill] => (GMT+10:30) Australia/Broken_Hill
[Australia/Sydney] => (GMT+11:00) Australia/Sydney
[Antarctica/Macquarie] => (GMT+11:00) Antarctica/Macquarie
[Pacific/Noumea] => (GMT+11:00) Pacific/Noumea
[Pacific/Norfolk] => (GMT+11:00) Pacific/Norfolk
[Australia/Melbourne] => (GMT+11:00) Australia/Melbourne
[Pacific/Kosrae] => (GMT+11:00) Pacific/Kosrae
[Pacific/Pohnpei] => (GMT+11:00) Pacific/Pohnpei
[Australia/Currie] => (GMT+11:00) Australia/Currie
[Pacific/Guadalcanal] => (GMT+11:00) Pacific/Guadalcanal
[Pacific/Efate] => (GMT+11:00) Pacific/Efate
[Australia/Hobart] => (GMT+11:00) Australia/Hobart
[Asia/Magadan] => (GMT+11:00) Asia/Magadan
[Asia/Sakhalin] => (GMT+11:00) Asia/Sakhalin
[Pacific/Bougainville] => (GMT+11:00) Pacific/Bougainville
[Australia/Lord_Howe] => (GMT+11:00) Australia/Lord_Howe
[Asia/Srednekolymsk] => (GMT+11:00) Asia/Srednekolymsk
[Pacific/Fiji] => (GMT+12:00) Pacific/Fiji
[Pacific/Wake] => (GMT+12:00) Pacific/Wake
[Pacific/Nauru] => (GMT+12:00) Pacific/Nauru
[Pacific/Majuro] => (GMT+12:00) Pacific/Majuro
[Asia/Kamchatka] => (GMT+12:00) Asia/Kamchatka
[Pacific/Kwajalein] => (GMT+12:00) Pacific/Kwajalein
[Pacific/Funafuti] => (GMT+12:00) Pacific/Funafuti
[Pacific/Wallis] => (GMT+12:00) Pacific/Wallis
[Asia/Anadyr] => (GMT+12:00) Asia/Anadyr
[Pacific/Tarawa] => (GMT+12:00) Pacific/Tarawa
[Pacific/Fakaofo] => (GMT+13:00) Pacific/Fakaofo
[Pacific/Enderbury] => (GMT+13:00) Pacific/Enderbury
[Pacific/Auckland] => (GMT+13:00) Pacific/Auckland
[Antarctica/McMurdo] => (GMT+13:00) Antarctica/McMurdo
[Pacific/Tongatapu] => (GMT+13:00) Pacific/Tongatapu
[Pacific/Chatham] => (GMT+13:45) Pacific/Chatham
[Pacific/Kiritimati] => (GMT+14:00) Pacific/Kiritimati
[Pacific/Apia] => (GMT+14:00) Pacific/Apia
)
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
dplyr >= 1.0.0
In newer versions of dplyr
you can use rowwise()
along with c_across
to perform row-wise aggregation for functions that do not have specific row-wise variants, but if the row-wise variant exists it should be faster.
Since rowwise()
is just a special form of grouping and changes the way verbs work you'll likely want to pipe it to ungroup()
after doing your row-wise operation.
To select a range of rows:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumrange = sum(dplyr::c_across(x1:x5), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
To select rows by type:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumnumeric = sum(c_across(where(is.numeric)), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
In your specific case a row-wise variant exists so you can do the following (note the use of across
instead):
df %>%
dplyr::mutate(sumrow = rowSums(dplyr::across(x1:x5), na.rm = T))
For more information see the page on rowwise.
private boolean isAppExist() {
PackageManager pm = getPackageManager();
try {
PackageInfo info = pm.getPackageInfo("com.facebook.katana", PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}
if (isFacebookExist()) {showToast(" Facebook is install.");}
else {showToast(" Facebook is not install.");}
How about this approach (c#)?
private int dividedBy3(int n) {
List<Object> a = new Object[n].ToList();
List<Object> b = new List<object>();
while (a.Count > 2) {
a.RemoveRange(0, 3);
b.Add(new Object());
}
return b.Count;
}
The struct's name is ReducedForm
; you need to make an object (instance of the struct
or class
) and use that. Do this:
ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;
$(function() _x000D_
{_x000D_
$( "#element" ).draggable({ snap: ".ui-widget-header",grid: [ 1, 1 ]});_x000D_
});_x000D_
$(document).ready(function() {_x000D_
$("#element").draggable({ _x000D_
containment: '#snaptarget', _x000D_
scroll: false_x000D_
}).mousemove(function(){_x000D_
var coord = $(this).position();_x000D_
var width = $(this).width();_x000D_
var height = $(this).height();_x000D_
$("p.position").text( "(" + coord.left + "," + coord.top + ")" );_x000D_
$("p.size").text( "(" + width + "," + height + ")" );_x000D_
}).mouseup(function(){_x000D_
var coord = $(this).position();_x000D_
var width = $(this).width();_x000D_
var height = $(this).height();_x000D_
$.post('/test/layout_view.php', {x: coord.left, y: coord.top, w: width, h: height});_x000D_
_x000D_
});_x000D_
});
_x000D_
#element {background:#666;border:1px #000 solid;cursor:move;height:110px;width:110px;padding:10px 10px 10px 10px;}_x000D_
#snaptarget { height:610px; width:1000px;}_x000D_
.draggable { width: 90px; height: 80px; float: left; margin: 0 0 0 0; font-size: .9em; }_x000D_
.wrapper_x000D_
{ _x000D_
background-image:linear-gradient(0deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent), linear-gradient(90deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent);_x000D_
height:100%;_x000D_
background-size:45px 45px;_x000D_
border: 1px solid black;_x000D_
background-color: #434343;_x000D_
margin: 20px 0px 0px 20px;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Layout</title>_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
<link rel="stylesheet" href="../themes/default/css/test4.css" type="text/css" charset="utf-8"/>_x000D_
<script src="../themes/default/js/layout.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="snaptarget" class="wrapper">_x000D_
<div id="element" class="draggable ui-widget-content">_x000D_
<p class="position"></p>_x000D_
<p class="size"></p>_x000D_
</div>_x000D_
</div> _x000D_
<div></div>_x000D_
</body>_x000D_
</html>
_x000D_
you should not use Nested List in List.
List<List<T>>
is not legal, even if T were a defined type.
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
I have done some investigation and sharing my results here,this may be useful for others.
First, we can check whether MockSetting option is turned ON
public static boolean isMockSettingsON(Context context) {
// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
}
Second, we can check whether are there other apps in the device, which are using android.permission.ACCESS_MOCK_LOCATION
(Location Spoofing Apps)
public static boolean areThereMockPermissionApps(Context context) {
int count = 0;
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages =
pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
PackageManager.GET_PERMISSIONS);
// Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context.getPackageName())) {
count++;
}
}
}
} catch (NameNotFoundException e) {
Log.e("Got exception " , e.getMessage());
}
}
if (count > 0)
return true;
return false;
}
If both above methods, first and second are true, then there are good chances that location may be spoofed or fake.
Now, spoofing can be avoided by using Location Manager's API.
We can remove the test provider before requesting the location updates from both the providers (Network and GPS)
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Log.d(TAG ,"Removing Test providers")
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
} catch (IllegalArgumentException error) {
Log.d(TAG,"Got exception in removing test provider");
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
I have seen that removeTestProvider(~) works very well over Jelly Bean and onwards version. This API appeared to be unreliable till Ice Cream Sandwich.
Flutter Update:
Use Geolocator and check Position
object's isMocked
property.
Simply put, If you want to pull from GitHub the branch the_branch_I_want
:
git fetch origin
git branch -f the_branch_I_want origin/the_branch_I_want
git checkout the_branch_I_want
I need a fast function that can check if a file is exist or not and PherricOxide's answer is almost what I need except it does not compare the performance of boost::filesystem::exists and open functions. From the benchmark results we can easily see that :
Using stat function is the fastest way to check if a file is exist. Note that my results are consistent with that of PherricOxide's answer.
The performance of boost::filesystem::exists function is very close to that of stat function and it is also portable. I would recommend this solution if boost libraries is accessible from your code.
Benchmark results obtained with Linux kernel 4.17.0 and gcc-7.3:
2018-05-05 00:35:35
Running ./filesystem
Run on (8 X 2661 MHz CPU s)
CPU Caches:
L1 Data 32K (x4)
L1 Instruction 32K (x4)
L2 Unified 256K (x4)
L3 Unified 8192K (x1)
--------------------------------------------------
Benchmark Time CPU Iterations
--------------------------------------------------
use_stat 815 ns 813 ns 861291
use_open 2007 ns 1919 ns 346273
use_access 1186 ns 1006 ns 683024
use_boost 831 ns 830 ns 831233
Below is my benchmark code:
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include "boost/filesystem.hpp"
#include <benchmark/benchmark.h>
const std::string fname("filesystem.cpp");
struct stat buf;
// Use stat function
void use_stat(benchmark::State &state) {
for (auto _ : state) {
benchmark::DoNotOptimize(stat(fname.data(), &buf));
}
}
BENCHMARK(use_stat);
// Use open function
void use_open(benchmark::State &state) {
for (auto _ : state) {
int fd = open(fname.data(), O_RDONLY);
if (fd > -1) close(fd);
}
}
BENCHMARK(use_open);
// Use access function
void use_access(benchmark::State &state) {
for (auto _ : state) {
benchmark::DoNotOptimize(access(fname.data(), R_OK));
}
}
BENCHMARK(use_access);
// Use boost
void use_boost(benchmark::State &state) {
for (auto _ : state) {
boost::filesystem::path p(fname);
benchmark::DoNotOptimize(boost::filesystem::exists(p));
}
}
BENCHMARK(use_boost);
BENCHMARK_MAIN();
by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.
example as below http://jsfiddle.net/BfLAh/1/
$(document).mousemove(function(e) {
$("#follow").css({
left: e.pageX,
top: e.pageY
});
});
_x000D_
#follow {
position: absolute;
text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
updated to follow slowly
for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
for the speed , you can set the jquery .animation duration to certain amount.
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:
fieldset {
display: block;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
border: none;
}
body {font-size: 15px; font-family: serif;}
input {
background: transparent;
border-radius: 0px;
border: 1px solid black;
padding: 5px;
box-shadow: none!important;
font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
opacity: 0;
position: absolute;
pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
display: block;
border: 1px solid black;
border-left: 0;
padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
<div>
<label for="name">Name (optional)</label>
<input id="name" type="text" name="name">
</div>
<fieldset>
<legend>Gender</legend>
<div class="checkboxes">
<label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
<label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
<label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
</div>
</fieldset>
<input type="submit" value="Send" />
</form>
_x000D_
Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.
I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me
I overrode onPause
and called finish()
inside that method.
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
You can leverage the streams API of Java 8.
public class ListToMap {
public static void main(String[] args) {
List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));
Map<String, User> map = createHashMap(items);
for(String key : map.keySet()) {
System.out.println(key +" : "+map.get(key));
}
}
public static Map<String, User> createHashMap(List<User> items) {
Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return map;
}
}
For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/
There are a bunch of possible things which could trigger this error:
In your case, you just need to add your facebook account into either tester, developer or admin of your facebook app
as you want to use that account to test.
But if you see the error upon clicking connect to facebook
(before you have chance to enter facebook credentials), then it means your current facebook account detected from cookie is not a valid tester/developer/admin account for your app.
Your could either add your account in
or just hit facebook.com and sign out(to remove the undesired cookie)
.
Use hashlib as hash()
was designed to be used to:
quickly compare dictionary keys during a dictionary lookup
and therefore does not guarantee that it will be the same across Python implementations.
We use object-scan for our data processing and it might be a viable solution here. This is how it could work (also pruning arrays correctly)
// const objectScan = require('object-scan');
const prune = (data) => objectScan(['**'], {
rtn: 'count',
filterFn: ({ isCircular, parent, property }) => {
if (isCircular) {
if (Array.isArray(parent)) {
parent.splice(property, 1);
} else {
delete parent[property];
}
return true;
}
return false;
},
breakFn: ({ isCircular }) => isCircular === true
})(data);
const obj = { a: 'foo', c: [0] };
obj.b = obj;
obj.c.push(obj);
console.log(obj);
// => { a: 'foo', c: [ 0, [Circular] ], b: [Circular] }
console.log(prune(obj)); // returns circular counts
// => 2
console.log(obj);
// => { a: 'foo', c: [ 0 ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
Use CSS positioning:
/* Creates a new stacking context on the header */
#header {
position: relative;
}
/* Positions header-content at the bottom of header's context */
#header-content {
position: absolute;
bottom: 0;
}
As cletus noted, you need identify the header-content to make this work.
<span id="header-content">some header content</span>
<div style="height:100%; position:relative;">
<div style="height:10%; position:absolute; bottom:0px;">bottom</div>
</div>
Simply add these two functions in your viewcontroller it will solve your problem. Here, list is a string array which contain your string of every row.
func tableView(_ tableView: UITableView,
estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
tableView.rowHeight = self.calculateHeight(inString: list[indexPath.row])
return (tableView.rowHeight)
}
func calculateHeight(inString:String) -> CGFloat
{
let messageString = input.text
let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 15.0)]
let attributedString : NSAttributedString = NSAttributedString(string: messageString!, attributes: attributes)
let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
let requredSize:CGRect = rect
return requredSize.height
}
My way on Windows 8
Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin
Open CMD, go to C:\Users\Me\
Generate SSH key ssh-keygen -t rsa
Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)
Add the key to Heroku heroku keys:add
Select a created key from a list
Go to your app directory, write some beautiful code
Init a git repo git init
git add .
git commit -m 'chore(release): v0.0.1
Create Heroku application heroku create
Deploy your app git push heroku master
Open your app heroku open
I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native Array
with for in
structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.
There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.
I would use for in
to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:
l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\n' } console.log(l);
It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.
I'm not really sure if this adds anything but,
Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax
for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).
Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.
The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax
, ecx
and edx
are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx
may be used to return a 64 bit value. I'm not sure why ecx
is also caller saved if needed, but it is.
echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back one page.
echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back two pages.
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
SQL Server / MS Access Syntax:
SELECT TOP 1 * FROM table_name ORDER BY RAND()
MySQL Syntax:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1
import java.util.Scanner;
public class Print {
public static void main(String[] args) {
int row,temp,c,n;
Scanner s=new Scanner(System.in);
n=s.nextInt();
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( c = 1 ; c < temp ; c++ )
System.out.print(" ");
temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
System.out.print("*");
System.out.println("");
}
}
}
I am going to post this because this is what I am currently using for my site and it works in both Google Chrome and IE 10 without receiving any popup messages:
<html>
<head>
</head>
<body onload="window.close();">
</body>
</html>
I have a function on my site that I want to run to save an on/off variable to session without directly going to a new page so I just open a tiny popup webpage. That webpage then closes itself immediately with the onload="window.close();"
function.
JLS Standard
JLS 7 15.17.2. Division Operator / says:
Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.
This is why 1/2
does not give a float.
Converting just either one to float as in (float)1/2
suffices because 15.17. Multiplicative Operators says:
Binary numeric promotion is performed on the operands
and 5.6.2. Binary Numeric Promotion says:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float
As you said:
if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.
Open Sql server 2014 Configuration Manager.
Click Sql server services and start the sql server service if it is stopped
Then click Check SQL server Network Configuration for TCP/IP Enabled
then restart the sql server management studio (SSMS) and connect your local database engine
If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.
e.g. run the shell command "env > /tmp/headers" from within your script
Then, look for the environment variables that start with HTTP_...
You will see lines like:
HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0
Each of those represents a request header.
Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.
This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.
CREATE FUNCTION [dbo].[MinutesToDuration]
(
@minutes int
)
RETURNS nvarchar(30)
AS
BEGIN
declare @hours nvarchar(20)
SET @hours =
CASE WHEN @minutes >= 60 THEN
(SELECT CAST((@minutes / 60) AS VARCHAR(2)) + 'h' +
CASE WHEN (@minutes % 60) > 0 THEN
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
ELSE
''
END)
ELSE
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
END
return @hours
END
To use this function :
SELECT dbo.MinutesToDuration(23)
Results: 23m
SELECT dbo.MinutesToDuration(120)
Results: 2h
SELECT dbo.MinutesToDuration(147)
Results: 2h27m
Hope this helps!
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
Set height or the width of the image to be %100.
There is more in Stack Overflow question How do I auto-resize an image to fit a 'div' container?.
from threading import Thread
from time import sleep
def run(name):
for x in range(10):
print("helo "+name)
sleep(1)
def run1():
for x in range(10):
print("hi")
sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")
I was wondering, until now, why someone had not posted a slightly alteration of the accepted answer to the use of implode()
in order to have a better readability of the code. So here it goes:
<?php
$uaFull = strtolower($_SERVER['HTTP_USER_AGENT']);
$uaStart = substr($uaFull, 0, 4);
$uaPhone = [
'(android|bb\d+|meego).+mobile',
'avantgo',
'bada\/',
'blackberry',
'blazer',
'compal',
'elaine',
'fennec',
'hiptop',
'iemobile',
'ip(hone|od)',
'iris',
'kindle',
'lge ',
'maemo',
'midp',
'mmp',
'mobile.+firefox',
'netfront',
'opera m(ob|in)i',
'palm( os)?',
'phone',
'p(ixi|re)\/',
'plucker',
'pocket',
'psp',
'series(4|6)0',
'symbian',
'treo',
'up\.(browser|link)',
'vodafone',
'wap',
'windows ce',
'xda',
'xiino'
];
$uaMobile = [
'1207',
'6310',
'6590',
'3gso',
'4thp',
'50[1-6]i',
'770s',
'802s',
'a wa',
'abac|ac(er|oo|s\-)',
'ai(ko|rn)',
'al(av|ca|co)',
'amoi',
'an(ex|ny|yw)',
'aptu',
'ar(ch|go)',
'as(te|us)',
'attw',
'au(di|\-m|r |s )',
'avan',
'be(ck|ll|nq)',
'bi(lb|rd)',
'bl(ac|az)',
'br(e|v)w',
'bumb',
'bw\-(n|u)',
'c55\/',
'capi',
'ccwa',
'cdm\-',
'cell',
'chtm',
'cldc',
'cmd\-',
'co(mp|nd)',
'craw',
'da(it|ll|ng)',
'dbte',
'dc\-s',
'devi',
'dica',
'dmob',
'do(c|p)o',
'ds(12|\-d)',
'el(49|ai)',
'em(l2|ul)',
'er(ic|k0)',
'esl8',
'ez([4-7]0|os|wa|ze)',
'fetc',
'fly(\-|_)',
'g1 u',
'g560',
'gene',
'gf\-5',
'g\-mo',
'go(\.w|od)',
'gr(ad|un)',
'haie',
'hcit',
'hd\-(m|p|t)',
'hei\-',
'hi(pt|ta)',
'hp( i|ip)',
'hs\-c',
'ht(c(\-| |_|a|g|p|s|t)|tp)',
'hu(aw|tc)',
'i\-(20|go|ma)',
'i230',
'iac( |\-|\/)',
'ibro',
'idea',
'ig01',
'ikom',
'im1k',
'inno',
'ipaq',
'iris',
'ja(t|v)a',
'jbro',
'jemu',
'jigs',
'kddi',
'keji',
'kgt( |\/)',
'klon',
'kpt ',
'kwc\-',
'kyo(c|k)',
'le(no|xi)',
'lg( g|\/(k|l|u)|50|54|\-[a-w])',
'libw',
'lynx',
'm1\-w',
'm3ga',
'm50\/',
'ma(te|ui|xo)',
'mc(01|21|ca)',
'm\-cr',
'me(rc|ri)',
'mi(o8|oa|ts)',
'mmef',
'mo(01|02|bi|de|do|t(\-| |o|v)|zz)',
'mt(50|p1|v )',
'mwbp',
'mywa',
'n10[0-2]',
'n20[2-3]',
'n30(0|2)',
'n50(0|2|5)',
'n7(0(0|1)|10)',
'ne((c|m)\-|on|tf|wf|wg|wt)',
'nok(6|i)',
'nzph',
'o2im',
'op(ti|wv)',
'oran',
'owg1',
'p800',
'pan(a|d|t)',
'pdxg',
'pg(13|\-([1-8]|c))',
'phil',
'pire',
'pl(ay|uc)',
'pn\-2',
'po(ck|rt|se)',
'prox',
'psio',
'pt\-g',
'qa\-a',
'qc(07|12|21|32|60|\-[2-7]|i\-)',
'qtek',
'r380',
'r600',
'raks',
'rim9',
'ro(ve|zo)',
's55\/',
'sa(ge|ma|mm|ms|ny|va)',
'sc(01|h\-|oo|p\-)',
'sdk\/',
'se(c(\-|0|1)|47|mc|nd|ri)',
'sgh\-',
'shar',
'sie(\-|m)',
'sk\-0',
'sl(45|id)',
'sm(al|ar|b3|it|t5)',
'so(ft|ny)',
'sp(01|h\-|v\-|v )',
'sy(01|mb)',
't2(18|50)',
't6(00|10|18)',
'ta(gt|lk)',
'tcl\-',
'tdg\-',
'tel(i|m)',
'tim\-',
't\-mo',
'to(pl|sh)',
'ts(70|m\-|m3|m5)',
'tx\-9',
'up(\.b|g1|si)',
'utst',
'v400',
'v750',
'veri',
'vi(rg|te)',
'vk(40|5[0-3]|\-v)',
'vm40',
'voda',
'vulc',
'vx(52|53|60|61|70|80|81|83|85|98)',
'w3c(\-| )',
'webc',
'whit',
'wi(g |nc|nw)',
'wmlb',
'wonu',
'x700',
'yas\-',
'your',
'zeto',
'zte\-'
];
$isPhone = preg_match('/' . implode($uaPhone, '|') . '/i', $uaFull);
$isMobile = preg_match('/' . implode($uaMobile, '|') . '/i', $uaStart);
if($isPhone || $isMobile) {
// do something with that device
} else {
// process normally
}
First set Storage Engine as InnoDB
then the relation view option enable in structure menu
Experience With: ASUS ZENFONE
If at all you have faced Missing Driver for Asus Zenfones Follow This Link (http://donandroid.com/how-to-install-adb-interface-drivers-windows-7-xp-vista-623)
I tried with
1) Killing and starting adb server at adb cmd.
2) Switching Usb Debugging on and Off and ...
This is What WORKED with me.
Step 1:Remove Connection with Device and Close Eclipse
Step 2:Navigate to C:/Users/User_name/.android/
Step 3:You Will Find adb_key
Step 4:Just delete it.
Step 5.Connect again and System will ask you Again.
Step 6.Ask Device to remember RSA Key when it Prompts. I think its done.
If you Face The Same Problem after couple of days, just disable and enable USB debugging
EDIT:
As this seem to be a top result on Google and my answer below is not, please refer to this much better answer:
https://stackoverflow.com/a/1222488/1240557
OLD ANSWER (not so complete :))
In order to create good software, you have to know what that software is all about. You cannot create a banking software system unless you have a good understanding of what banking is all about, one must understand the domain of banking.
From: Domain Driven Design by Eric Evans.
This book does a pretty good job of describing DDD.
Register to download a summary of the book, or download the summary directly.
str1.toLowerCase().contains(str2.toLowerCase())
TCPDF 6.2.11 (2015-08-02)
Some things won't work when included within <style>
tags, however they will if added in a style=""
attribute in the HTML tag. E.g. table padding – this doesn't work:
table {
padding: 5px;
}
This does:
<table style="padding: 5px;">
It is possible to download all of the UNIX commands compiled for Windows, including which
from this GitHub repository: https://github.com/George-Ogden/UNIX
Fiddle: http://jsfiddle.net/simple/BdQvp/
You can do it like so:
I have added two buttons in the Fiddle to illustrate how you can insert or clear values in those input fields through buttons. You just capture the onClick event and call the function.
//Fires when the Document Loads, clears all input fields
$(document).ready(function() {
$('.fetch_results').find('input:text').val('');
});
//Custom Functions that you can call
function resetAllValues() {
$('.fetch_results').find('input:text').val('');
}
function addSomeValues() {
$('.fetch_results').find('input:text').val('Lala.');
}
Update:
Check out this great answer below by Beena as well for a more universal approach.
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
works for me: File -> Invalidate Caches / Restart... -> Invalidate and Restart
You can write a query as follows:
IF OBJECT_ID('ProcedureName','P') IS NOT NULL
DROP PROC ProcedureName
GO
CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....
To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P
This query will find the procedure and if it is available it will drop it and create new one.
For detailed information about OBJECT_ID and Object types please visit : SYS.Objects
I think this is the most clear solution, using an extension method:
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}
So just use it like:
var ipAddress = request.GetClientIpAddress();
We use this in our projects.
Source/Reference: Retrieving the client’s IP address in ASP.NET Web API
I successfully debug app through WiFi by following the official site's guide.
Note,
adb pair
.I have the same problem, i read the url with an properties file:
String configFile = System.getenv("system.Environment");
if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
configFile = "dev.properties";
}
// Load properties
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/" + configFile));
//read url from file
apiUrl = properties.getProperty("url").trim();
URL url = new URL(apiUrl);
//throw exception here
URLConnection conn = url.openConnection();
dev.properties
url = "https://myDevServer.com/dev/api/gate"
it should be
dev.properties
url = https://myDevServer.com/dev/api/gate
without "" and my problem is solved.
According to oracle documentation
- Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
So it means it is not parsed inside the string.
To convert an int
ASCII value to character you can also use:
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
set a border on it before you click to be the same color as the background.
Then when you click just change the background color and the width will not change.
They have the same speed. Maybe in some special architecture what he/she said is right, but in the x86 family at least I know they are the same. Because for doing this the CPU will do a substraction (a - b) and then check the flags of the flag register. Two bits of that register are called ZF (zero Flag) and SF (sign flag), and it is done in one cycle, because it will do it with one mask operation.
Or just use this in your View(Razor page)
@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))
I recommend that don't add date format in your model class
I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?
This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.
For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'
From Spring In Action
As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.
In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.
I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.
<button onClick="window.location.reload();">Reload</button>
Or you can also use
<form action="<same page url>" method="GET">
<button>Reload</button>
</form>
Note: Change "<same page link>"
with the url of same page you want to reload.
for example:
<form action="home.html> method="GET">
Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!
It gave me the idea to change the function _DispEx
that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file:
See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:
/**
* fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
* @param {HTMLElement} p the <A> element
* @param {HTMLEvent} a the click event
* @param {Boolean} h TRUE
* @param {Boolean} e FALSE
* @param {Boolean} g FALSE
* @param {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
* @param {Number} c 0
* @param {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
* @param {String} m
* @param {String} b the replacement URL to the xslviewer
*/
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
bak_DispEx = _DispEx;
_DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
// if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
// in that case we want to open ask the user if he/she wants to readonly or edit the file
var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
// if the URL doesn't start with http
if (!/^http/.test(fileURL)) {
fileURL = window.location.protocol + "//" + window.location.host + fileURL;
}
var ohtml = document.createElement('div');
ohtml.style.padding = "10px";
ohtml.style.display = "inline-block";
ohtml.style.width = "200px";
ohtml.style.width = "200px";
ohtml.innerHTML = '<style>'
+ '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
+ '.opendocument_button:hover { box-shadow: none }'
+ '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
+ '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
+ '</style>'
+ 'You are about to open:'
+ '<ul class="opendocument_ul">'
+ ' <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
+ ' <li>From: <b>'+window.location.hostname+'</b></li>'
+ '</ul>'
+ 'How would like to open this file?'
+ '<ul class="opendocument_ul">'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
+ '</ul>'
+ '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
// show the modal
modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
html:ohtml,
dialogReturnValueCallback:function(ret) {
if (ret!==-1) {
if (ret === true) { // edit
// reformat the fileURL
var ext;
if (/\.xlsx?$/.test(b)) ext = "ms-excel";
if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
fileURL = ext + ":ofe|u|" + fileURL;
}
window.location.href = fileURL; // open the file
}
}
});
a.preventDefault();
a.stopImmediatePropagation()
a.cancelBubble = true;
a.returnValue = false;
return false;
}
return bak_DispEx.apply(this, arguments);
}
}, "sp.scriptloaded-core.js")
I use SP.SOD.executeOrDelayUntilEventNotified
to make sure the function will be executed when core.js
is loaded.
The following command does this automatically for you: This will also delete all the data in the table. So be careful.
TRUNCATE TABLE someTable RESTART IDENTITY;
If you have couple of json files:
import data from 'sample.json';
If you were to dynamically load one of the many json file, you might have to use a fetch
instead:
fetch(`${fileName}.json`)
.then(response => response.json())
.then(data => console.log(data))
import csv
with open('file_name.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(('colum1', 'colum2', 'colum3'))
for key, value in dictionary.items():
writer.writerow([key, value[0], value[1]])
This would be the simplest way to write data to .csv file
the problem can because of MVC MW.you must set formatterType in MVC options:
services.AddMvc(options =>
{
options.UseCustomStringModelBinder();
options.AllowEmptyInputInBodyModelBinding = true;
foreach (var formatter in options.InputFormatters)
{
if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
}
}).AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
@RequestMapping(value="/register",method=RequestMethod.POST)
public ModelAndView postRegisterPage(HttpServletRequest request,HttpServletResponse response,
@ModelAttribute("bean")RegisterModel bean)
{
RegisterService service = new RegisterService();
boolean b = service.saveUser(bean);
if(b)
{
return new ModelAndView("registerPage","errorMessage","Registered Successfully!");
}
else
{
return new ModelAndView("registerPage","errorMessage","ERROR!!");
}
}
/* "registerPage" is the .jsp page -> which will viewed.
/* "errorMessage" is the variable that could be displayed in page using -> **${errorMessage}**
/* "Registered Successfully!" or "ERROR!!" is the message will be printed based on **if-else condition**
You'll need to use an Iterator
to loop through the keys to get their values.
Here's a Kotlin implementation, you will realised that the way I got the string is using optString()
, which is expecting a String or a nullable value.
val keys = jsonObject.keys()
while (keys.hasNext()) {
val key = keys.next()
val value = targetJson.optString(key)
}
A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code
Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.
The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.
The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.
One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.
After making changes to the pg_hba.conf
or postgresql.conf
files, the cluster needs to be reloaded to pick up the changes.
From the command line: pg_ctl reload
From within a db (as superuser): select pg_reload_conf();
From PGAdmin: right-click db name, select "Reload Configuration"
Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers
, etc -- those require a cluster restart.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL
SELECT STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM table
say for example use the below query to get output
SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table
For String format use the below link
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
As stated above, using 'click touchstart'
will get the desired result. If you console.log(e)
your clicks though, you may find that when jquery recognizes touch as a click - you will get 2 actions from click and touchstart. The solution bellow worked for me.
//if its a mobile device use 'touchstart'
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
deviceEventType = 'touchstart'
} else {
//If its not a mobile device use 'click'
deviceEventType = 'click'
}
$(document).on(specialEventType, function(e){
//code here
});
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
A little late to the game, but for future searchers, this also should work:
df.quantity = df.quantity * -1
Yes, you can merge them using HTML. When I create tables in .md
files from Github, I always like to use HTML code instead of markdown.
Github Flavored Markdown supports basic HTML in .md
file. So this would be the answer:
Markdown mixed with HTML:
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|
Or pure HTML:
<table>
<tbody>
<tr>
<th>Tables</th>
<th align="center">Are</th>
<th align="right">Cool</th>
</tr>
<tr>
<td>col 3 is</td>
<td align="center">right-aligned</td>
<td align="right">$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td align="center">centered</td>
<td align="right">$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td align="center">are neat</td>
<td align="right">$1</td>
</tr>
<tr>
<td>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
</td>
<td align="center">See the list</td>
<td align="right">from the first column</td>
</tr>
</tbody>
</table>
This is how it looks on Github:
"End Process" on the Processes-Tab calls TerminateProcess
which is the most ultimate way Windows knows to kill a process.
If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.
Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx
Unix based systems like Linux also have that problem where processes could survive a kill -9
if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D
) at which point the processes sleep so well that they can't process incoming signals (which is what kill
does - sending signals).
Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork
without exec
) can end up sleeping in D
forever.
I'm probably late but this worked for me:
<target name="build" />
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
This made my life so much easier. You basically put in your elements id tag and its scrolls to it without a lot of code
http://balupton.github.io/jquery-scrollto/
In Javascript
$('#scrollto1').ScrollTo();
In your html
<div id="scroollto1">
Here I am all the way down the page
You have multiple ways to set :
as the separator:
awk -F: '{print $1}'
awk -v FS=: '{print $1}'
awk '{print $1}' FS=:
awk 'BEGIN{FS=":"} {print $1}'
All of them are equivalent and will return 1
given a sample input "1:2:3":
$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
tools => fiddler options => connections there is a textarea with stuff to jump, delete LH from there
Try below code.
Random rnd = new Random();
int month = rnd.Next(1, 13); // creates a number between 1 and 12
int dice = rnd.Next(1, 7); // creates a number between 1 and 6
int card = rnd.Next(52); // creates a number between 0 and 51
The same issue with 7.1
apt-get install php7.1-json
sudo nano /etc/php/7.1/mods-available/json.ini
In concerns make file filename.rb
For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by
module TestConcern
extend ActiveSupport::Concern
def checkattributes
if self.has_attribute?(:created_by)
self.update_attributes(created_by: 1)
end
if self.has_attribute?(:updated_by)
self.update_attributes(updated_by: 0)
end
end
end
If you want to pass arguments in action
included do
before_action only: [:create] do
blaablaa(options)
end
end
after that include in your model like this:
class Role < ActiveRecord::Base
include TestConcern
end
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
In Sql Server
You can do this using cross apply
Select
ColumnA,
ColumnB,
c.calccolumn1 As calccolumn1,
c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
Now I solved this issue in this way,
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the
default TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.out.println(e);
}
The best way is to start the timer thread once. Inside your timer thread you'd code the following
class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(0.5):
print("my thread")
# call a function
In the code that started the timer, you can then set
the stopped event to stop the timer.
stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
A simple way to used copy module to transfer the file from one server to another
Here is playbook
---
- hosts: machine1 {from here file will be transferred to another remote machine}
tasks:
- name: transfer data from machine1 to machine2
copy:
src=/path/of/machine1
dest=/path/of/machine2
delegate_to: machine2 {file/data receiver machine}
Just giving a more up to date answer in case someone sees this old post.
Adding "utc=False" when converting to datetime will remove the timezone component and keep only the date in a datetime64[ns] data type.
pd.to_datetime(df['Date'], utc=False)
You will be able to save it in excel without getting the error "ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel."
I have created a module for pipes in the same directory where my pipes are present
import { NgModule } from '@angular/core';
///import pipe...
import { Base64ToImage, TruncateString} from './'
@NgModule({
imports: [],
declarations: [Base64ToImage, TruncateString],
exports: [Base64ToImage, TruncateString]
})
export class SharedPipeModule { }
Now import that module in app.module:
import {SharedPipeModule} from './pipe/shared.pipe.module'
@NgModule({
imports: [
...
, PipeModule.forRoot()
....
],
Now it can be used by importing the same in the nested module
Another option is to check if it's busy with a timer:
Set the timer as disabled by default. Then whenever navigating, enable it. i.e.:
WebBrowser1.Navigate("https://www.somesite.com")
tmrBusy.Enabled = True
And the timer:
Private Sub tmrBusy_Tick(sender As Object, e As EventArgs) Handles tmrBusy.Tick
If WebBrowser1.IsBusy = True Then
Debug.WriteLine("WB Busy ...")
Else
Debug.WriteLine("WB Done.")
tmrBusy.Enabled = False
End If
End Sub
If speed is important, use this:
/**
* Replace last occurrence of a string with another string
* x - the initial string
* y - string to replace
* z - string that will replace
*/
function replaceLast(x, y, z){
var a = x.split("");
var length = y.length;
if(x.lastIndexOf(y) != -1) {
for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
if(i == x.lastIndexOf(y)) {
a[i] = z;
}
else {
delete a[i];
}
}
}
return a.join("");
}
It's faster than using RegExp.
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
I am note sure, what you are expecting. Have a look at this fiddle, this might help you.
You HTML should have the class navbar-fixed-top
or navbar-fixed-bottom
.
HTML
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
JS
$(document).scroll(function(e){
var scrollTop = $(document).scrollTop();
if(scrollTop > 0){
console.log(scrollTop);
$('.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
} else {
$('.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
}
});
It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).
(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)
When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).
Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").
Here is another reference for go this time at 10 million: http://goroutines.com/10m.
This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/
It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
Here is one aditional free Floating Action Button library for Android It has many customizations and requires SDK version 9 and higher
You can use code below to remove style default inforwindow. After you can use HTML code for inforwindow:
var inforwindow = "<div style="border-radius: 50%"><img src='URL'></div>"; // show inforwindow image circle
marker.addListener('click', function() {
$('.gm-style-iw').next().css({'height': '0px'}); //remove arrow bottom inforwindow
$('.gm-style-iw').prev().html(''); //remove style default inforwindows
});
I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
Depends on what you mean by better. This works if your goal is removal of redundancy.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
While passing parameters, it is better option is an input file, can this be a excel a json or whatever you need and from there read the data structure and variables you need from that including the variable name as is the need. To read a file can have the following structure.
namespace :name_sapace_task do
desc "Description task...."
task :name_task => :environment do
data = ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
# and work whit yoour data, example is data["user_id"]
end
end
{
"name_task": "I'm a task",
"user_id": 389,
"users_assigned": [389,672,524],
"task_id": 3
}
rake :name_task
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
this.input
is undefined until the ref
callback is called. Try setting this.input
to some initial value in your constructor.
From the React docs on refs, emphasis mine:
the callback will be executed immediately after the component is mounted or unmounted
here is a trick
a = double.Parse(a.ToString().Split(',')[0])
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
For example, something like:
player p;
showInventory(p);
I'm guessing you have something like this:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
int main()
{
player p;
toDo(p);
}
and
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
It should be the same command, except SET instead of EXPORT
I've been recently working on it. Check out this jsFiddle test, try it yourself changing the width of the base table to check the behavior).
The solution is to embedded a table into another:
<table style="width: 200px;border:0;border-collapse:collapse">
<tbody>
<tr>
<td style="width: 100%;">
<table style="width: 100%;border:0;border-collapse:collapse">
<tbody>
<tr>
<td>
<div style="position: relative;overflow:hidden">
<p> </p>
<p style="overflow:hidden;text-overflow: ellipsis;position: absolute; top: 0pt; left: 0pt;width:100%">This cells has more content</p>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td style="white-space:nowrap">Less content here</td>
</tr>
</tbody>
</table>
Is Fred now happy with Celldito's expansion?
You can add this piece of code to the top of your batch file:
@Echo off
SET LOGFILE=MyLogFile.log
call :Logit >> %LOGFILE%
exit /b 0
:Logit
:: The rest of your code
:: ....
It basically redirects the output of the :Logit
method to the LOGFILE
. The exit
command is to ensure the batch exits after executing :Logit
.
I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.
You get to the SDK Manager through one of two paths. Option 1. Tools > Android > SDK Manager Option 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)
In the pane "SDK Platforms," check the "Show Packages" box to see the system images.
Select the ones you want, click "Apply" and voilà!
I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module
After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!
In case my experience is unclear:
Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()
Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()
From AllFSGroupsCY()
Public Sub FSGroupsCY()
AllFSGroupsPY 'will error each time until the properties name is changed
End Sub
Your code ArrayList<String> list2 = (String)list;
does not compile because list2
is not of type String
. But that is not the only problem.
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
Check if below are enabled
bz, mbstring, intl, ioncube_loader and Json extension.
First you need to prepare your url to accept the param in the regex: (urls.py)
url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),
So you use this in your template:
{% url 'panel_person_form' person_id=item.id %}
If you have more than one param, you can change your regex and modify the template using the following:
{% url 'panel_person_form' person_id=item.id group_id=3 %}
By default time zone of laravel project is **UTC*
'timezone' => 'UTC',
now change according to your time zone for me it's Asia/Calcutta
so for me setting will be 'timezone' => 'Asia/Calcutta',
*for time zone list visit this url https://www.w3schools.com/php/php_ref_timezones.asp
I was using a custom downloader middleware, but wasn't very happy with it, as I didn't manage to make the cache work with it.
A better approach was to implement a custom download handler.
There is a working example here. It looks like this:
# encoding: utf-8
from __future__ import unicode_literals
from scrapy import signals
from scrapy.signalmanager import SignalManager
from scrapy.responsetypes import responsetypes
from scrapy.xlib.pydispatch import dispatcher
from selenium import webdriver
from six.moves import queue
from twisted.internet import defer, threads
from twisted.python.failure import Failure
class PhantomJSDownloadHandler(object):
def __init__(self, settings):
self.options = settings.get('PHANTOMJS_OPTIONS', {})
max_run = settings.get('PHANTOMJS_MAXRUN', 10)
self.sem = defer.DeferredSemaphore(max_run)
self.queue = queue.LifoQueue(max_run)
SignalManager(dispatcher.Any).connect(self._close, signal=signals.spider_closed)
def download_request(self, request, spider):
"""use semaphore to guard a phantomjs pool"""
return self.sem.run(self._wait_request, request, spider)
def _wait_request(self, request, spider):
try:
driver = self.queue.get_nowait()
except queue.Empty:
driver = webdriver.PhantomJS(**self.options)
driver.get(request.url)
# ghostdriver won't response when switch window until page is loaded
dfd = threads.deferToThread(lambda: driver.switch_to.window(driver.current_window_handle))
dfd.addCallback(self._response, driver, spider)
return dfd
def _response(self, _, driver, spider):
body = driver.execute_script("return document.documentElement.innerHTML")
if body.startswith("<head></head>"): # cannot access response header in Selenium
body = driver.execute_script("return document.documentElement.textContent")
url = driver.current_url
respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf8'))
resp = respcls(url=url, body=body, encoding="utf-8")
response_failed = getattr(spider, "response_failed", None)
if response_failed and callable(response_failed) and response_failed(resp, driver):
driver.close()
return defer.fail(Failure())
else:
self.queue.put(driver)
return defer.succeed(resp)
def _close(self):
while not self.queue.empty():
driver = self.queue.get_nowait()
driver.close()
Suppose your scraper is called "scraper". If you put the mentioned code inside a file called handlers.py on the root of the "scraper" folder, then you could add to your settings.py:
DOWNLOAD_HANDLERS = {
'http': 'scraper.handlers.PhantomJSDownloadHandler',
'https': 'scraper.handlers.PhantomJSDownloadHandler',
}
And voilà, the JS parsed DOM, with scrapy cache, retries, etc.
In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.
This is why Python requires us to use immutable datatypes for the keys in a dictionary.
Why so complicated?
Just check System Objects in Access-Options/Current Database/Navigation Options/Show System Objects
Open Table "MSysIMEXSpecs" and change according to your needs - its easy to read...
There is a ToObject method now.
var obj = jsonObject["date_joined"];
var result = obj.ToObject<DateTime>();
It also works with any complex type, and obey to JsonPropertyAttribute rules
var result = obj.ToObject<MyClass>();
public class MyClass
{
[JsonProperty("date_field")]
public DateTime MyDate {get;set;}
}
There are special cases where arrow functions
just won't do the trick:
If we're changing a method of an external API, and need the object's reference.
If we need to use special keywords that are exclusive to the function
expression: arguments
, yield
, bind
etc.
For more information:
Arrow function expression limitations
Example:
I assigned this function as an event handler in the Highcharts
API.
It's fired by the library, so the this
keyword should match a specific object.
export const handleCrosshairHover = function (proceed, e) {
const axis = this; // axis object
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};
With an arrow function, this
would match the declaration scope, and we won't have access to the API obj:
export const handleCrosshairHover = (proceed, e) => {
const axis = this; // this = undefined
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};
If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.
http://docs.python.org/library/threading.html#threading.Thread.daemon
Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.
RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).
HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.
If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.
Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.
Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.
The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration
. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json
, which contains the public key (or keys) of the account.
If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.
When you say you have "clearly set" JAVA_HOME to "C:\Program Files\Java\jdk1.6.0_14" - is that what you see when you run "set" from the command line? I believe Ant will guess at a value for JAVA_HOME if one isn't set at all... is it possible that you've set JAVAHOME instead of JAVA_HOME?
If it's nothing like that, I suggest you edit the ant.bat
batch file (and whatever it calls - I can't remember whether it's convoluted or not offhand) to print out JAVA_HOME at the start and at various other interesting places.
If using Struts, we disable direct access to the JSP files by using this tag in web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>no_access</web-resource-name>
<url-pattern>*.jsp</url-pattern>
</web-resource-collection>
<auth-constraint/>
This will get selected value from multi-value select boxes: $("#id option:selected").val()
2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker
Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.
To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:
#content #nav a {_x000D_
background-color: #FF0;_x000D_
_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-moz-transition: background-color 1000ms linear;_x000D_
-o-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
<div id="nav">_x000D_
<a href="#link1">Link 1</a>_x000D_
</div>_x000D_
</div>
_x000D_
Save the following script as brew-purge
#!/bin/bash
#:Usage: brew purge formula
#:
#:Removes the package and all dependancies.
#:
#:
PKG="$1"
if [ -z "$PKG" ];then
brew purge --help
exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
do :
done
echo Package $PKG and its dependancies have been removed.
exit 0
Now install it with the following command
sudo install brew-purge /usr/local/bin
Now run it
brew purge package
Example using gpg
$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$
To have text-align:center
work you need to add that style to the #siteInfo
div or wrap the input in a paragraph and add text-align:center
to the paragraph.
To add all the changes you've made:
git add .
To commit them:
git commit -m "MY MESSAGE HERE"
#-m is the message flag
You can put those steps together like this:
git commit -a -m "MY MESSAGE HERE"
To push your committed changes from your local repository to your remote repository:
git push origin master
You might have to type in your username/password for github after this. Here's a good primer on using git. A bit old, but it covers what's going on really well.
It's also important to put
table-layout:fixed;
Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.
Inside Layout Xml File We can Change Color of Hint.....
android:textColorHint="@android:color/*****"
you can replace * with color or color code.
Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B
.
If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M
.
(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)
I also encountered this problem because I install Ruby on Ubuntu via brightbox, and I thought ruby-dev is the trunk of ruby. So I did not install. Install ruby2.3-dev fixes it:
sudo apt-get install ruby2.3-dev
You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others
To use Run (Simple Method)
Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn
ProgramPath is the full path to your script you want to run
ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)
])
IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run Method
WaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.
NOTE: The Run method can return the exit code but you must set WaitOnReturn to True, and assign the 'WshShell.Run' to a variable. (EX: ExitCode=WshShell.Run (Command,intWindowStyle,True)
)
To Use EXEC (Advanced Method)
Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
'Currently Waiting on the program to finish execution.
WScript.Sleep 300
Loop
ProgramPath same as Run READ RUN'S DESCRIPTION
ProgramArgs DITTO
ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe". Note that in order to use stdin and stdout (we'll cover what these are a bit further down) you must choose "CScript.exe".
Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.
More Details about the members of Process Object
Process.StdIn.WriteLine "Hello Other Worlds"
)Process.StdOut.ReadLine
. This is the stream that the called script will receive any information sent by the calling script's stdin. If you used the stdin's example then StdOut.Readline will return "Hello Other Worlds". If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not RespondingRead
or ReadAll
instead of ReadLine
if you want. Use Read (X)
if you want to read X amount of characters. Or ReadAll
if you want the rest of the stream.For more information about WshShell.Exec go to Exec Method Windows Scripting Host
Yes of course, just add the response y
as first column in the dataframe and call lm()
on it:
d2<-data.frame(y,d)
> d2
y x1 x2 x3
1 1 4 3 4
2 4 -1 9 -4
3 6 3 8 -2
> lm(d2)
Call:
lm(formula = d2)
Coefficients:
(Intercept) x1 x2 x3
-5.6316 0.7895 1.1579 NA
Also, my information about R points out that assignment with <-
is recommended over =
.
String name,password;
public int idGen() {
int id = this.name.hashCode() + this.password.hashCode();
int length = String.valueOf(id).length();
int Max_Length = 5;
if(String.valueOf(id).length()>Max_Length)
{
id = (int) (id /Math.pow(10.0,length - Max_Length ));
}
return id;
}
if("123".search(/^\d+$/) >= 0){
// its a number
}
Try that:
if(WIN32)
set(ADDITIONAL_LIBRARIES wsock32)
else()
set(ADDITIONAL_LIBRARIES "")
endif()
target_link_libraries(${PROJECT_NAME} bioutils ${ADDITIONAL_LIBRARIES})
You can find other useful variables here.
In my case it happened cause i embedded a RecyclerView in a LinearLayout.
I previously had a layout file only containing one root RecyclerView as follows
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/fragment_products"
android:name="Products.ProductsFragment"
app:layoutManager="LinearLayoutManager"
tools:context=".Products.ProductsFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"/>
I believe the problem is within the 3 lines separated. Anyway, I think its a simple problem, ill be working on it tomorrow; thought i should write what i found before forgetting about this thread.
You can use this regex to get the yyyy-MM-dd format:
((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])
You can find example for date validation: How to validate date with regular expression.
You're looking for RAISERROR
.
From MSDN:
Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.
CodeProject has a good article that also describes in-depth the details of how it works and how to use it.
The simplest solution is:
array - array for remove some element valueForRemove; valueForRemove - element for remove;
array.filter(arrayItem => !array.includes(valueForRemove));
More simple:
array.filter(arrayItem => arrayItem !== valueForRemove);
No pretty, but works:
array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))
No pretty, but works:
while(array.indexOf(valueForRemove) !== -1) {
array.splice(array.indexOf(valueForRemove), 1)
}
P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
That query is failing and returning false
.
Put this after mysqli_query()
to see what's going on.
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
For more information:
Underscore-java library has static method U.jsonToXml(jsonstring)
. I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
public class MyClass {
public static void main(String args[]) {
String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
System.out.println(json);
String xml = U.jsonToXml(json);
System.out.println(xml);
}
}
Output:
{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>JSON</name>
<integer number="true">1</integer>
<double number="true">2.0</double>
<boolean boolean="true">true</boolean>
<nested>
<id number="true">42</id>
</nested>
<array number="true">1</array>
<array number="true">2</array>
<array number="true">3</array>
</root>
You can use findHandlersJS
You can find the handler by doing in the chrome console:
findEventHandlers("click", "img.envio")
You'll get the following information printed in chrome's console:
More info here and you can try it in this example site here.
I liked @AshOoO's answer but like @Rajan Rawal I needed to preserve selected item state, if any. So I added my customization to his method AddFirstItem()
public static SelectList AddFirstItem(SelectList origList, SelectListItem firstItem)
{
List<SelectListItem> newList = origList.ToList();
newList.Insert(0, firstItem);
var selectedItem = newList.FirstOrDefault(item => item.Selected);
var selectedItemValue = String.Empty;
if (selectedItem != null)
{
selectedItemValue = selectedItem.Value;
}
return new SelectList(newList, "Value", "Text", selectedItemValue);
}
First of all, there're two kinds of keystores.
Individual and General
The application will use the one indicated in the startup or the default of the system.
It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.
They are encrypted too
In short, the path will be like:
$JAVA_HOME/lib/security/cacerts
for the "general one", who has all the CA for the Authorities and is quite important.
updateOrCreate
Built into core...]Just in case people are still coming across this... I found out a few weeks after writing this, that this is in fact part of Laravel's Eloquent's core...
Digging into Eloquent’s equivalent method(s). You can see here:
https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553
on :570 and :553
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return static
*/
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
Old Answer Below
I am wondering if there is any built in L4 functionality for doing this in some way such as:
$row = DB::table('table')->where('id', '=', $id)->first();
// Fancy field => data assignments here
$row->save();
I did create this method a few weeks back...
// Within a Model extends Eloquent
public static function createOrUpdate($formatted_array) {
$row = Model::find($formatted_array['id']);
if ($row === null) {
Model::create($formatted_array);
Session::flash('footer_message', "CREATED");
} else {
$row->update($formatted_array);
Session::flash('footer_message', "EXISITING");
}
$affected_row = Model::find($formatted_array['id']);
return $affected_row;
}
I Hope that helps. I would love to see an alternative to this if anyone has one to share. @erikthedev_
In Mac OS X, it is under
<workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects
Below are the working steps without the need for any external modules:
Step 1: Create a module in your app.
E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.
Lets call this as custom_cors_middleware.py
Paste the below Class definition:
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
Step 2: Register a middleware
In your projects settings.py file, add this line
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
E.g:
MIDDLEWARE = [
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
...
'django.middleware.common.CommonMiddleware',
]
Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.
You can now verify it will add the required response headers to all the views in the project!
Called "Destructive Methods" They tend to change the original copy of the object you are referring to.
numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers # returns [nil,nil,nil,nil,nil]
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
From version 9.1.4 you only need to import ReactiveFormsModule
Use the json
module (new in Python 2.6) or the simplejson
module which is almost always installed.
git config --global --unset http.proxy
have you looked at layoutIfNeeded?
The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?
layoutIfNeeded Lays out the subviews if needed.
- (void)layoutIfNeeded
Discussion Use this method to force the layout of subviews before drawing.
Availability Available in iPhone OS 2.0 and later.
I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:
pip uninstall opencv-python # -- the original step. failed.
ImportError: DLL load failed: The specified module could not be found.
I did this into my python3.6 environment and got this error.
python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.
Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.
finally, this fixed it:
pip uninstall opencv-python
(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.
>>>import cv2
>>>
working!
Try this one updated intent google map address location find out
Uri gmmIntentUri1 = Uri.parse("geo:0,0?q=" + Uri.encode(address));
Intent mapIntent1 = new Intent(Intent.ACTION_VIEW, gmmIntentUri1);
mapIntent1.setPackage("com.google.android.apps.maps");
startActivity(mapIntent1);
I want to share my personal experience, calling a REST WS with Post JSON call:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
public class HWS {
public static void main(String[] args) throws IOException {
URL url = new URL("INSERT YOUR SERVER REQUEST");
//Insert your JSON query request
String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
//It change the apostrophe char to double quote char, to form a correct JSON string
query=query.replace("'", "\"");
try{
//make connection
URLConnection urlc = url.openConnection();
//It Content Type is so important to support JSON call
urlc.setRequestProperty("Content-Type", "application/xml");
Msj("Conectando: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
Msj("Consulta: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
Msj(l);
}
br.close();
} catch (Exception e){
Msj("Error ocurrido");
Msj(e.toString());
}
}
private static void Msj(String texto){
System.out.println(texto);
}
}
<a data-toggle="tooltip" data-placement="top" title="My Tooltip text!">+</a>
Take a look at example and do in similar way
(sorce from http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/):
ssh.connect('127.0.0.1', username='jesse',
password='lol')
stdin, stdout, stderr = ssh.exec_command(
"sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
if line.split(':')[0] == 'AirPort':
print line
Visual C++ Redistributable for Visual Studio 2015 (x32 bit version) - RC.
This should correct that. You can google for what the DLL is, but that's not important.
PS: It's officially from Microsoft too:)
Where I found it: Downloads (Visual Studio)