send a GET
to a page and the content replied will be the answer.Base url : http://website/api/
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
I found an other way to just get the base url to to display the value of environment variable APP_URL
env('APP_URL')
which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).
Take a look at the documentation for HttpServletRequest
.
In order to build the URL in your example you will need to use:
getScheme()
getServerName()
getServerPort()
getContextPath()
Here is a method that will return your example:
public static String getURLWithContextPath(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers.
Instead (unless you don't use the standard services configuration), inject the request object by type-hinting.
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* The YourService class provides a method for retrieving the base URL.
*
* @package App\Service
*/
class YourService
{
/**
* @var string
*/
protected $baseUrl;
/**
* YourService constructor.
*
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();
}
/**
* Returns the current base URL.
*
* @return string
*/
public function getBaseUrl(): string
{
return $this->baseUrl;
}
}
See also official Symfony docs about how to retrieve the current request object.
shape
is a property of both numpy ndarray's and matrices.
A.shape
will return a tuple (m, n), where m is the number of rows, and n is the number of columns.
In fact, the numpy matrix
object is built on top of the ndarray
object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}
Generate values from the uniform distribution on the interval [a, b].
r = a + (b-a).*rand(100,1);
You can create a putty session, and auto load the script on the server, when starting the session:
putty -load "sessionName"
At remote command, point to the remote script.
You can do it with HttpWebRequest
:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "pass"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Whenever you try to show a Link
on a page thats outside the BrowserRouter
you will get that error.
This error message is essentially saying that any component that is not a child of our <Router>
cannot contain any React Router related components.
You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.
Let's say you have a Header.js
component that looks like this:
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return (
<div className="ui secondary pointing menu">
<Link to="/" className="item">
Streamy
</Link>
<div className="right menu">
<Link to="/" className="item">
All Streams
</Link>
</div>
</div>
);
};
export default Header;
And your App.js
file looks like this:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<Header />
<BrowserRouter>
<div>
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Notice that the Header.js
component is making use of the Link
tag from react-router-dom
but the componet was placed outside the <BrowserRouter>
, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Please review carefully and ensure you have the <Header />
or whatever your component may be inside of not only the <BrowserRouter>
but also inside of the <div>
, otherwise you will also get the error that a Router may only have one child which is referring to the <div>
which is the child of <BrowserRouter>
. Everything else such as Route
and components must go within it in the hierarchy.
So now the <Header />
is a child of the <BrowserRouter>
within the <div>
tags and it can successfully make use of the Link
element.
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
The better and dynamic solution I have found is to use $watch to trace the variable changes and then update the title.
Little performance tip if somebody has a datastore kind of service with key -> value pairs:
If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.
app.factory('dataStore', function () {
var store = { data: [], change: [] };
// when storing the data, updating the timestamp
store.setData = function(key, data){
store.data[key] = data;
store.setChange(key);
}
// get the change to watch
store.getChange = function(key){
return store.change[key];
}
// set the change
store.setChange = function(key){
store.change[key] = new Date().getTime();
}
});
And in a directive you are only watching the timestamp to change
app.directive("myDir", function ($scope, dataStore) {
$scope.dataStore = dataStore;
$scope.$watch('dataStore.getChange("myKey")', function(newVal, oldVal){
if(newVal !== oldVal && newVal){
// Data changed
}
});
});
First you have some data in a specific type like int here:
int x = 0x7fffffff://==nan in binary representation
Then you want to access the same variable as an other type like float: You can decide between
float y = reinterpret_cast<float&>(x);
//this could only be used in cpp, looks like a function with template-parameters
or
float y = *(float*)&(x);
//this could be used in c and cpp
BRIEF: it means that the same memory is used as a different type. So you could convert binary representations of floats as int type like above to floats. 0x80000000 is -0 for example (the mantissa and exponent are null but the sign, the msb, is one. This also works for doubles and long doubles.
OPTIMIZE: I think reinterpret_cast would be optimized in many compilers, while the c-casting is made by pointerarithmetic (the value must be copied to the memory, cause pointers couldn't point to cpu- registers).
NOTE: In both cases you should save the casted value in a variable before cast! This macro could help:
#define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })
The spirit of handlebars is that it is "logicless". Sometimes this makes us feel like we are fighting with it, and sometimes we end up with ugly nested if/else logic. You could write a helper; many people augment handlebars with a "better" conditional operator or believe that it should be part of the core. I think, though, that instead of this,
{{#if FriendStatus.IsFriend}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
{{#if FriendStatus.FriendRequested}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
{{/if}}
you might want to arrange things in your model so that you can have this,
{{#if is_friend }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{/if}}
{{#if is_not_friend_yet }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{/if}}
{{#if will_never_be_my_friend }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
Just make sure that only one of these flags is ever true. Chances are, if you are using this if/elsif/else
in your view, you are probably using it somewhere else too, so these variables might not end up being superfluous.
Keep it lean.
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc
eg.
if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
//do stuff
}
timeIntervalSinceReferenceDate
converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate
returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.
here is the easiest way to add progress bar in android Web View.
Add a boolean field in your activity/fragment
private boolean isRedirected;
This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
isRedirected = true;
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Here when start loading it will call onPageStarted
. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished
method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource()
before onPageFinished
method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected)
in onLoadResource()
in onPageFinished()
method before dismissing the Progress Dialog you can write your 10 second time delay code
That's it. Happy coding :)
To input AN ENTIRE LINE containing lot of spaces you can use getline(cin,string_variable);
eg:
string input;
getline(cin, input);
This format captures all the spaces in the sentence untill return
is pressed
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
_x000D_
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
_x000D_
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
Follow these links for the MSDN descriptions of:
Math.Floor
, which rounds down towards negative infinity.Math.Ceiling
, which rounds up towards positive infinity.Math.Truncate
, which rounds up or down towards zero.Math.Round
, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)
" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)
" becoming 3).The following diagram and table may help:
-3 -2 -1 0 1 2 3
+--|------+---------+----|----+--|------+----|----+-------|-+
a b c d e
a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8
====== ====== ===== ===== =====
Floor -3 -1 0 1 2
Ceiling -2 0 1 2 3
Truncate -2 0 0 1 2
Round (ToEven) -3 0 0 2 3
Round (AwayFromZero) -3 -1 0 2 3
Note that Round
is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
With the other functions, you have to use multiply/divide trickery to achieve the same effect:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15
In order to avoid to pass this argument i use class derived from Application
public class MyApplication extends Application {
private static Context sContext;
@Override
public void onCreate() {
super.onCreate();
sContext= getApplicationContext();
}
public static Context getContext() {
return sContext;
}
and invoke MyApplication.getContext()
in Helper classes.
Don't forget to update the manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<activity....>
......
</activity>
</application>
</manifest>
Sorry, there is no operation similar to LIKE IN
in mysql.
If you want to use the LIKE operator without a join, you'll have to do it this way:
(field LIKE value OR field LIKE value OR field LIKE value)
You know, MySQL will not optimize that query, FYI.
You have to make a change in the asterisk.conf file located at /etc/asterisk
astrundir => /var/run/asterisk
Reboot your system and check
Hope this helps you
There are lot of factors , first see whether server returns the result, then check between server and client.
rectify them from server side first,then check the writing condition between server and client !
server side rectify the time outs between the datalayer and server from client side rectify the time out and number of available connections !
If none of your routes contain closures, but you are still getting this error, please check
routes/api.php
Laravel has a default auth api route in the above file.
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which can be commented or replaced with a call to controller method if required.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
var ExcelToJSON = function() {_x000D_
_x000D_
this.parseExcel = function(file) {_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function(e) {_x000D_
var data = e.target.result;_x000D_
var workbook = XLSX.read(data, {_x000D_
type: 'binary'_x000D_
});_x000D_
workbook.SheetNames.forEach(function(sheetName) {_x000D_
// Here is your object_x000D_
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
var json_object = JSON.stringify(XL_row_object);_x000D_
console.log(JSON.parse(json_object));_x000D_
jQuery( '#xlx_json' ).val( json_object );_x000D_
})_x000D_
};_x000D_
_x000D_
reader.onerror = function(ex) {_x000D_
console.log(ex);_x000D_
};_x000D_
_x000D_
reader.readAsBinaryString(file);_x000D_
};_x000D_
};_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
_x000D_
var files = evt.target.files; // FileList object_x000D_
var xl2json = new ExcelToJSON();_x000D_
xl2json.parseExcel(files[0]);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
<input id="upload" type=file name="files[]">_x000D_
</form>_x000D_
_x000D_
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
<script>_x000D_
document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
</script>
_x000D_
This problem happened with me when I used jQUery Fancybox inside a website with many others jQuery plugins. When I used the LightBox (site here) instead of Fancybox, the problem is gone.
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
Any reason not to use Random.NextDouble
and then cast to float
? That will give you a float between 0 and 1.
If you want a different form of "best" you'll need to specify your requirements. Note that Random
shouldn't be used for sensitive matters such as finance or security - and you should generally reuse an existing instance throughout your application, or one per thread (as Random
isn't thread-safe).
EDIT: As suggested in comments, to convert this to a range of float.MinValue
, float.MaxValue
:
// Perform arithmetic in double type to avoid overflowing
double range = (double) float.MaxValue - (double) float.MinValue;
double sample = rng.NextDouble();
double scaled = (sample * range) + float.MinValue;
float f = (float) scaled;
EDIT: Now you've mentioned that this is for unit testing, I'm not sure it's an ideal approach. You should probably test with concrete values instead - making sure you test with samples in each of the relevant categories - infinities, NaNs, denormal numbers, very large numbers, zero, etc.
Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csv
module, which is more desirable than parsing it manually. I've also put in a bit of namedtuple
goodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.
import csv
from collections import namedtuple
from time import localtime, strftime
# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
grades = [[e.strip() for e in s.split(',')] for s in files]
# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))
request = open('requests.dat', 'w')
cont = 'y'
while cont.lower() == 'y':
answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
for student in grades:
if answer == student[0]:
print '%s, %s %s %s' % (student[1], student[2], student[0], student[3])
time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
print time
print 'Exams - %s, %s, %s' % student[11:14]
print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
total = sum(int(x) for x in student[4:14])
print 'Total points earned - %d' % total
grade = total / 5.5
if grade >= 90:
letter = 'an A'
elif grade >= 80:
letter = 'a B'
elif grade >= 70:
letter = 'a C'
elif grade >= 60:
letter = 'a D'
else:
letter = 'an F'
if letter = 'an A':
print 'Grade: %s, that is equal to %s.' % (grade, letter)
else:
print 'Grade: %.2f, that is equal to %s.' % (grade, letter)
request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))
print
cont = raw_input('Would you like to search again? ')
print 'Goodbye.'
Solved the issue for me :
Range(Cells(1, 1), Cells(100, 1)).Select
For Each xCell In Selection
xCell.Value = CDate(xCell.Value)
Next xCell
This works for me, with Mac OS Sierra using Python,
options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
This code will not work (you can check in firebug jQuery.ui is undefined):
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
Try use follow code:
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
$.browser
has been removed from JQuery 1.9. You can to use Modernizr project instead
http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed
UPDATE TO SUPPORT IE 10 AND IE 11 (TRIDENT version)
To complete the @daniel.moura answer, here is a version which support IE 11 and +
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie)[\s?]([\w.]+)/.exec( ua ) ||
/(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident)
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
// log removed - adds an extra dependency
//log(jQuery.browser)
@media print{
/* use your css selector */
div{
page-break-inside: avoid;
}
}
For all new browser this solution works. See caniuse.com/#search=page-break-inside
This is what I came op for a thread safe bounded blocking queue.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
public class BlockingBuffer<T>
{
private Object t_lock;
private Semaphore sema_NotEmpty;
private Semaphore sema_NotFull;
private T[] buf;
private int getFromIndex;
private int putToIndex;
private int size;
private int numItems;
public BlockingBuffer(int Capacity)
{
if (Capacity <= 0)
throw new ArgumentOutOfRangeException("Capacity must be larger than 0");
t_lock = new Object();
buf = new T[Capacity];
sema_NotEmpty = new Semaphore(0, Capacity);
sema_NotFull = new Semaphore(Capacity, Capacity);
getFromIndex = 0;
putToIndex = 0;
size = Capacity;
numItems = 0;
}
public void put(T item)
{
sema_NotFull.WaitOne();
lock (t_lock)
{
while (numItems == size)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
buf[putToIndex++] = item;
if (putToIndex == size)
putToIndex = 0;
numItems++;
Monitor.Pulse(t_lock);
}
sema_NotEmpty.Release();
}
public T take()
{
T item;
sema_NotEmpty.WaitOne();
lock (t_lock)
{
while (numItems == 0)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
item = buf[getFromIndex++];
if (getFromIndex == size)
getFromIndex = 0;
numItems--;
Monitor.Pulse(t_lock);
}
sema_NotFull.Release();
return item;
}
}
The reason the code will not work without void
is because the System.out.println(String string)
method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void
keyword in its signature.
You can see the documentation of the System.out.println here:
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29
To press the issue further, println is a classic example of a method which is performing computation as a "side effect."
Following code worked for me.
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)
To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:
sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1
I had a similar problem using axes. The class parameter is frameon
but the kwarg is frame_on
. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon
frame_on
data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False) # Old
ax.set(frame_on=False) # New
plt.show()
In order to exit from the app on pressing back button you have to first clear all the top activities and then start the ACTION_MAIN of android phone
So, you have to write all these code only which is mentioned below :
Note : In your case MainActivity get replaced by YourActivity
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
quit();
}
}).create().show();
}
public void quit() {
Intent start = new Intent(Intent.ACTION_MAIN);
start.addCategory(Intent.CATEGORY_HOME);
start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
start.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(start);
}
Adding to @Narendra solution...
IMPORTANT: When working with fragments, navigations is closely related to host acivity so, you can't justo jump from fragment to fragment without implement that fragment class in host Activity.
Sample:
public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {
Also, check your host activity has the next override function:
@Override
public void onFragmentInteraction(Uri uri) {}
Hope this helps...
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
Hazar is right with his \t
. Here's the full list of escape characters for C#:
\'
for a single quote.
\"
for a double quote.
\\
for a backslash.
\0
for a null character.
\a
for an alert character.
\b
for a backspace.
\f
for a form feed.
\n
for a new line.
\r
for a carriage return.
\t
for a horizontal tab.
\v
for a vertical tab.
\uxxxx
for a unicode character hex value (e.g. \u0020
).
\x
is the same as \u
, but you don't need leading zeroes (e.g. \x20
).
\Uxxxxxxxx
for a unicode character hex value (longer form needed for generating surrogates).
Copy the value of path to notepad and check if this corresponds with the echo %path% in terminal window and make changes if needed. Then delete the old path value and paste the notepad value back in. I assume some invisible character entered there by some installation corrupted the path value.
A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)
Take an extension from the file and see if it is in the set of extensions:
>>> import os
>>> extensions = set(['.mp3','.avi'])
>>> file_name = 'test.mp3'
>>> extension = os.path.splitext(file_name)[1]
>>> extension in extensions
True
Using a set because time complexity for lookups in sets is O(1) (docs).
If you're using form.serialize() - you need to give each form element a name like this:
<input id="firstName" name="firstName" ...
And the form gets serialized like this:
firstName=Chris&lastName=Halcrow ...
Its just like creating a WAR
file of your project, you can do it in several ways (from Eclipse, command line, maven).
If you want to do from command line, the command is
jar -cvf my_web_app.war *
Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
Why not just wrap the "osopen" with a try/except and let the underlying OS sort out whether the file is valid?
This seems like much less work and is valid no matter which OS you use.
You want the background color of your main view to be semi-transparent? There's nothing behind it... so nothing will really happen however:
If you want to modify the alpha of any view, use the alpha property:
UIView *someView = [[UIView alloc] init];
...
someView.alpha = 0.8f; //Sets the opacity to 80%
...
Views themselves have the alpha transparency, not just UIColor.
But since your problem is that you can't read text on top of the images... either:
UIView *overlay = [[[UIView alloc] init] autorelease]; overlay.frame = self.view.bounds; overlay.alpha = 0.2f; [self.view addSubview:overlay]; ... Add the rest of the views
Posting as answer, as I don't have the privilege to comment.
Point to note: follow the accepted answer posted by "That Dave Guy".
After setting the variables, make sure you set the appropriate permissions to the java directory where it's installed.
chmod -R 755 /usr/java
In case you want to do it yourself..
List<Integer> commons = new ArrayList<Integer>();
for (Integer igr : group1) {
if (group2.contains(igr)) {
commons.add(igr);
}
}
System.out.println("Common elements are :: -");
for (Integer igr : commons) {
System.out.println(" "+igr);
}
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
If you're looking for something like MySQL's DUMP
, then good news: SQL Server 2008 Management Studio added that ability.
In SSMS, just right-click on the DB in question and select Tasks > Generate Scripts. Then in the 2nd page of the options wizard, make sure to select that you'd like the data scripted as well, and it will generate what amounts to a DUMP
file for you.
ResourceManager
shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:
Assuming a project namespace: UberSoft.WidgetPro
And your resx contains:
You can just use:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
The most easy to build, easy to use implementation I have found is made by theguardianproject team: https://github.com/guardianproject/android-ffmpeg
Check out this Sample Camera Preview code, CameraPreview
. This would help you in devloping video recording code for video preview, create MediaRecorder
object, and set video recording parameters.
public static void main(String[] args) {
String value = " Chlamydia_spp. IgG, IgM & IgA Abs (8006) ";
System.out.println(value.replaceAll("[^A-Za-z0-9]", ""));
}
output: ChlamydiasppIgGIgMIgAAbs8006
Github: https://github.com/AlbinViju/Learning/blob/master/StripNonAlphaNumericFromString.java
The debug_backtrace()
function is the only way to know this, if you're lazy it's one more reason you should code the GetCallingMethodName()
yourself. Fight the laziness! :D
'\u0000'
stands for null
. So if you print an uninitialized char variable , you'll get nothing.
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)
function verify1() {
jQuery.ajax({
type: 'POST',
url:"functions.php",
data: new FormData($("#infoForm1")[0]),
processData: false,
contentType: false,
success: function(returnval) {
$("#show1").html(returnval);
$('#show1').show();
}
});
}
Just print the file details and check. You will get Output. If error let me know.
What worked for me is:
GoTo
setting.gradle
And you are done!
==
is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__
or __cmp__
methods.)
is
is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is
operation.
You use is
(and is not
) for singletons, like None
, where you don't care about objects that might want to pretend to be None
or where you want to protect against objects breaking when being compared against None
.
You need to adjust shell path , the path will be set in either .bashrc
or .bash_profile
in your home directory, more likely .bash_profile
.
So add into the path similar to the below and keep what you already have in the path, each segment is separated by a colon:
export PATH="/usr/local/bin:/usr/bin/git:/usr/bin:/usr/local/sbin:$PATH"
Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.
You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9">
for numbers
or
<input type = "email" maxlength="9">
for email
validation will show up
For view procedure in name wise
select name from mysql.proc
below code used to list all the procedure and below code is give same result as show procedure status
select * from mysql.proc
We have a no code past the 80th character column that is controversial in our C++ development team. Liked and code review enforced by some; Despised by others.
Also, we have a very controversial C++ throw(), throw(...) specification standard. Religiously used by some and demonized by others. Both camps cite discussions and experts to enforce their respective positions.
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
There is no problem with displaying HTML code in blade templates.
For test, you can add to routes.php only one route:
Route::get('/', function () {
$data = new stdClass();
$data->page_desc
= '<strong>aaa</strong><em>bbb</em>
<p>New paragaph</p><script>alert("Hello");</script>';
return View::make('hello')->with('content', $data);
}
);
and in hello.blade.php
file:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
{{ $content->page_desc }}
</body>
</html>
For the following code you will get output as on image
So probably page_desc
in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags
EDIT
I've also tested it with putting the same code into database:
Route::get('/', function () {
$data = User::where('id','=',1)->first();
return View::make('hello')->with('content', $data);
}
);
Output is exactly the same in this case
Edit2
I also don't know if Pages
is your model or it's a vendor model. For example it can have accessor inside:
public function getPageDescAttribute($value)
{
return htmlspecialchars($value);
}
and then when you get page_desc
attribute you will get modified page_desc
with htmlspecialchars
. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages
class
The Eclipse UI is a little bit confusing.
The Import -> "Existing projects into workspace" actually means import "Existing Eclipse projects into workspace". That's why you can't click on finish: the import option looks for a .project
file (the file used by Eclipse to store the project options) in the directory that you have chosen.
To import existing source code that doesn't have an Eclipse project file you have the following options (I suppose that you want to create a Java project):
New project inside the workspace dir: Create a new empty Java project into the workspace (File->New->Java Project). Then right click on the source folder and choose Import...->General->File system then choose your files, and it will make a copy of your files.
Tip: you can drag&drop your files from the Finder into the src folder.
Create an eclipse project in your existing dir: Create a new Java project, but in the "New Java Project" window:
The new version is hard to find. Select the app, then look for "3 dot menu" in upper right corner.
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
Create a view and return it as a partial view:
public class AssetsController : Controller
{
protected void SetMIME(string mimeType)
{
this.Response.AddHeader("Content-Type", mimeType);
this.Response.ContentType = mimeType;
}
// this will render a view as a Javascript file
public ActionResult GlobalJS()
{
this.SetMIME("text/javascript");
return PartialView();
}
}
Then in the GlobalJS view add the javascript code like (adding the // will make visual studio intellisense read it as java-script)
//<script>
$(document).ready(function () {
alert('@ViewBag.PropertyName');
});
//</script>
Then in your final view you can add a reference to the javascript just like this.
<script src="@Url.Action("GlobalJS", "Assets")"></script>
Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.
public class MyFinalViewController : Controller
{
public ActionResult Index()
{
ViewBag.PropertyName = "My ViewBag value!";
return View();
}
}
Hope it helps.
He want an elegant and proper solution try this small regex pattern matcher.
This is specifically for India.(First digit can't be zero and and then can be any 9 digits)
return mobile.matches("[1-9][0-9]{9}");
Pattern Breakdown:-
[1-9]
matches first digit and checks if number(integer) lies between(inclusive) 1 to 9
[0-9]{9}
matches the same thing but {9}
tells the pattern that it has to check for upcoming all 9 digits.
Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.
Create a new style
<style name="my_dialog_theme" parent="ThemeOverlay.AppCompat.Dialog">
<item name="colorAccent">@color/colorAccent</item> <!--header background-->
<item name="android:windowBackground">@color/colorPrimary</item> <!--calendar background-->
<item name="android:colorControlActivated">@color/colorAccent</item> <!--selected day-->
<item name="android:textColorPrimary">@color/colorPrimaryText</item> <!--days of the month-->
<item name="android:textColorSecondary">@color/colorAccent</item> <!--days of the week-->
</style>
Then initialize the dialog
Calendar mCalendar = new GregorianCalendar();
mCalendar.setTime(new Date());
new DatePickerDialog(mContext, R.style.my_dialog_theme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//do something with the date
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();
Result:
Broken pipe means you wrote to a connection that is already closed by the other end.
isConnected()
does not detect this condition. Only a write does.
is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()
It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.
for my auth server... this works. i like to have options for /auth for my own humanized readability... or also i have it configured by port/upstream for machine to machine.
####################################################
upstream auth {
server 127.0.0.1:9011 weight=1 fail_timeout=300s;
keepalive 16;
}
if (-d $request_filename) {
rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}
location /auth {
proxy_pass http://$http_host:9011;
proxy_set_header Origin http://$host;
proxy_set_header Host $http_host:9011;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
}
#####################################################################
# #
# Proxies for all the Other servers on other ports upstream #
# #
#####################################################################
#######################
# Fusion #
#######################
server {
listen 9001 ssl;
############# Lock it down ################
# SSL certificate locations
ssl_certificate /etc/letsencrypt/live/allineed.app/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/allineed.app/privkey.pem;
# Exclusions
include snippets/exclusions.conf;
# Security
include snippets/security.conf;
include snippets/ssl.conf;
# Fastcgi cache rules
include snippets/fastcgi-cache.conf;
include snippets/limits.conf;
include snippets/nginx-cloudflare.conf;
########### Location upstream ##############
location ~ / {
proxy_pass http://auth;
proxy_set_header Origin http://$host;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_http_version 1.1;
}
if (-d $request_filename) {
rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}
}
if you can access the head add
<style>
/*...some style */
</style>
the way Hussein showed you
and the ultra hacky
<style>
</style>
in the html it will work but its ugly.
or javascript it the best way if you can use it in you case
If somebody comes looking it should look like this:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/domains/example.com/html
ErrorLog /var/www/domains/example.com/apache.error.log
CustomLog /var/www/domains/example.com/apache.access.log common
php_flag log_errors on
php_flag display_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/domains/example.com/php.error.log
</VirtualHost>
This is for development only since display_error
is turned on. You will notice that the Apache error log is separate from the PHP error log. The good stuff is in php.error.log
.
Take a look here for the error_reporting
key http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
Website and Project>>website are two different methods of creating ASP.NET application using visual studio. One is projectless and another is project environment. Differences are as
there no much basic difference in using either approach. But if you are creating website that will take longer time, opt for project environment.
If you want to check on just one RadioButton
you can use the isChecked
function
if(radioButton.isChecked())
{
// is checked
}
else
{
// not checked
}
and if you have a RadioGroup
you can use
if (radioGroup.getCheckedRadioButtonId() == -1)
{
// no radio buttons are checked
}
else
{
// one of the radio buttons is checked
}
I think the best answer is
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
chars ++;
}
words += new StringTokenizer(line, " ,").countTokens();
}
You should always use audio/mpeg, because firefox cannot play audio/mpeg3 files
Small mistake -- I knew I had to open/close my cmd to get the updated path to reflect. Using Jupyter Notebook I had to shutdown the client and re-initialize it also.
If you're using pandas
there is a function hidden in pandas.io.json._normalize
1 called nested_to_record
which does this exactly.
from pandas.io.json._normalize import nested_to_record
flat = nested_to_record(my_dict, sep='_')
1 In pandas versions 0.24.x
and older use pandas.io.json.normalize
(without the _
)
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.
To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.
I think AddRange is better implemented like so:
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
It saves you a list copy. Also if you want to micro-optimise you could do adds for up to N items and if more than N items where added do a reset.
&
is bitwise.
&&
is logical.
&
evaluates both sides of the operation.
&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
I have reproduced the issue in my system,
postgres=# alter user my-sys with password 'pass11';
ERROR: syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
^
Here is the issue,
psql is asking for input and you have given again the alter query see postgres-#
That's why it's giving error at alter
postgres-# alter user "my-sys" with password 'pass11';
ERROR: syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
^
Solution is as simple as the error,
postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE
I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.
Let's assume an application downloads an XML, and then saves the XML to a database.
I have 2 projects here which build my solution: FTP and a SaveDatabase.
So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.
Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.
During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.
See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.
class FTP
{
public void Begin()
{
string filePath = DownloadFileFromFtpAndReturnPathName();
SaveDatabase sd = new SaveDatabase();
sd.Begin(filePath, NotifyFtpComplete());
}
private void NotifyFtpComplete()
{
//Code to send file to FTP site
}
}
class SaveDatabase
{
private void Begin(string filePath, delegateType NotifyJobComplete())
{
SaveToTheDatabase(filePath);
/* InvokeTheDelegate -
* here we can execute the NotifyJobComplete
* method at our preferred moment in the application,
* despite the method being private and belonging
* to a different class.
*/
NotifyJobComplete.Invoke();
}
}
So, with that explained, we can do it for real now with this Console Application using C#
using System;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that
* the SaveToDatabase cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
//Note, this NotifyDelegate type is defined in the SaveToDatabase project
NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);
SaveToDatabase sd = new SaveToDatabase();
sd.Start(nofityDelegate);
Console.ReadKey();
}
/* this is the method which will be delegated -
* the only thing it has in common with the NofityDelegate
* is that it takes 0 parameters and that it returns void.
* However, it is these 2 which are essential.
* It is really important to notice that it writes
* a variable which, due to no constructor,
* has not yet been called (so _notice is not initialized yet).
*/
private static void NotifyIfComplete()
{
Console.WriteLine(_notice);
}
private static string _notice = "Notified";
}
public class SaveToDatabase
{
public void Start(NotifyDelegate nd)
{
/* I shouldn't write to the console from here,
* just for demonstration purposes
*/
Console.WriteLine("SaveToDatabase Complete");
Console.WriteLine(" ");
nd.Invoke();
}
}
public delegate void NotifyDelegate();
}
I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.
However, lastly, we can make it more useful by changing the delegate type to include a parameter.
using System.Text;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that the SaveToDatabase
* cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
SaveToDatabase sd = new SaveToDatabase();
/* Please note, that although NotifyIfComplete()
* takes a string parameter, we do not declare it,
* all we want to do is tell C# where the method is
* so it can be referenced later,
* we will pass the parameter later.
*/
var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);
sd.Start(notifyDelegateWithMessage );
Console.ReadKey();
}
private static void NotifyIfComplete(string message)
{
Console.WriteLine(message);
}
}
public class SaveToDatabase
{
public void Start(NotifyDelegateWithMessage nd)
{
/* To simulate a saving fail or success, I'm just going
* to check the current time (well, the seconds) and
* store the value as variable.
*/
string message = string.Empty;
if (DateTime.Now.Second > 30)
message = "Saved";
else
message = "Failed";
//It is at this point we pass the parameter to our method.
nd.Invoke(message);
}
}
public delegate void NotifyDelegateWithMessage(string message);
}
You can use the following command c:\path of you tomcat directory\bin>catalina run
As the "GNU C Library Reference Manual" says
off_t
This is a signed integer type used to represent file sizes.
In the GNU C Library, this type is no narrower than int.
If the source is compiled with _FILE_OFFSET_BITS == 64 this
type is transparently replaced by off64_t.
and
off64_t
This type is used similar to off_t. The difference is that
even on 32 bit machines, where the off_t type would have 32 bits,
off64_t has 64 bits and so is able to address files up to 2^63 bytes
in length. When compiling with _FILE_OFFSET_BITS == 64 this type
is available under the name off_t.
Thus if you want reliable way of representing file size between client and server, you can:
off64_t
type and stat64()
function accordingly (as it fills structure stat64
, which contains off64_t
type itself). Type off64_t
guaranties the same size on 32 and 64 bit machines.-D_FILE_OFFSET_BITS == 64
and use usual off_t
and stat()
.off_t
to type int64_t
with fixed size (C99 standard).
Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:7.20.1.1 Exact-width integer types
1 The typedef name intN_t designates a signed integer type with width N ,
no padding bits, and a two’s complement representation. Thus, int8_t
denotes such a signed integer type with a width of exactly 8 bits.
without mentioning.
And about implementation:
7.20 Integer types <stdint.h>
... An implementation shall provide those types described as ‘‘required’’,
but need not provide any of the others (described as ‘‘optional’’).
...
The following types are required:
int_least8_t uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t
All other types of this form are optional.
Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.
EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81
There is built in functionality for this using the JavaScriptSerializer Class:
var json = JavaScriptSerializer.Serialize(data);
AndroidManifest.xml:
<uses-sdk
android:minSdkVersion=...
android:targetSdkVersion="11" />
and
Project Properties -> Project Build Target = 11 or above
These 2 things fixed the problem for me!
This is a Play 2 controller to initialize the H2 TCP and Web servers:
package controllers;
import org.h2.tools.Server;
import play.mvc.Controller;
import play.mvc.Result;
import java.sql.SQLException;
/**
* Play 2 controller to initialize H2 TCP Server and H2 Web Console Server.
*
* Once it's initialized, you can connect with a JDBC client with
* the URL `jdbc:h2:tcp://127.0.1.1:9092/mem:DBNAME`,
* or can be accessed with the web console at `http://localhost:8082`,
* and the URL JDBC `jdbc:h2:mem:DBNAME`.
*
* @author Mariano Ruiz <[email protected]>
*/
public class H2ServerController extends Controller {
private static Server h2Server = null;
private static Server h2WebServer = null;
public static synchronized Result debugH2() throws SQLException {
if (h2Server == null) {
h2Server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
h2Server.start();
h2WebServer = Server.createWebServer("-web","-webAllowOthers","-webPort","8082");
h2WebServer.start();
return ok("H2 TCP/Web servers initialized");
} else {
return ok("H2 TCP/Web servers already initialized");
}
}
}
For those like me who have been groping your way through much-more-than-you-need-to-know-right-now tutorials and Docs, and just want to see the thing working for starters, I found the only thing I had to do was add:
AddHandler cgi-script .pl .cgi
To my configuration file.
http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addhandler
For my situation this works best as I can put my perl script anywhere I want, and just add the .pl or .cgi extension.
Dave Sherohman's answer mentions the AddHandler solution also.
Of course you still must make sure the permissions/ownership on your script are set correctly, especially that the script will be executable. Take note of who the "user" is when run from an http request - eg, www or www-data.
A simple ddply
option:
ddply(test,.(id),function(x) head(x,1))
If speed is an issue, a similar approach could be taken with data.table
:
testd <- data.table(test)
setkey(testd,id)
testd[,.SD[1],by = key(testd)]
or this might be considerably faster:
testd[testd[, .I[1], by = key(testd]$V1]
Installation:
for 10.10:
sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
for 11.04
sudo add-apt-repository "deb http://archive.canonical.com/ natty partner"
Continue with:
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin
Use as default:
sudo update-alternatives --config java
Installing JDK:
sudo apt-get install sun-java6-jdk
Source code (to be used in development):
sudo apt-get install sun-java6-source
Source of these instructions: https://help.ubuntu.com/community/Java
you can't get city location by ip. here you can get country with jquery:
$.get("http://ip-api.com/json", function(response) {
console.log(response.country);}, "jsonp");
Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html
Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.
There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices
.
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
See this section on the MediaWiki docs
These are the key parameters.
prop=revisions&rvprop=content&rvsection=0
rvsection = 0 specifies to only return the lead section.
See this example.
To get the HTML, you can use similarly use action=parse http://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&page=pizza
Note, that you'll have to strip out any templates or infoboxes.
.load()
& .unload()
have been deprecated$(window).load();
Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.
$(document).ready();
This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.
$(window).unload();
This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.
To sum up, ready() will be fired before load(), and unload() will be the last to be fired.
I drilled down the formation of the drop down list instead of using @Html.DropDownList()
. This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
@foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>
}
</select>
Full worked solution on 2021.
The binding with IP is not worked. The asterisk solved the problem.
<bindings>
<binding protocol="http" bindingInformation="*:63000:localhost" />
<binding protocol="http" bindingInformation="*:63000:*" />
</bindings>
https://www.theancientscroll.com/tech/4-steps-aspnet-web-apps-lan/753/
I would suggest:
def foo(element):
do something
if not check: return
do more (because check was succesful)
do much much more...
I'm using apache-tomcat-7.0.70 with jdk1.7.0_45 and none of the solutions here and elsewhere on stackoverflow worked for me. Just sharing this solution as it hopefully might help someone as this is very high on Google's search
What worked is doing BOTH of these steps:
Starting my tomcat with "export JAVA_OPTS="$JAVA_OPTS -Dhttps.protocols=TLSv1.2" by adding it to tomcat/bin/setenv.sh (Syntax slightly different on Windows)
Manually building/forcing HttpClients or anything else you need with the TLS1.2 protocol:
Context ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
HttpClient httpClient = HttpClientBuilder.create().setSslcontext(ctx).build();
HttpPost httppost = new HttpPost(scsTokenVerificationUrl);
List<NameValuePair> paramsAccessToken = new ArrayList<NameValuePair>(2);
paramsAccessToken.add(new BasicNameValuePair("token", token));
paramsAccessToken.add(new BasicNameValuePair("client_id", scsClientId));
paramsAccessToken.add(new BasicNameValuePair("secret", scsClientSecret));
httppost.setEntity(new UrlEncodedFormEntity(paramsAccessToken, "utf-8"));
//Execute and get the response.
HttpResponse httpResponseAccessToken = httpClientAccessToken.execute(httppost);
String responseJsonAccessToken = EntityUtils.toString(httpResponseAccessToken.getEntity());
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
Bootstrap naming conventions carry styles of their own, col-XS-1 refers to a column being 8.33% of the containing element wide. Your text, would most likely expand far beyond the specified width, and couldn't possible be centered within it. If you wanted it to constrain to the div, you could use something like css word-break.
For centering the content within an element large enough to expand beyond the text, you have two options.
Option 1: HTML Center Tag
<div class="row">
<div class="col-xs-1 center-block">
<center>
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</center>
</div>
</div>
Option 2: CSS Text-Align
<div class="row">
<div class="col-xs-1 center-block" style="text-align:center;">
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
If you wanted everything to constrain to the width of the column
<div class="row">
<div class="col-xs-1 center-block" style="text-align:center;word-break:break-all;">
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
UPDATE - Using Bootstrap's text-center class
<div class="row">
<div class="col-xs-1 center-block text-center">
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
FlexBox Method
<div class="row">
<div class="flexBox" style="
display: flex;
flex-flow: row wrap;
justify-content: center;">
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
You can take advantage of the placeholder and use:
input:not(:placeholder-shown) {
border: 1px solid red;
}
$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
let pic=[
"https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif",
"https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif"
];
$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d1">
<div class="c1">
<a href="#"><img src="img1_on.gif"></a>
<a href="#"><img src="img2_on.gif"></a>
</div>
</div>
_x000D_
Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.
<div style="background-color: yellow;">
<div style="float: left;width: 65%;">column a</div>
<div style="float: right;width: 35%;">column b</div>
<div style="clear: both;"></div>
</div>
Updated to address some comments and my own thoughts:
This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.
The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.
It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like clearfix or by simply having overflow: hidden on the parent element.
Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.
The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.
You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation).
This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.
<div style="overflow: hidden;">
<div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
<div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
</div>
You can see an example of this technique on the bowers and wilkins website (see the four horizontal spotlight images the bottom of the page).
As long as you know how to use lambda and the "key" argument, a simple solution is:
max_index = max( range( len(my_list) ), key = lambda index : my_list[ index ] )
header("Content-type: image/png");
echo file_get_contents(".../image.png");
The first step is retrieve the image from a particular location and then store it on to a variable for that purpose we use the function file_get_contents() with the destination as the parameter. Next we set the content type of the output page as image type using the header file. Finally we print the retrieved file using echo.
By default, Log4j
logs to standard output and that means you should be able to see log messages on your Eclipse's console view. To log to a file you need to use a FileAppender
explicitly by defining it in a log4j.properties
file in your classpath.
Create the following log4j.properties
file in your classpath. This allows you to log your message to both a file as well as your console.
log4j.rootLogger=debug, stdout, file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=example.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n
Note: The above creates an example.log in your current working directory (i.e. Eclipse's project directory) so that the same log4j.properties could work with different projects without overwriting each other's logs.
References:
Apache log4j 1.2 - Short introduction to log4j
Vendor independent version, solely relies on ADO.NET interfaces; 2 ways:
public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
using (var conn = new T())
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Connection.ConnectionString = _connectionString;
cmd.Connection.Open();
var table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
}
public DataTable Read2<S, T>(string query) where S : IDbConnection, new()
where T : IDbDataAdapter, IDisposable, new()
{
using (var conn = new S())
{
using (var da = new T())
{
using (da.SelectCommand = conn.CreateCommand())
{
da.SelectCommand.CommandText = query;
da.SelectCommand.Connection.ConnectionString = _connectionString;
DataSet ds = new DataSet(); //conn is opened by dataadapter
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
I did some performance testing, and the second approach always outperformed the first.
Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
dt = Read1<MySqlConnection>(query); // ~9800ms
dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms
dt = Read1<SQLiteConnection>(query); // ~4000ms
dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms
dt = Read1<SqlCeConnection>(query); // ~5700ms
dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms
dt = Read1<SqlConnection>(query); // ~850ms
dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms
dt = Read1<VistaDBConnection>(query); // ~3900ms
dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
Read1
looks better on eyes, but data adapter performs better (not to confuse that one db outperformed the other, the queries were all different). The difference between the two depended on query though. The reason could be that Load
requires various constraints to be checked row by row from the documentation when adding rows (its a method on DataTable
) while Fill
is on DataAdapters which were designed just for that - fast creation of DataTables.
I take it from your question that your hover effect changes the content of your page. In that case, my advice is to:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Alternatively, you can edit your page that there is no content change.
In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):
touchstart
touchmove
touchend
mouseover
mouseenter
mouseover
, mouseenter
or mousemove
event changes the page content, the following events are never fired.mousemove
mousedown
mouseup
click
It does not seem possible to simply tell the webbrowser to skip the mouse events.
What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.
To recap:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Note that there is no action on touchend
!
This clearly works for mouse events: mouseenter
and mouseleave
(slightly improved versions of mouseover
and mouseout
) are fired, and add and remove the hover.
If the user actually click
s a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.
This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter
, and since this causes no content changes (it was already added), the click
event is also fired, and the link is followed without the need for the user to click again!
The 300ms delay that a browser has between a touchstart
event and click
is actually put in good use because the hover effect will be shown during this short time.
If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave
event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove
.
That's it!
Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.
I've found the following problems with the following alternatives:
touchend
: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.touchend
that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. See Walter Roman's answer on this page. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend
is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).mouseover
or mousemove
event.For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:
java -jar filex.jar
The file will execute in terminal.
One way you do this is set a counter and if number exceeds the certain number return false. easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
Dominc has the right idea, but put the calculation on the other side of the expression.
SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)
This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.
I made the same error using sudo for my installation. (oops)
brew install python
brew linkapps python
brew link --overwrite python
This brought everything back to normal.
Your application has an AppCompat theme
<application
android:theme="@style/AppTheme">
But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
You could define your own fullscreen theme like so (notice AppCompat
in the parent=
)
<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
Then set that on the Activity.
<activity android:name=".MainActivity"
android:theme="@style/AppFullScreenTheme" >
Note: There might be an AppCompat theme that's already full screen, but don't know immediately
final
just binds the reference to particular object. You are free to change the 'state' of that object, but not the object itself.Use NSNumberFormatter
with maximumFractionDigits
as below:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);
And you will get 12.35
find $HOME -name "hello.c" -print
This will search the whole $HOME
(i.e. /home/username/
) system for any files named “hello.c” and display their pathnames:
/Users/user/Downloads/hello.c
/Users/user/hello.c
However, it will not match HELLO.C
or HellO.C
. To match is case insensitive pass the -iname
option as follows:
find $HOME -iname "hello.c" -print
Sample outputs:
/Users/user/Downloads/hello.c
/Users/user/Downloads/Y/Hello.C
/Users/user/Downloads/Z/HELLO.c
/Users/user/hello.c
Pass the -type f
option to only search for files:
find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print
The -iname
works either on GNU or BSD (including OS X) version find command. If your version of find command does not supports -iname
, try the following syntax using grep
command:
find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"
OR try
find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print
Sample outputs:
/Users/user/Downloads/Z/HELLO.C
/Users/user/Downloads/Z/HEllO.c
/Users/user/Downloads/hello.c
/Users/user/hello.c
Before each of your conditional statements, you could do something like this:
var pagetype = pagetype || false;
if (pagetype === 'something') {
//do stuff
}
When I were trying install librosa
package with pip
(pip install librosa
), this error were appeared:
ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
I tried to remove llvmlite
, but pip uninstall
could not remove it. So, I used capability of ignore
of pip
by this code:
pip install librosa --ignore-installed llvmlite
Indeed, you can use this rule for ignoring a package you don't want to consider:
pip install {package you want to install} --ignore-installed {installed package you don't want to consider}
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
If you do not use the sender
argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).
Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().
for gradle :
compile 'javax.el:javax.el-api:2.2.4'
The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:
Dynamic pivot tables (transform rows to columns)
Your code would look like this:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
)
) INTO @sql
FROM product_additional;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See Demo
NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len
If you want to catch the focus event dynamiclly on every input on your component :
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Checkout the full code here : https://stackblitz.com/edit/angular-93jdir
Here is a simple python code example of Recursive
, Top-down
, Bottom-up
approach for Fibonacci series:
def fib_recursive(n):
if n == 1 or n == 2:
return 1
else:
return fib_recursive(n-1) + fib_recursive(n-2)
print(fib_recursive(40))
def fib_memoize_or_top_down(n, mem):
if mem[n] is not 0:
return mem[n]
else:
mem[n] = fib_memoize_or_top_down(n-1, mem) + fib_memoize_or_top_down(n-2, mem)
return mem[n]
n = 40
mem = [0] * (n+1)
mem[1] = 1
mem[2] = 1
print(fib_memoize_or_top_down(n, mem))
def fib_bottom_up(n):
mem = [0] * (n+1)
mem[1] = 1
mem[2] = 1
if n == 1 or n == 2:
return 1
for i in range(3, n+1):
mem[i] = mem[i-1] + mem[i-2]
return mem[n]
print(fib_bottom_up(40))
For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.
Have faced the similar issue, resolved this by right clicking on the main method in the outline view and run as Java application.
Here is my answer:
services.msc
, Enter"D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56
Full answer here: https://stackoverflow.com/a/20136523/1316649
Do you execute the script from the command line on Linux or UNIX? In that case, you could just use
time ./script.py
Following the @greg0ire suggestion in comments:
<input type="submit" name="add_tag" value="Lägg till tag" />
In your server side, you'll do something like:
if (request.getParameter("add_tag") != null)
tags.addTag( /*...*/ );
(Since I don't know that language (java?), there may be syntax errors.)
I would prefer the <button>
solution, but it doesn't work as expected on IE < 9.
As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1
. Here's what you would need for DB2 for example:
spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1
Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none
The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.
https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html
Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.
Try This :
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/**
* Method to check whether external media available and writable. This is
* adapted from
* http://developer.android.com/guide/topics/data/data-storage.html
* #filesExternal
*/
private void checkExternalMedia() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
+ " writable=" + mExternalStorageWriteable);
}
/**
* Method to write ascii text characters to file on SD card. Note that you
* must add a WRITE_EXTERNAL_STORAGE permission to the manifest file or this
* method will throw a FileNotFound Exception because you won't have write
* permission.
*/
private void writeToSDFile() {
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data-
// storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: " + root);
// See
// http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you"
+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to " + file);
}
/**
* Method to read in a text file placed in the res/raw directory of the
* application. The method reads in all lines of the file sequentially.
*/
private void readRaw() {
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
// size
// More efficient (less readable) implementation of above is the
// composite expression
/*
* BufferedReader br = new BufferedReader(new InputStreamReader(
* this.getResources().openRawResource(R.raw.textfile)), 8192);
*/
try {
String test;
while (true) {
test = br.readLine();
// readLine() returns null if no more lines in the file
if (test == null) break;
tv.append("\n" + " " + test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
Append the below Script in Console:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
def flatten_it(d):
if isinstance(d, list) or isinstance(d, tuple):
return tuple([flatten_it(item) for item in d])
elif isinstance(d, dict):
return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
else:
return d
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}
print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])
I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.
Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)
More about fr units here.
.container{
width: 100vw;
height:100vh;
display: grid;
grid-template-columns: 1fr 3fr;
}
/*You don't need this*/
.div1{
background-color: yellow;
}
.div2{
background-color: red;
}
_x000D_
<div class='container'>
<div class='div1'>This is div 1</div>
<div class='div2'>This is div 2</div>
</div>
_x000D_
If it's an integer you need a part of....
var result = number.toString().slice(-2);
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:
public static bool ToBoolean(this string s)
{
string[] trueStrings = { "1", "y" , "yes" , "true" };
string[] falseStrings = { "0", "n", "no", "false" };
if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return true;
if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return false;
throw new InvalidCastException("only the following are supported for converting strings to boolean: "
+ string.Join(",", trueStrings)
+ " and "
+ string.Join(",", falseStrings));
}
With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.
So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.
In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.
I tried all the above and it did not work.
I found that in spite of uninstalling the app a new version of the app still gives the same error.
This is what solved it: go to Settings -> General -> application Manager -> choose your app -> click on the three dots on the top -> uninstall for all users
Once you do this, now it is actually uninstalled and will now allow your new version to install.
Hope this helps.
In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.
<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>
Will give you:
What the...heck is going on?
and not
What the...
heck is going on?
I'm using yarn. I had to do the following to overcome the error.
yarn add @babel/plugin-proposal-class-properties --dev
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml
:
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
And that's it. A plain yaml.load()
function also exists, but yaml.safe_load()
should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.
Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.
The list function will do this
>>> list('foo')
['f', 'o', 'o']
If you are using Babel or such transpilers and using async/await you could do :
function onDrop() {
console.log("dropped");
}
async function dropAll( collections ) {
const drops = collections.map(col => conn.collection(col).drop(onDrop) );
await drops;
console.log("all dropped");
}
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
The function eat
of my package safejoin has such feature, if you give
it a list of data.frames as a second input it will join them
recursively to the first input.
Borrowing and extending the accepted answer's data :
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
z2 <- data_frame(i = c("a","b","c"), l = rep(100L,3),l2 = rep(100L,3)) # for later
# devtools::install_github("moodymudskipper/safejoin")
library(safejoin)
eat(x, list(y,z), .by = "i")
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
We don't have to take all columns, we can use select helpers from tidyselect and
choose (as we start from .x
all .x
columns are kept):
eat(x, list(y,z), starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j l
# <chr> <int> <int>
# 1 a 1 9
# 2 b 2 NA
# 3 c 3 7
or remove specific ones:
eat(x, list(y,z), -starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j k
# <chr> <int> <int>
# 1 a 1 NA
# 2 b 2 4
# 3 c 3 5
If the list is named the names will be used as prefixes :
eat(x, dplyr::lst(y,z), .by = "i")
# # A tibble: 3 x 4
# i j y_k z_l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
If there are column conflicts the .conflict
argument allows you to resolve it,
for example by taking the first/second one, adding them, coalescing them,
or nesting them.
keep first :
eat(x, list(y, z, z2), .by = "i", .conflict = ~.x)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
keep last:
eat(x, list(y, z, z2), .by = "i", .conflict = ~.y)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 100
# 2 b 2 4 100
# 3 c 3 5 100
add:
eat(x, list(y, z, z2), .by = "i", .conflict = `+`)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 109
# 2 b 2 4 NA
# 3 c 3 5 107
coalesce:
eat(x, list(y, z, z2), .by = "i", .conflict = dplyr::coalesce)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 9
# 2 b 2 4 100
# 3 c 3 5 7
nest:
eat(x, list(y, z, z2), .by = "i", .conflict = ~tibble(first=.x, second=.y))
# # A tibble: 3 x 4
# i j k l$first $second
# <chr> <int> <int> <int> <int>
# 1 a 1 NA 9 100
# 2 b 2 4 NA 100
# 3 c 3 5 7 100
NA
values can be replaced by using the .fill
argument.
eat(x, list(y, z), .by = "i", .fill = 0)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <dbl> <dbl>
# 1 a 1 0 9
# 2 b 2 4 0
# 3 c 3 5 7
By default it's an enhanced left_join
but all dplyr joins are supported through
the .mode
argument, fuzzy joins are also supported through the match_fun
argument (it's wrapped around the package fuzzyjoin
) or
giving a formula such as ~ X("var1") > Y("var2") & X("var3") < Y("var4")
to the
by
argument.
You can also use IFNA(expression, value)
Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).
Intent i = new Intent(getBaseContext(), ViewPerson.class);
i.putExtra("PersonID", personID);
startActivity(i);
Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
personID = extras.getString("PersonID");
}
Now if you need to share data between two Activities, you can also have a Global Singleton.
public class YourApplication extends Application
{
public SomeDataClass data = new SomeDataClass();
}
Then call it in any activity by:
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here. Could be setter/getter or some other type of logic
You are trying to insert data that is larger than allowed for the column logo
.
Use following data types as per your need
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
Use LONGBLOB
to avoid this exception.
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
Think of it like this:
Whenever you create an object in ECMAscript, this object is formed in a mystique ECMAscript universal place where no man will ever be able to get. All you get back is a reference to that object in this mystique place.
var obj = { };
Even obj
is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this reference around. Effectively, any piece of code which accesses obj will modify the object which is far, far away.
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
For adding argument to delay function.
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}
In your build.gradle
repositories {
jcenter()
}
implementation 'com.quickbirdstudios:opencv:4.1.0'
You can also configure CXFNonSpringJAXRSServlet (assuming JSONProvider is used):
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>
org.apache.cxf.jaxrs.provider.JSONProvider
(writeXsiType=false)
</param-value>
</init-param>
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Use .prop()
instead and if we go with your code then compare like this:
Look at the example jsbin:
$("#news_list tr").click(function () {
var ele = $(this).find(':checkbox');
if ($(':checked').length) {
ele.prop('checked', false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Changes:
input
to :checkbox
.the length
of the checked checkboxes
."set -e
" is probably the easiest way to do this. Just put that before any commands in your program.
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.
It sounds like you want to do a nearest neighbour search with some bound on the distance. SQL does not support anything like this as far as I am aware and you would need to use an alternative data structure such as an R-tree or kd-tree.
When using FragmentPagerAdapter or FragmentStatePagerAdapter, it is best to deal solely with getItem()
and not touch instantiateItem()
at all. The instantiateItem()
-destroyItem()
-isViewFromObject()
interface on PagerAdapter is a lower-level interface that FragmentPagerAdapter uses to implement the much simpler getItem()
interface.
Before getting into this, I should clarify that
if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.
An earlier version of this answer made the mistake of using FragmentPagerAdapter for its example - that won't work because FragmentPagerAdapter never destroys a fragment after it's been displayed the first time.
I don't recommend the setTag()
and findViewWithTag()
workaround provided in the post you linked. As you've discovered, using setTag()
and findViewWithTag()
doesn't work with fragments, so it's not a good match.
The right solution is to override getItemPosition()
. When notifyDataSetChanged()
is called, ViewPager calls getItemPosition()
on all the items in its adapter to see whether they need to be moved to a different position or removed.
By default, getItemPosition()
returns POSITION_UNCHANGED
, which means, "This object is fine where it is, don't destroy or remove it." Returning POSITION_NONE
fixes the problem by instead saying, "This object is no longer an item I'm displaying, remove it." So it has the effect of removing and recreating every single item in your adapter.
This is a completely legitimate fix! This fix makes notifyDataSetChanged behave like a regular Adapter without view recycling. If you implement this fix and performance is satisfactory, you're off to the races. Job done.
If you need better performance, you can use a fancier getItemPosition()
implementation. Here's an example for a pager creating fragments off of a list of strings:
ViewPager pager = /* get my ViewPager */;
// assume this actually has stuff in it
final ArrayList<String> titles = new ArrayList<String>();
FragmentManager fm = getSupportFragmentManager();
pager.setAdapter(new FragmentStatePagerAdapter(fm) {
public int getCount() {
return titles.size();
}
public Fragment getItem(int position) {
MyFragment fragment = new MyFragment();
fragment.setTitle(titles.get(position));
return fragment;
}
public int getItemPosition(Object item) {
MyFragment fragment = (MyFragment)item;
String title = fragment.getTitle();
int position = titles.indexOf(title);
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
});
With this implementation, only fragments displaying new titles will get displayed. Any fragments displaying titles that are still in the list will instead be moved around to their new position in the list, and fragments with titles that are no longer in the list at all will be destroyed.
What if the fragment has not been recreated, but needs to be updated anyway? Updates to a living fragment are best handled by the fragment itself. That's the advantage of having a fragment, after all - it is its own controller. A fragment can add a listener or an observer to another object in onCreate()
, and then remove it in onDestroy()
, thus managing the updates itself. You don't have to put all the update code inside getItem()
like you do in an adapter for a ListView or other AdapterView types.
One last thing - just because FragmentPagerAdapter doesn't destroy a fragment doesn't mean that getItemPosition is completely useless in a FragmentPagerAdapter. You can still use this callback to reorder your fragments in the ViewPager. It will never remove them completely from the FragmentManager, though.
To be on the safe side use
os.getenv('FOO') or 'bar'
A corner case with the above answers is when the environment variable is set but is empty
For this special case you get
print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`
or
if "FOO" in os.environ:
print("FOO is here")
# prints FOO is here - however its not
To avoid this just use or
os.getenv('FOO') or 'bar'
Then you get
print(os.getenv('FOO') or 'bar')
# bar
When do we have empty environment variables?
You forgot to set the value in the .env
file
# .env
FOO=
or exported as
$ export FOO=
or forgot to set it in settings.py
# settings.py
os.environ['FOO'] = ''
Update: if in doubt, check out these one-liners
>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))
$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"
random_state number splits the test and training datasets with a random manner. In addition to what is explained here, it is important to remember that random_state value can have significant effect on the quality of your model (by quality I essentially mean accuracy to predict). For instance, If you take a certain dataset and train a regression model with it, without specifying the random_state value, there is the potential that everytime, you will get a different accuracy result for your trained model on the test data. So it is important to find the best random_state value to provide you with the most accurate model. And then, that number will be used to reproduce your model in another occasion such as another research experiment. To do so, it is possible to split and train the model in a for-loop by assigning random numbers to random_state parameter:
for j in range(1000):
X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =j, test_size=0.35)
lr = LarsCV().fit(X_train, y_train)
tr_score.append(lr.score(X_train, y_train))
ts_score.append(lr.score(X_test, y_test))
J = ts_score.index(np.max(ts_score))
X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =J, test_size=0.35)
M = LarsCV().fit(X_train, y_train)
y_pred = M.predict(X_test)`
If you have code in your Page_Load() event. Try adding this:
if (!Page.IsPostBack)
{
//your code here
}
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.
I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.
In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).
As of 2017 / Brew 1.3.2 @ macOS Sierra 10.12.6 all you have to do is:
$ brew install r
You don't even need to tap homebrew/science since r is now a part of core formulae for the Homebrew (homebrew-core).
It will also install all dependencies automatically:
==> Installing dependencies for r: gmp, mpfr, libmpc, isl, gcc
There are two additional options you might want to know:
--with-java
Build with java support
--with-openblas
Build with openblas support
In python 2.7, the /
operator is integer division if inputs are integers.
If you want float division (which is something I always prefer), just use this special import:
from __future__ import division
See it here:
>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>
Integer division is achieved by using //
, and modulo by using %
>>> 7 % 2
1
>>> 7 // 2
3
>>>
EDIT
As commented by user2357112
, this import has to be done before any other normal import.
Check this post under FileUpload Control
Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.
Its an option under Internet security that can be enabled
Your OCD is to blame :)
You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.
In application.properties, please add this:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false
and in your html form, you need an : enctype="multipart/form-data"
.
For example:
<form method="POST" enctype="multipart/form-data" action="/">
Hope this help!
One more possibility: if the symptom is that the first invocation works, but subsequent ones do not, you may be using PrimeFaces 3.x with JSF 2.2, as detailed here: No ViewState is sent.