You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.
-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.
Which forces your entire application to HTTPS.
If you want to do it by ClassName you could do:
<script type="text/javascript">
function hideTd(className){
var elements;
if (document.getElementsByClassName)
{
elements = document.getElementsByClassName(className);
}
else
{
var elArray = [];
var tmp = document.getElementsByTagName(elements);
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
elements = elArray;
}
for(var i = 0, i < elements.length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:
var localPath = (new Uri(urlStylePath)).AbsolutePath
In general, using the provided API is best practice.
The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.
The markup would be;
<asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
EnablePartialRendering="true" />
When dealing with Uniform Resource Locator(URL) s there are certain syntax standards, in this particular situation we are dealing with Reserved Characters.
As up to RFC 3986, Reserved Characters may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm; And asterisk(*) is a Reserved Character.
The best practice is to use Unreserved Characters in URLs or you can try encoding it.
Keep digging :
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
Here's another one for the books. It appears that this happens when you launch more than one web application from the same port number.
Basically, I have a couple of branches that I work off, I have a main branch and a staging branch and a release branch. When I switched branch to the staging branch I noticed that it was using the same port address configuration so I opted to change that. I then received another warning that this reservation conflicts with another configured application. The IIS Express server is sensitive about that and for whatever reason it bricks the configuration.
By simply picking a third unaffected port this problem went away because it then maps the port to a new directory mapping (my branches are located differently on disk). I noticed this because I tried to change the type name pointed to by Global.asax
but the type name was unchanged even after restarting the server, so clearly, the code I was changing wasn't reflected by the IIS Express deployment.
So, before you lose too much sleep over this, try changing the IIS port number that is currently used to run the web project.
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
For specific formats like yours ".drp ". You can directly pass that in accept=".drp" it will work for that.
But without " * "
<input name="Upload Saved Replay" type="file" accept=".drp" />_x000D_
<br/>
_x000D_
<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>
for e.g ,
<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>
If you need form
inside tr
and input
s in every td
, you can add form
in td
tag, and add attribute 'form' that contains id of form
tag to outside input
s.
Something like this:
<tr>
<td>
<form id='f1'>
<input type="text">
</form>
</td>
<td>
<input form='f1' type="text">
</td>
</tr>
try this.
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
public static class CookieHelper
{
/// <summary>
/// Checks whether a cookie exists.
/// </summary>
/// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
/// <param name="name">The cookie name to delete.</param>
/// <returns>A bool indicating whether a cookie exists.</returns>
public static bool Exists(this HttpCookieCollection cookieCollection, string name)
{
if (cookieCollection == null)
{
throw new ArgumentNullException("cookieCollection");
}
return cookieCollection[name] != null;
}
}
Usage:
Request.Cookies.Exists("MyCookie")
The core idea of the solution is:
input
elementtext
This can be done via this simple script:
var input = document.createElement('input');
input.setAttribute('type', 'text');
document.getElementById('parent').appendChild(input);
Now the question is, how to render this process dynamic. As stated in the question, there is another input where the user insert the number of input to generate. This can be done as follows:
function renderInputs(el){
var n = el.value && parseInt(el.value, 10);
if(isNaN(n)){
return;
}
var input;
var parent = document.getElementById("parent");
cleanDiv(parent);
for(var i=0; i<n; i++){
input = document.createElement('input');
input.setAttribute('type', 'text');
parent.appendChild(input);
}
}
function cleanDiv(div){
div.innerHTML = '';
}
_x000D_
Insert number of input to generate: </br>
<input type="text" onchange="renderInputs(this)"/>
<div id="parent">
Generated inputs:
</div>
_x000D_
but usually adding just an input is not really usefull, it would be better to add a name to the input, so that it can be easily sent as a form. This snippet add also a name:
function renderInputs(el){
var n = el.value;
var input, label;
var parent = document.getElementById("parent");
cleanDiv(parent);
el.value.split(',').forEach(function(name){
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', name);
label = document.createElement('label');
label.setAttribute('for', name);
label.innerText = name;
parent.appendChild(label);
parent.appendChild(input);
parent.appendChild(document.createElement('br'));
});
}
function cleanDiv(div){
div.innerHTML = '';
}
_x000D_
Insert the names, separated by comma, of the inputs to generate: </br>
<input type="text" onchange="renderInputs(this)"/>
<br>
Generated inputs: </br>
<div id="parent">
</div>
_x000D_
If you want information about all exceptions then use exception.ToString()
. It will collect data from all inner exceptions.
If you want only the original exception then use exception.GetBaseException().ToString()
. This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.
Example:
try {
Exception ex1 = new Exception( "Original" );
Exception ex2 = new Exception( "Second", ex1 );
Exception ex3 = new Exception( "Third", ex2 );
throw ex3;
} catch( Exception ex ) {
// ex => ex3
Exception baseEx = ex.GetBaseException(); // => ex1
}
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:
install webpack-dev-server
npm i -g webpack-dev-server
start webpack-dev-server with https
webpack-dev-server --https
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula
On a Scientific Linux 6.7 system, the man page on rsync says:
--ignore-times don't skip files that match size and time
I have two files with identical contents, but with different creation dates:
[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron
[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/new/usercron
With --size-only
, the two files are regarded the same:
[root@windstorm ~]# rsync -v --size-only -n /tmp/new/usercron /tmp/master/usercron
sent 29 bytes received 12 bytes 82.00 bytes/sec
total size is 1595 speedup is 38.90 (DRY RUN)
With --ignore-times
, the two files are regarded different:
[root@windstorm ~]# rsync -v --ignore-times -n /tmp/new/usercron /tmp/master/usercron
usercron
sent 32 bytes received 15 bytes 94.00 bytes/sec
total size is 1595 speedup is 33.94 (DRY RUN)
So it does not looks like --ignore-times
has any effect at all.
Its a good idea to work with odd number when trying to develop a good hast function for string. this function takes a string and return a index value, so far its work pretty good. and has less collision. the index ranges from 0 - 300 maybe even more than that, but i haven't gotten any higher so far even with long words like "electromechanical engineering"
int keyHash(string key)
{
unsigned int k = (int)key.length();
unsigned int u = 0,n = 0;
for (Uint i=0; i<k; i++)
{
n = (int)key[i];
u += 7*n%31;
}
return u%139;
}
another thing you can do is multiplying each character int parse by the index as it increase like the word "bear" (0*b) + (1*e) + (2*a) + (3*r) which will give you an int value to play with. the first hash function above collide at "here" and "hear" but still great at give some good unique values. the one below doesn't collide with "here" and "hear" because i multiply each character with the index as it increases.
int keyHash(string key)
{
unsigned int k = (int)key.length();
unsigned int u = 0,n = 0;
for (Uint i=0; i<k; i++)
{
n = (int)key[i];
u += i*n%31;
}
return u%139;
}
I liked PostMan
, it was the main reason why I kept using Chrome, now I'm good with HttpRequester
https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search
Out of all the combinations you tried, %ld
and %lu
are the only ones which are valid printf format specifiers at all. %lu
(long unsigned decimal), %lx
or %lX
(long hex with lowercase or uppercase letters), and %lo
(long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the %
and the l
).
You can do something like this to extract the value you want from JavaScript instead of an attribute:
<a href='#' class='click'>
<span style='display:none;'>value for JavaScript</span>some text
</a>
As Suhel Meman said in the comments:
SELECT column1, column2, column3 FROM table 1
UNION
SELECT column1, column2, column3 FROM table 2
...
would work.
But all your SELECTS
would have to consist of the same amount of columns. And because you are displaying it in one resulting table they should contain the same information.
What you might want to do, is a JOIN on Product ID or something like that. This way you would get more columns, which makes more sense most of the time.
While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)
Thank you all for your answers but I figured out how to do it and the final procedure looks like that :
Create Procedure sp_ADD_RESPONSABLE_EXTRANET_CLIENT
(
@ParLngId int output
)
as
Begin
if not exists (Select ParLngId from T_Param where ParStrIndex = 'RES' and ParStrP2 = 'Web')
Begin
INSERT INTO T_Param values('RES','¤ExtranetClient', 'ECli', 'Web', 1, 1, Null, Null, 'non', 'ExtranetClient', 'ExtranetClient', 25032, Null, '[email protected]', 'Extranet-Client', Null, 27, Null, Null, Null, Null, Null, Null, Null, Null, 1, Null, Null, 0 )
SET @ParLngId = @@IDENTITY
End
Else
Begin
SET @ParLngId = (Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client')
Return @ParLngId
End
End
So the thing that I found out and which made it works is:
if not exists
It allows us to use a boolean instead of Null or 0 or a number resulted of count()
Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
fetch(url)
.then(res => res.blob())
.then(console.log)
_x000D_
With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)
As a function:
const b64toBlob = (base64, type = 'application/octet-stream') =>
fetch(`data:${type};base64,${base64}`).then(res => res.blob())
I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while.
keeping the devtool open can slow the fetch performance
document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();
async function perf() {
const blob = await fetch(img).then(res => res.blob())
// turn it to a dataURI
const url = img
const b64Data = url.split(',')[1]
// Jeremy Banks solution
const b64toBlob = (b64Data, contentType = '', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
// bench blocking method
let i = 500
console.time('blocking b64')
while (i--) {
await b64toBlob(b64Data)
}
console.timeEnd('blocking b64')
// bench non blocking
i = 500
// so that the function is not reconstructed each time
const toBlob = res => res.blob()
console.time('fetch')
while (i--) {
await fetch(url).then(toBlob)
}
console.timeEnd('fetch')
console.log('done')
}
perf()
_x000D_
You need to make the decode function return an array by passing in the true
parameter.
json_decode(file_get_contents($file),true);
You want
strchr (const char *s, int c)
If the character c is in the string s it returns a pointer to the location in s. Otherwise it returns NULL. So just use your list of invalid characters as the string.
Adding my solution for this issue for anyone it might help.
I had a ClickOnce solution throwing this error. The app referenced a common "Libs" folder and contained a project reference to a Foo.dll
. While none of the projects in the solution referenced the static copy of the Foo.dll
in the "Libs" folder, some of the references in that folder did (ie: my solution had refs to Libs\Bar.dll
which referenced Foo.dll
.) Since the CO app pulled all the dependencies from Libs
as well as their dependencies, both copies were going into the project. This was generating the error above.
I fixed the problem by moving my Libs\Foo.dll
static version into a subfolder, Libs\Fix\Foo.dll
. This change made the ClickOnce app use only the project version of the DLL and the error disappeared.
There are a lot of nice technical answers here that clearly discuss the differences between VMs and containers as well as the origins of Docker.
For me the fundamental difference between VMs and Docker is how you manage the promotion of your application.
With VMs you promote your application and its dependencies from one VM to the next DEV to UAT to PRD.
With Docker the idea is that you bundle up your application inside its own container along with the libraries it needs and then promote the whole container as a single unit.
So at the most fundamental level with VMs you promote the application and its dependencies as discrete components whereas with Docker you promote everything in one hit.
And yes there are issues with containers including managing them although tools like Kubernetes or Docker Swarm greatly simplify the task.
Since Dheeraj Bhaskar
's answer is relatively old as many years past.
Here is my latest (2019 year) answer:
from dex
to java sourcecode
, currently has two kind of solution:
One Step
: directly convert dex
to java sourcecode
Two Step
: first convert dex
to jar
, second convert jar
to java sourcecode
dex
directly to java sourcecode
bin
folder can see command line jadx
or GUI version jadx-gui
, double click to run GUI version: jadx-gui
dex
filethen can show java source code:
File
-> save as gradle project
then got java sourcecode:
dex
to jar
download dex2jar zip, unzip got d2j-dex2jar.sh
, then:
apk
to jar
: sh d2j-dex2jar.sh -f ~/path/to/apk_to_decompile.apk
dex
to jar
: sh d2j-dex2jar.sh -f ~/path/to/dex_to_decompile.dex
example:
? v3.4.8 /Users/crifan/dev/dev_tool/android/reverse_engineering/dex-tools/dex-tools-2.1-SNAPSHOT/d2j-dex2jar.sh -f com.huili.readingclub8825612.dex
dex2jar com.huili.readingclub8825612.dex -> ./com.huili.readingclub8825612-dex2jar.jar
? v3.4.8 ll
-rw------- 1 crifan staff 9.5M 3 21 10:00 com.huili.readingclub8825612-dex2jar.jar
-rw------- 1 crifan staff 8.4M 3 19 14:04 com.huili.readingclub8825612.dex
jar
to java sourcecode
many
code will decompile errorminor
code will decompile errorno
code decompile error
Procyon
here demo Procyon
convert jar to java source code:
download procyon-decompiler-0.5.34.jar
then using syntax:
java -jar /path/to/procyon-decompiler-0.5.34.jar -jar your_to_decompile.jar -o outputFolderName
example:
java -jar /Users/crifan/dev/dev_tool/android/reverse_engineering/Procyon/procyon-decompiler-0.5.34.jar -jar com.huili.readingclub8825612-dex2jar.jar -o com.huili.readingclub8825612
using editor VSCode to open exported source code, look like this:
Conversion correctness : Jadx
> Procyon
> CRF
> JD-GUI
Recommend use: (One step solution's) Jadx
for more detailed explanation, please refer my online Chinese ebook: ??????????
For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js
Web API
module Api
module V1
class DownloadsController < BaseController
def show
@download = Download.find(params[:id])
send_data @download.blob_data
end
end
end
end
HTML
<a ng-click="download('foo')">download presentation</a>
Angular controller
$scope.download = function(type) {
return Download.get(type);
};
Angular Service
'use strict';
app.service('Download', function Download(Restangular) {
this.get = function(id) {
return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
console.log(data)
var blob = new Blob([data], {
type: "application/pdf"
});
//saveAs provided by FileSaver.js
saveAs(blob, id + '.pdf');
})
}
});
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string
constant to (char *)
.
Team:
This works with ASP.NET Core; The challenge to the above is how you 'set the setting to ignore'. Depending on how you setup your application it can be quite challenging. Here is what worked for me.
This can be placed in your public void ConfigureServices(IServiceCollection services) section.
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Instead, you can collect the output in a test result.
You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.
If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.
namespace Commandline.Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CommandlineTests
{
[TestMethod]
public void RunNoArguments()
{
Commandline.Program.Main(new string[0]);
}
}
}
Here's a novel method for detected when a URL has loaded by utilising Android's capability for JavaScript hooks. Using this pattern, we exploit JavaScript's knowledge of the document's state to generate a native method call within the Android runtime. These JavaScript-accessible calls can be made using the @JavaScriptInterface
annotation.
This implementation requires that we call setJavaScriptEnabled(true)
on the WebView
's settings, so it might not be suitable depending on your application's requirements, e.g. security concerns.
src/io/github/cawfree/webviewcallback/MainActivity.java (Jelly Bean, API Level 16)
package io.github.cawfree.webviewcallback;
/**
* Created by Alex Thomas (@Cawfree), 30/03/2017.
**/
import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {
/* Static Declarations. */
private static final String HOOK_JS = "Android";
private static final String URL_TEST = "http://www.zonal.co.uk/";
private static final String URL_PREPARE_WEBVIEW = "";
/* Member Variables. */
private WebView mWebView = null;
/** Create the Activity. */
@Override protected final void onCreate(final Bundle pSavedInstanceState) {
// Initialize the parent definition.
super.onCreate(pSavedInstanceState);
// Set the Content View.
this.setContentView(R.layout.activity_main);
// Fetch the WebView.
this.mWebView = (WebView)this.findViewById(R.id.webView);
// Enable JavaScript.
this.getWebView().getSettings().setJavaScriptEnabled(true);
// Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
this.getWebView().setWebViewClient(new WebViewClient() { @Override public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); } });
// Define the WebView JavaScript hook.
this.getWebView().addJavascriptInterface(this, MainActivity.HOOK_JS);
// Make this initial call to prepare JavaScript execution.
this.getWebView().loadUrl(MainActivity.URL_PREPARE_WEBVIEW);
}
/** When the Activity is Resumed. */
@Override protected final void onPostResume() {
// Handle as usual.
super.onPostResume();
// Load the URL as usual.
this.getWebView().loadUrl(MainActivity.URL_TEST);
// Use JavaScript to embed a hook to Android's MainActivity. (The onExportPageLoaded() function implements the callback, whilst we add some tests for the state of the WebPage so as to infer when to export the event.)
this.getWebView().loadUrl("javascript:" + "function onExportPageLoaded() { " + MainActivity.HOOK_JS + ".onPageLoaded(); }" + "if(document.readyState === 'complete') { onExportPageLoaded(); } else { window.addEventListener('onload', function () { onExportPageLoaded(); }, false); }");
}
/** Javascript-accessible callback for declaring when a page has loaded. */
@JavascriptInterface @SuppressWarnings("unused") public final void onPageLoaded() {
// Display the Message.
Toast.makeText(this, "Page has loaded!", Toast.LENGTH_SHORT).show();
}
/* Getters. */
public final WebView getWebView() {
return this.mWebView;
}
}
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Essentially, we're appending an additional JavaScript function that is used to test the state of the document. If it's loaded, we launch a custom onPageLoaded()
event in Android's MainActivity
; otherwise, we register an event listener that updates Android once the page is ready, using window.addEventListener('onload', ...);
.
Since we're appending this script after the call to this.getWebView().loadURL("")
has been made, it's probable that we don't need to 'listen' for the events at all, since we only get a chance to append the JavaScript hook by making a successive call to loadURL
, once the page has already been loaded.
I'm pretty sure this isn't the BEST way, but you could set the MinimumSize
and MaximimSize
properties to the same value. That will stop it.
In my case I was using a UIWebView and I passed a NSString in the second parameter instead of a NSURL. So I suspect that wrong class types passed to a functions can cause this error.
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE
, can be tampered with so always use server side validation.
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize
. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE
has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.
On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.php
<?php
if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
You can use this tool to create appropriate c# classes:
http://jsonclassgenerator.codeplex.com/
and when you will have classes created you can simply convert string to object:
public static T ParseJsonObject<T>(string json) where T : class, new()
{
JObject jobject = JObject.Parse(json);
return JsonConvert.DeserializeObject<T>(jobject.ToString());
}
Here that classes: http://ge.tt/2KGtbPT/v/0?c
Just fix namespaces.
Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.
I've got this little function:
public static class CoreUtil
{
public static IEnumerable<T> ToEnumerable<T>(params T[] items)
{
return items;
}
}
Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like
CoreUtil.ToEnumerable("title").ToList();
But of course it also allows
CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();
I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:
CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))
Saves a few ToList()
and Add
statements.
(Late answer, but I stumbled upon this oldie and thought this could be helpful)
I think programmers should be competent in the language they are using; use it clearly; and use it well. I don't think they should artificially cripple the language they are using. I speak from experience. I once worked literally next door to a Cobol shop where they didn't use ELSE 'because it was too complicated'. Reductio ad absurdam.
findstr /spin /c:"string" [files]
The parameters have the following meanings:
s
= recursivep
= skip non-printable charactersi
= case insensitiven
= print line numbersAnd the string to search for is the bit you put in quotes after /c:
I wrote this handy piece to sort by multiple columns / properties of an object. With each successive column click, the code stores the last column clicked and adds it to a growing list of clicked column string names, placing them in an array called sortArray. The built-in Angular "orderBy" filter simply reads the sortArray list and orders the columns by the order of column names stored there. So the last clicked column name becomes the primary ordered filter, the previous one clicked the next in precedence, etc. The reverse order affects all columns order at once and toggles ascending/descending for the complete array list set:
<script>
app.controller('myCtrl', function ($scope) {
$scope.sortArray = ['name'];
$scope.sortReverse1 = false;
$scope.searchProperty1 = '';
$scope.addSort = function (x) {
if ($scope.sortArray.indexOf(x) === -1) {
$scope.sortArray.splice(0,0,x);//add to front
}
else {
$scope.sortArray.splice($scope.sortArray.indexOf(x), 1, x);//remove
$scope.sortArray.splice(0, 0, x);//add to front again
}
};
$scope.sushi = [
{ name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
{ name: 'Philly', fish: 'Tuna', tastiness: 2 },
{ name: 'Tiger', fish: 'Eel', tastiness: 7 },
{ name: 'Rainbow', fish: 'Variety', tastiness: 6 },
{ name: 'Salmon', fish: 'Misc', tastiness: 2 }
];
});
</script>
<table style="border: 2px solid #000;">
<thead>
<tr>
<td><a href="#" ng-click="addSort('name');sortReverse1=!sortReverse1">NAME<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
<td><a href="#" ng-click="addSort('fish');sortReverse1=!sortReverse1">FISH<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
<td><a href="#" ng-click="addSort('tastiness');sortReverse1=!sortReverse1">TASTINESS<span ng-show="sortReverse1==false">▼</span><span ng-show="sortReverse1==true">▲</span></a></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="s in sushi | orderBy:sortArray:sortReverse1 | filter:searchProperty1">
<td>{{ s.name }}</td>
<td>{{ s.fish }}</td>
<td>{{ s.tastiness }}</td>
</tr>
</tbody>
</table>
Another option for an in-memory java cache is cache2k. The in-memory performance is superior to EHCache and google guava, see the cache2k benchmarks page.
The usage pattern is similar to other caches. Here is an example:
Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
.expireAfterWrite(5, TimeUnit.MINUTES) // expire/refresh after 5 minutes
.resilienceDuration(30, TimeUnit.SECONDS) // cope with at most 30 seconds
// outage before propagating
// exceptions
.refreshAhead(true) // keep fresh when expiring
.loader(new CacheLoader<String, String>() {
@Override
public String load(final String key) throws Exception {
return ....;
}
})
.build();
String val = cache.peek("something");
cache.put("something", "hello");
val = cache.get("something");
If you have google guava as dependency then trying out guava cache, may be a good alternative.
You can do something like this:
<%!
String myMethod(String input) {
return "test " + input;
}
%>
<%= myMethod("1 2 3") %>
This will output test 1 2 3
to the page.
This is fairly close to an XY problem. That is, the question being asked is essentially how to mutate a captured local variable from a lambda. But the actual task at hand is how to number the elements of a list.
In my experience, upward of 80% of the time there is a question of how to mutate a captured local from within a lambda, there's a better way to proceed. Usually this involves reduction, but in this case the technique of running a stream over the list indexes applies well:
IntStream.range(0, list.size())
.forEach(i -> list.get(i).setOrdinal(i));
I've discovered some really interesting (read as "horrible") behavior in Safari 5 and Internet Explorer 9. I was using this with great success in Chrome and Firefox.
if (typeof this === 'string') {
doStuffWith(this);
}
Then I test in IE9, and it doesn't work at all. Big surprise. But in Safari, it's intermittent! So I start debugging, and I find that Internet Explorer is always returning false
. But the weirdest thing is that Safari seems to be doing some kind of optimization in its JavaScript VM where it is true
the first time, but false
every time you hit reload!
My brain almost exploded.
So now I've settled on this:
if (this instanceof String || typeof this === 'string')
doStuffWith(this.toString());
}
And now everything works great. Note that you can call "a string".toString()
and it just returns a copy of the string, i.e.
"a string".toString() === new String("a string").toString(); // true
So I'll be using both from now on.
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
Since ruby 2.4.0
you can use native Hash#transform_values
method:
hash = {"a" => "b", "c" => "d"}
new_hash = hash.transform_values(&:upcase)
# => {"a" => "B", "c" => "D"}
There is also destructive Hash#transform_values!
version.
Just use puttygen and load your private key into it. It offers different options, e.g. exporting the corresponding public key.
I can't comment directly in the thread since I don't have the requisite reputation yet, but the author asked the following:
the only issue is that the background is white but the clock, wireless and other text and icons are also in white .. I am not sure why!!
For anyone else who comes to this thread, here's what worked for me. The text color of the status bar is decided by the Brightness constant in flutter/material.dart
. To change this, adjust the SystemChrome
solution like so to configure the text:
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.red,
statusBarBrightness: Brightness.dark,
));
Your possible values for Brightness
are Brightness.dark
and Brightness.light
.
Documentation: https://api.flutter.dev/flutter/dart-ui/Brightness-class.html https://api.flutter.dev/flutter/services/SystemUiOverlayStyle-class.html
See my answer to a similar question here.
It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:
.chapter {
position: relative;
height: 1200px;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/3/
The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.
If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height
to 0 and set the padding-bottom
to the percentage of the width:
.chapter {
position: relative;
height: 0;
padding-bottom: 75%;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/4/
You could also put the padding-bottom
percentage into each #chapter
style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.
Always use :::
. There are two reasons: efficiency and type safety.
Efficiency
x ::: y ::: z
is faster than x ++ y ++ z
, because :::
is right associative. x ::: y ::: z
is parsed as x ::: (y ::: z)
, which is algorithmically faster than (x ::: y) ::: z
(the latter requires O(|x|) more steps).
Type safety
With :::
you can only concatenate two List
s. With ++
you can append any collection to List
, which is terrible:
scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)
++
is also easy to mix up with +
:
scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab
In later versions of CMake, one way to do it on each target is:
set_target_properties(MyTarget PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
I don't know of a way to do it globally.
This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.
Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.
But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.
Here is a script that deploys an executable jar as a systemd service.
It creates a user for the service and the .service file, and place the jar file under /var, and makes some basic lock down of privileges.
#!/bin/bash
# Argument: The jar file to deploy
APPSRCPATH=$1
# Argument: application name, no spaces please, used as folder name under /var
APPNAME=$2
# Argument: the user to use when running the application, may exist, created if not exists
APPUSER=$3
# Help text
USAGE="
Usage: sudo $0 <jar-file> <app-name> <runtime-user>
If an app with the name <app-name> already exist, it is stopped and deleted.
If the <runtime-user> does not already exist, it is created.
"
# Check that we are root
if [ ! "root" = "$(whoami)" ]; then
echo "Must be root. Please use e.g. sudo"
echo "$USAGE"
exit
fi
# Check arguments
if [ "$#" -ne 3 -o ${#APPSRCPATH} = 0 -o ${#APPNAME} = 0 -o ${#APPUSER} = 0 ]; then
echo "Incorrect number of parameters."
echo "$USAGE"
exit
fi
if [ ! -f $APPSRCPATH ]; then
echo "Can't find jar file $APPSRCPATH"
echo "$USAGE"
exit
fi
# Infered values
APPFILENAME=$(basename $APPSRCPATH)
APPFOLDER=/var/javaapps/$APPNAME
APPDESTPATH=$APPFOLDER/$APPFILENAME
# Stop the service if it already exist and is running
systemctl stop $APPNAME >/dev/null 2>&1
# Create the app folder, deleting any previous content
rm -fr $APPFOLDER
mkdir -p $APPFOLDER
# Create the user if it does not exist
if id "$APPUSER" >/dev/null 2>&1; then
echo "Using existing user $APPUSER"
else
adduser --disabled-password --gecos "" $APPUSER
echo "Created user $APPUSER"
fi
# Place app in app folder, setting owner and rights
cp $APPSRCPATH $APPDESTPATH
chown $APPUSER $APPDESTPATH
chmod 500 $APPDESTPATH
echo "Added or updated the $APPDESTPATH file"
# Create the .service file used by systemd
echo "
[Unit]
Description=$APPNAME
After=syslog.target
[Service]
User=$APPUSER
ExecStart=/usr/bin/java -jar $APPDESTPATH
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/$APPNAME.service
echo "Created the /etc/systemd/system/$APPNAME.service file"
# Reload the daemon
systemctl daemon-reload
# Start the deployed app
systemctl start $APPNAME
systemctl status $APPNAME
//Filter out array elements with keys shorter than 4 characters // By using Anonymous function with Closure...
function comparison($min)
{
return function($item) use ($min) {
return strlen($item) >= $min;
};
}
$input = array(
0 => "val 0",
"one" => "val one",
"two" => "val two",
"three"=> "val three",
"four" => "val four",
"five" => "val five",
"6" => "val 6"
);
$output = array_filter(array_keys($input), comparison(4));
Check this out: http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/ I'm using this and I'm happy with the solution.
Right here you can find a demo: http://demo.wil-linssen.com/jquery-sortable-ajax/
Enjoy!
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
s.Name, t.Name
If you want to separate table space from index space, you need to use AND i.index_id IN (0,1)
for the table space (index_id = 0
is the heap space, index_id = 1
is the size of the clustered index = data pages) and AND i.index_id > 1
for the index-only space
You will want to look into the nl2br() function along with the trim().
The nl2br()
will insert <br />
before the newline character (\n
) and the trim()
will remove any ending \n
or whitespace characters.
$text = trim($_POST['textareaname']); // remove the last \n or whitespace character
$text = nl2br($text); // insert <br /> before \n
That should do what you want.
UPDATE
The reason the following code will not work is because in order for \n
to be recognized, it needs to be inside double quotes since double quotes parse data inside of them, where as single quotes takes it literally, IE "\n"
$text = str_replace('\n', '<br />', $text);
To fix it, it would be:
$text = str_replace("\n", '<br />', $text);
But it is still better to use the builtin nl2br()
function, PHP provides.
EDIT
Sorry, I figured the first question was so you could add the linebreaks in, indeed this will change the answer quite a bit, as anytype of explode()
will remove the line breaks, but here it is:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
If you do it this way, you will need to append the <br />
onto the end of the line before the processing is done on your own, as the explode()
function will remove the \n
characters.
Added the array_filter()
to trim()
off any extra \r
characters that may have been lingering.
Here's an example
// in the service
getVehicles(){
return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}
// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
this.vehicles = this._vehicleService.getVehicles();
}
// in template
<div *ngFor='let vehicle of vehicles | async'>
{{vehicle.name}}
</div>
Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String filePath) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath = filePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream = fileStream;
}
private void loadFile() throws FileNotFoundException,
NullObjectFoundException {
if (resourceAsStream == null)
throw new FileNotFoundException("Unable to locate give file..");
else {
try {
workbook = new XSSFWorkbook(resourceAsStream);
} catch (IOException ex) {
}
}
}// end loadxlsFile
public String[] getSheetsName() {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex() {
int totalsheet = 0;
int i = 0;
int[] sheetIndex = null;
String[] sheetname = getSheetsName();
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetIndex = new int[totalsheet];
while (i < totalsheet) {
sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index) {
if (index < getSheetsIndex().length && index >= 0)
return true;
else
return false;
}
public int getNumberOfSheet() {
int totalsheet = 0;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
// logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
// logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex) {
int NO_OF_Column = 0;
@SuppressWarnings("unused")
XSSFCell cell = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = firstRow.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex) {
int NO_OF_ROW = 0;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex) {
int noOfColumns = 0;
XSSFCell cell = null;
int i = 0;
String columns[] = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = Row.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
// logger.error(ex);
}
return columns;
}// end of method
public String[][] getSheetData(int SheetIndex) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int noOfRows = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows = getNumberOfRows(SheetIndex) + 1;
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
data[i][j] = Boolean.toString(cell
.getBooleanCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
public String[][] getSheetData(int SheetIndex, int noOfRows) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (i < noOfRows) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
}
Created this little testcode:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
System.out.println(test.getSheetsName());
System.out.println(test.getNumberOfSheet());
}
}
All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.
Cheers, Wim
Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved
Check
glassfish\config\asenv.bat
where java path is configured
REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16
adb push [file path on your computer] [file path on your mobile]
//The following example is going to generate a number between 0 and 73.
int value;
value = (arc4random() % 74);
NSLog(@"random number: %i ", value);
//In order to generate 1 to 73, do the following:
int value1;
value1 = (arc4random() % 73) + 1;
NSLog(@"random number step 2: %i ", value1);
Output:
random number: 72
random number step 2: 52
IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/
I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.
Or you could use Red Gate SQL Refactor or SQL Prompt, which expands your SELECT * into column lists with a click of the Tab button
so in your case, if you type in SELECT * FROM A JOIN B ... Go to the end of *, Tab button, voila! you'll see SELECT A.column1, A.column2, .... , B.column1, B.column2 FROM A JOIN B
It's not free though
The manual is clear enough. Please specify what part you get stuck with after you work through it, I'd suggest:
https://developer.android.com/studio/publish/app-signing.html
Okay, a small overview without reference or eclipse around, so leave some space for errors, but it works like this
Also, from the link:
Compile and sign with Eclipse ADT
If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed .apk (and even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed your package, it will also perform package alignment with zip align. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing.
To create a signed and aligned .apk in Eclipse:
- Select the project in the Package Explorer and select File > Export.
Open the Android folder, select Export Android Application, and click Next.
The Export Android Application wizard now starts, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the .apk (or creating a new keystore and private key).
- Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.
For Windows Smart device (compact frame work ) (MC75-Motorola devices)
mytabControl.SelectedIndex = 1
Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.
So I had a lot of problems with all of the solutions mentioned so far...
I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.
I also need it to work on Windows AND Unix, so sym-links aren't ideal.
Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.
so.. This is what worked well for me!
Main Project's Package.json File Snippet:
"name": "main-project-name",
"version": "0.0.0",
"scripts": {
"ng": "ng",
...
"preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
},
"private": true,
"dependencies": {
...
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
...
}
This achieves 3 things:
I hope this is clear, and helps someone out.
The tar.gz approach also sort of works..
npm install (file path) also sort of works.
This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)
====== UPDATE: ======
There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.
As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.
First:
For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.
As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:
"scripts": {
"build": "ng-packagr -p ng-package.json",
"package": "npm install && npm run build && cd dist && npm pack"
},
And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:
"scripts": {
"preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
},
Second
Reference the built tgz npm package from your main project!
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
...
}
Third
Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.
If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348
for now, just update the:
"version": "1.0.0-build5",
In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
...
}
You get used to it. Just update the two package.json files - version then the ref to the new filename.
Hope that helps someone...
For whats its worth here is my standard answer. The only thing new here is that is uses the Collections.reverseOrder(). Plus it puts all suggestions into one example:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people,
Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
The index statistics likely need to be current, but this will return the number of rows for all tables that are not MS_SHIPPED.
select o.name, i.rowcnt
from sys.objects o join sys.sysindexes i
on o.object_id = i.id
where o.is_ms_shipped = 0
and i.rowcnt > 0
order by o.name
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
My understanding is that you actually use script tags with JSONP, sooo...
The first step is to create your function that will handle the JSON:
function hooray(json) {
// dealin wit teh jsonz
}
Make sure that this function is accessible on a global level.
Next, add a script element to the DOM:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
The script will load the JavaScript that the API provider builds, and execute it.
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)
almost works perfectly except for the space issue. if that were changed to:
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),22)
...then you get the space. And additionally, if the column being converted is already of TIME
format, you can skip the cast if you reference it directly.
Final answer:
select CONVERT(varchar(15),StartTime,22)
Create a separate ul.nav
for just that list item and float that ul
right.
Actually, it appears that urllib2 can do an HTTP HEAD request.
The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.
Here's my take on it:
import urllib2
# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)
try:
response = urllib2.urlopen(request)
response_headers = response.info()
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response_headers.dict
except urllib2.HTTPError, e:
# Prints the HTTP Status code of the response but only if there was a
# problem.
print ("Error code: %s" % e.code)
If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.
This is the HTTP request and response from the code above, as captured by Wireshark:
HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly
However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.
The request above involves a redirect. Here is request to the destination, as captured by Wireshark:
GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7
An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:
import httplib2
url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()
try:
response, content = http_interface.request(url, method="HEAD")
print ("Response status: %d - %s" % (response.status, response.reason))
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response.__dict__
except httplib2.ServerNotFoundError, e:
print (e.message)
This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.
Here's the first request:
HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
Here's the second request, to the destination:
HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
The simplest way: run git push -u origin feature/123-sandbox-tests
once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push
to push tracked branches to their upstream remote(s).
You can also do this in the config yourself by setting branch.<branch name>.merge
to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote
to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master
, so you can follow that example.
Finally, make sure you consider the push.default
setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.
Details on each of these settings can be found in the git-config man page.
On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):
function pushCurrent {
git config push.default upstream
git push
git config push.default matching
}
What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.
In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.
Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.
You can put this code in cshtml if you are returning view from controller and you want to increase the length of view bag data while encoding in json in cshtml
@{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
jss.MaxJsonLength = Int32.MaxValue;
var userInfoJson = jss.Serialize(ViewBag.ActionObj);
}
var dataJsonOnActionGrid1 = @Html.Raw(userInfoJson);
Now, dataJsonOnActionGrid1
will be accesible on js page and you will get proper result.
Thanks
Follow these steps:
sudo xcodebuild --license
.On your select use width: auto and no padding to see how long your text is. I'm using 100% available width on my select and all of my options have the same length, this allows me to use very simple css.
text-indent will move the text from left, similar to padding-left
120px is my text length - I want to center it so take half of that size and half of the select size, leaving me with 50% - 60px
select{
width: 100%;
text-indent: calc(50% - 60px);
}
What if I have different sizes of options?
It is possible, however, the solution will not be a pretty one.
The former solution might get you really close to being centered if the difference between options isn't like 5 characters.
If you still need to center it more precisely you can do this
Prepare this class:
.realWidth{
width: auto;
}
Apply onChange listener to select element
In that listener apply .realWidth to the select element with
const selectRef = document.getElementById("yourId");
selectRef.classList.add("realWidth");
Get access to the real width of the option.
const widthOfSelect = selectRef.getBoundingClientRect().width / 2;
widthOfSelect is the width you are looking for. Store it in global/component variable.
Remove the realWidth, you don't need it anymore.
selectRef.classList.remove("realWidth");
I am using react, I'm not sure this will work in vanilla, if not you have to find another solution.
<select style={`textIndent: calc(50% - ${widthOfSelect}) %`}> ... </select>
Another solution, however, that is a bad one could be creating the CSS classes with js and putting it to head.
PROS:
CONS:
One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.
This is barely mentioned in the GitHub README, where there's one line for it:
Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.
However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.
This has an effect on the way you can use #
variables as conditionals.
For example in Mustache you can do this:
{{#variable}}<span class="text">{{variable}}</span>{{/variable}}
It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:
{{this}}
instead{{../variable}}
to get back out to relevant scopevariable
value within the parent variable
objectMore details on this, if you want them, here.
Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:
It is also possible to change the default username "user" and the default password "live".
I tried the username user
and password live
and it did work. If you want to run commands as root you can preface each command with sudo
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
var s = ",'first string','more','even more'";
s.split(/'?,'?/).filter(function(v) { return v; });
Results in:
["first string", "more", "even more'"]
First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.
$(( ( RANDOM % 10 ) + 1 ))
EDIT. Changed brackets into parenthesis according to the comment. http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting
If anyone got an error while signing in to Google and this message appear:
Couldn't Sign In
can't establish a reliable connection to the server...
then try to sign in from the browser - in YouTube, Gmail, Google sites, etc.
This helped me. After signing in in the browser I was able to sign in the Google Play app...
If you see this intermittently on wifi or LAN, but your mobile internet connection seems ok, it is most likely your ISP's cheap gateway router is experiencing high traffic load.
You should trap these errors and display a reminder to the user to close any other apps using the network.
Test by running a couple of HD youtube videos on your desktop to reproduce, or just go to a busy Starbucks.
I look for natural primary keys and use them where I can.
If no natural keys can be found, I prefer a GUID to a INT++ because SQL Server use trees, and it is bad to always add keys to the end in trees.
On tables that are many-to-many couplings I use a compound primary key of the foreign keys.
Because I'm lucky enough to use SQL Server I can study execution plans and statistics with the profiler and the query analyzer and find out how my keys are performing very easily.
If you want very few info like a class in your html for common browsers for instance, you could use:
function get_browser()
{
$browser = '';
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];
return $browser;
}
which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.
I also tried regexp and list solutions, and list one is faster.
Here is my solution (by previous answers):
text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
We can also use this with the $_GET
method
$employee_id = 'EMP-1234';
header('Location: employee.php?id='.$employee_id);
You can Zoom In and Zoom Out the entire user interface from the View menu.
Right now i'm using version 1.21.1 and there in view menu you can get the Zoom in and Zoom out option which are the 2nd and 3rd last options. You can do it by using Ctrl + + and Ctrl + -.
You can reset the zoom at any time by selecting Reset Zoom option.
In my case when i tried
$ hive --service metastore
I got
MetaException(message:Version information not found in metastore. )
The necessary tables required for the metastore are missing in MySQL. Manually create the tables and restart hive metastore.
cd $HIVE_HOME/scripts/metastore/upgrade/mysql/
< Login into MySQL >
mysql> drop database IF EXISTS <metastore db name>;
mysql> create database <metastore db name>;
mysql> use <metastore db name>;
mysql> source hive-schema-2.x.x.mysql.sql;
metastore db name should match the database name mentioned in hive-site.xml files connection property tag.
hive-schema-2.x.x.mysql.sql file depends on the version available in the current directory. Try to go for the latest because it holds many old schema files also.
Now try to execute hive --service metastore
If everything goes cool, then simply start the hive from terminal.
>hive
I hope the above answer serves your need.
td.setAttribute('rowspan',x);
Since android doesnt support <ol>, <ul> or <li>
html elements, I had to do it like this
<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>•name1<br />•name2<br /></p>]]></string>
if you want to maintain custom space then use </pre> tag
If it works fine on your local environment, probably your remote server's IP is being blocked by the server at the target URL you've set for cURL to use. You need to verify that your remote server is allowed to access the URL you've set for CURLOPT_URL.
Try this
To Remove Hand Cursor
a.link {
cursor: default;
}
I am a CSS noob but I have noticed that hover will work for touch screens so long as it's a "hoverable" element: image, link, button. You can do it all with CSS using the following trick.
Change your div background to an actual image tag within the div or create a dummy link around the entire div, it will then register as a hover when you touch the image.
Doing this will mean that you need the rest of your page to also be "hoverable" so when you touch outside of the image it recognizes that info-slide:hover has ended. My trick is to make all of my other content dummy links.
It's not very elegant but it works.
You can also use the setProperty method like below
document.getElementById('divName').style.setProperty("top", "100px");
Usually the desire is to match the menu width to the width of the dropdown parent. This can be achieved easily like so:
.dropdown-menu {
width:100%;
}
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
Fewer lines for 2019 searchers:
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')
UPDATE NOTE: size
was changed to height
.
I think you want to print the name of the person or both the name and email :
const renObjData = this.props.data.map(function(data, idx) {
return <p key={idx}>{data.name}</p>;
});
or :
const renObjData = this.props.data.map(function(data, idx) {
return ([
<p key={idx}>{data.name}</p>,
<p key={idx}>{data.email}</p>,
]);
});
I thought I experienced issues with connecting my emulator to the internet but it turned out to be problems with the code I was using. I know its obvious but in the first instance try the browser on the emulator to confirm you have no internet access. I would have saved an hour if I had done that first.
$.ajax
will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
You may refer to: How to deal with "refusing to merge unrelated histories" error:
$ git pull --allow-unrelated-histories
$ git push -f origin master
Objective-C
You can use (see NSString Class Reference)
- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding
Example:
NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
Remark: Please notice the NSData
value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil
will be returned:
Prior Swift 3.0
String(data: yourData, encoding: NSUTF8StringEncoding)
Swift 3.0 Onwards
String(data: yourData, encoding: .utf8)
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '')
is faster.
see http://jsperf.com/cast-to-string/8
note - there are significant differences across browsers at this time.
I used to declare the configuration in application.properties
like this (you can use you own property file)
server.host = localhost
server.port = 8081
and in application you can get it easily by @Value("${server.host}")
and @Value("${server.port}")
as field level annotation.
or if in your case it is dynamic than you can get from system properties
Here is the example
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
For a better understanding of this annotation , see this example Multiple uses of @Value annotation
CSS could be of help here.
style="text-transform: uppercase";"
does this help?
var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');
That should work just fine.
There's no difference in the size of the memory block allocated. calloc
just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc
have initilial value as if they were initialized with literal 0
, i.e. integers should have value of 0
, floating-point variables - value of 0.0
, pointers - the appropriate null-pointer value, and so on.
From the pedantic point of view though, calloc
(as well as memset(..., 0, ...)
) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char
. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char
the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.
Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc
(and memset(..., 0, ...)
). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.
In practice, calloc
works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc
instead and perform my own initialization.
Finally, another important detail is that calloc
is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc
must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc
version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.
Create a new ImageIcon
object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame
with setIconImage()
:
myFrame.setIconImage(img.getImage());
Also checkout setIconImages()
which takes a List
instead.
I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:
Here is the result: Bootply example
Javascript/Jquery:
$(function(){
// ADD SLIDEDOWN ANIMATION TO DROPDOWN //
$('.dropdown').on('show.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
e.preventDefault();
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
//On Complete, we reset all active dropdown classes and attributes
//This fixes the visual bug associated with the open class being removed too fast
$('.dropdown').removeClass('show');
$('.dropdown-menu').removeClass('show');
$('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
});
});
});
Another way to do it is subclass it:
package my.own;
public class FQNDate extends Date {
}
And then import my.own.FQNDate in packages that have java.util.Date.
You are almost there :)
All that is left is to
git checkout featurex
git merge our-team
This will merge our-team into featurex.
The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.
You'll have to configure the server to interpret .html
files as .php
files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
Do a str.replace('; ', ', ')
and then a str.split(', ')
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
If the array is unsorted, you will need to use linear search.
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange
event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
No need for a plugin to check if outside of view port.
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();
$.each($("div"),function(){
p = $(this).position();
//vertical
if (p.top > h + d || p.top > h - d){
console.log($(this))
}
//horizontal
if (p.left < 0 - $(this).width() || p.left > w){
console.log($(this))
}
});
Here is one more way to do this:
arr = ['Cat', 'Dog', 'Bird']
e = 'Dog'
present = arr.size != (arr - [e]).size
If you mean milliseconds since epoch you could do
ptime time_t_epoch(date(1970,1,1));
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();
However, it's not particularly clear what you're after.
Have a look at the example in the documentation for DateTime at Boost Date Time
After executing the below regex, your answer is in the first capture.
/^(.*?)\.txt/
For this reason better is if you use this data from CSS or JSON file data, and then with this data setting new state with this.state({width: "some value",height:"some value" }); or writing code who use data of width screen data in self work if you wish responsive show images
break
breaks the current loop and continues, while return
it will break the current method and continues from where you called that method
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
Example from the docs:
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ...
result = source.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
You can use simple trick which is import flask app variable from main inside another file, like:
test-routes.py
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test-routes
It works from my side.
For log4j 2 API , you can use
Logger logger = LogManager.getRootLogger();
Configurator.setAllLevels(logger.getName(), Level.getLevel(level));
Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:
if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {
// ... stuff ...
}
Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).
and at the same time for Cordova (a.k.a Phonegap), React-Native and all other development platforms
Format : 9-Patch PNG (recommended)
Dimensions
- LDPI:
- Portrait: 200x320px
- Landscape: 320x200px
- MDPI:
- Portrait: 320x480px
- Landscape: 480x320px
- HDPI:
- Portrait: 480x800px
- Landscape: 800x480px
- XHDPI:
- Portrait: 720px1280px
- Landscape: 1280x720px
- XXHDPI
- Portrait: 960x1600px
- Landscape: 1600x960px
- XXXHDPI
- Portrait: 1280x1920px
- Landscape: 1920x1280px
Note: Preparing XXXHDPI is not needed and also maybe XXHDPI size too because of the repeating areas of 9-patch images. On the other hand, if only Portrait sizes are used the App size could be more less. More pictures mean more space is need.
I think there is no an exact size for the all devices. I use Xperia Z 5". If you develop a crossplatform-webview app you should consider a lot of things (whether screen has softkey navigation buttons or not, etc). Therefore, I think there is only one suitable solution. The solution is to prepare a 9-patch splash screen (find How to design a new splash screen
heading below).
That's it!
Cordova specific code
To be added lines into the config.xml for 9-patch splash screens
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="6000" />
<platform name="android">
<splash src="res/screen/android/ldpi.9.png" density="ldpi"/>
<splash src="res/screen/android/mdpi.9.png" density="mdpi"/>
<splash src="res/screen/android/hdpi.9.png" density="hdpi"/>
<splash src="res/screen/android/xhdpi.9.png" density="xhdpi"/>
</platform>
To be added lines into the config.xml when using non-9-patch splash screens
<platform name="android">
<splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
<splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
<splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
<splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>
<splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
<splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
<splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
<splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>
I would describe a simple way to create proper splash screen using this way. Assume we're designing a 1280dp x 720dp - xhdpi (x-large) screen. I've written for the sake of example the below;
In Photoshop: File -> New in new dialog window set your screens
Width: 720 Pixels Height: 1280 Pixels
I guess the above sizes mean Resolution is 320 Pixels/Inch. But to ensure you can change resolution value to 320 in your dialog window. In this case Pixels/Inch = DPI
Congratulations... You have a 720dp x 1280dp splash screen template.
After you designed your splash screen, if you want to design 9-Patch splash screen, you should insert 1 pixel gap for every side. For this reason you should increase +2 pixel your canvas size's width and height ( now your image sizes are 722 x 1282 ).
I've left the blank 1 pixel gap at every side as directed the below.
Changing the canvas size by using Photoshop:
- Open a splash screen png file in Photoshop
- Click onto the lock icon next to the 'Background' name in the Layers field (to leave blank instead of another color like white) if there is like the below:
- Change the canvas size from Image menu ( Width: 720 pixels to 722 pixels and Height: 1280 pixels to 1282 pixels). Now, should see 1 pixel gap at every side of the splash screen image.
Then you can use C:\Program Files (x86)\Android\android-studio\sdk\tools\draw9patch.bat to convert a 9-patch file. For that open your splash screen on draw9patch app. You should define your logo and expandable areas. Notice the black line the following example splash screen. The black line's thickness is just 1 px ;) Left and Top sides black lines define your splash screen's must display area. Exactly as your designed. Right and Bottom lines define the addable and removable area (automatically repeating areas).
Just do that: Zoom your image's top edge on draw9patch application. Click and drag your mouse to draw line. And press shift + click and drag your mouse to erase line.
If you develop a cross-platform app (like Cordova/PhoneGap) you can find the following address almost all mabile OS splash screen sizes. Click for Windows Phone, WebOS, BlackBerry, Bada-WAC and Bada splash screen sizes.
https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes
And if you need IOS, Android etc. app icon sizes you can visit here.
Format : PNG (recommended)
Dimensions
- Tablet (iPad)
- Non-Retina (1x)
- Portrait: 768x1024px
- Landscape: 1024x768px
- Retina (2x)
- Portrait: 1536x2048px
- Landscape: 2048x1536px
- Handheld (iPhone, iPod)
- Non-Retina (1x)
- Portrait: 320x480px
- Landscape: 480x320px
- Retina (2x)
- Portrait: 640x960px
- Landscape: 960x640px
- iPhone 5 Retina (2x)
- Portrait: 640x1136px
- Landscape: 1136x640px
- iPhone 6 (2x)
- Portrait: 750x1334px
- Landscape: 1334x750px
- iPhone 6 Plus (3x)
- Portrait: 1242x2208px
- Landscape: 2208x1242px
Without actually seeing your output file for confirmation, my guess is that you've got to get rid of the FIELDS ESCAPED BY
value.
MySQL's FIELDS ESCAPED BY
is probably behaving in two ways that you were not counting on: (1) it is only meant to be one character, so in your case it is probably equal to just one quotation mark; (2) it is used to precede each character that MySQL thinks needs escaping, including the FIELDS TERMINATED BY
and LINES TERMINATED BY
values. This makes sense to most of the computing world, but it isn't the way Excel does escaping.
I think your double REPLACE
is working, and that you are successfully replacing literal newlines with spaces (two spaces in the case of Windows-style newlines). But if you have any commas in your data (literals, not field separators), these are being preceded by quotation marks, which Excel treats much differently than MySQL. If that's the case, then the erroneous newlines that are tripping up Excel are actually newlines that MySQL had intended as line terminators.
If downgrading from pip version 10 because of PyCharm manage.py or other python errors:
python -m pip install pip==9.0.1
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
There is no difference between the two, one is just a shorthand for the second.
The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
Source: official documentation.
It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.
1) If you want to count the number of occurrences of keys, you can just do:
Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1
2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:
Definition.get(key) # returns None if key not stored
Definition.get(key, default_other_than_none)
3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.
For example, if you only want to store values for those keys:
expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
Definition[key_found] = value
Or if you want to make sure all expected keys were found:
assert(all(key in Definition for key in expected_keys))
The choice should be based on the which idiom is best understood.
An array is iterated using:
for (var i = 0; i < a.length; i++)
//do stuff with a[i]
An object being used as an associative array is iterated using:
for (var key in o)
//do stuff with o[key]
Unless you have earth shattering reasons, stick to the established pattern of usage.
Sometimes you have to npm install package_name -g
for it to work.
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)
function. For instance, I wanted 3 decimal places:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'
specifies decimal format notation (more info here, you can also specify scientific notation) and the 3
specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number
function can be found here in the QString
documentation
I know this isn't exactly one command, but the desired result can be achieved from within phpMyAdmin by following these steps:
The idea is to quickly get all the tables from the database (which you do in 5 seconds and 2 clicks) but disable foreign key checks first. No CLI and no dropping the database and adding it again.
It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.
For example:
$("#theButton").button().click( function(event) {
$.post( url, data )
.always( function( response ) {
window.open( newurl + response, '_blank' );
} );
} );
will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:
$("#theButton").button().click( function(event) {
var newtab = window.open( '', '_blank' );
$.post( url, data )
.always( function( response ) {
newtab.location = newurl + response;
} );
} );
we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();
getElementById
returns a reference to the element using its id
. The element is the input
in the first case and the paragraph in the second case.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
I'm not sure if this would be a common mistake, but if you do something like:
$var = 'value' .= 'value2';
this will also produce the same error
Can't use method return value in write context
You can't have an =
and a .=
in the same statement. You can use one or the other, but not both.
Note, I understand this is unrelated to the actual code in the question, however this question is the top result when searching for the error message, so I wanted to post it here for completeness.
Add system variable (for Windows) "JAVA_TOOL_OPTIONS" = "-Dfile.encoding=UTF8".
I did it only way to fix this error.
if (Build.VERSION.SDK_INT >= 11) {
Point size = new Point();
try {
this.getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
} catch (NoSuchMethodError e) {
screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
}
} else {
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
}
Don't use list
as a variable name for it shadows the builtin.
And there is no need to determine the length of the list. Just iterate over it.
def printer(data):
for element in data:
print(element[0])
Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.
This is because an XML documentation file has been specified in your Project Properties and Your Method/Class is public and lack documentation.
You can either :
Right Click on your Project -> Properties -> 'Build' tab -> uncheck XML Documentation File.
Summary of XML documentation goes like this:
/// <summary>
/// Description of the class/method/variable
/// </summary>
..declaration goes here..
I am using Android Studio 0.8.1. I have a project's gradle file like below:
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.omersonmez.widgets.hotspot"
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
My emulator was android 4.0. So i modified my emulator and made api level 4.0.3(apilevel 15). It worked.
Note that const declarations are block-scoped.
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
So the value of definitelyAnElement is not accessible outside of the {}.
(I would have commented above, but I do not have enough Reputation apparently.)
By default node package is nodejs, so use
$ nodejs -v
or
$ nodejs --version
You can make a link using
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
then u can use
$ node --version
or
$ node -v
Depth first search with backtracking should work here. Keep an array of boolean values to keep track of whether you visited a node before. If you run out of new nodes to go to (without hitting a node you have already been), then just backtrack and try a different branch.
The DFS is easy to implement if you have an adjacency list to represent the graph. For example adj[A] = {B,C} indicates that B and C are the children of A.
For example, pseudo-code below. "start" is the node you start from.
dfs(adj,node,visited):
if (visited[node]):
if (node == start):
"found a path"
return;
visited[node]=YES;
for child in adj[node]:
dfs(adj,child,visited)
visited[node]=NO;
Call the above function with the start node:
visited = {}
dfs(adj,start,visited)
Here are 2 simple ways to calculate running total:
Approach 1: It can be written this way if your DBMS supports Analytical Functions
SELECT id
,somedate
,somevalue
,runningtotal = SUM(somevalue) OVER (ORDER BY somedate ASC)
FROM TestTable
Approach 2: You can make use of OUTER APPLY if your database version / DBMS itself does not support Analytical Functions
SELECT T.id
,T.somedate
,T.somevalue
,runningtotal = OA.runningtotal
FROM TestTable T
OUTER APPLY (
SELECT runningtotal = SUM(TI.somevalue)
FROM TestTable TI
WHERE TI.somedate <= S.somedate
) OA;
Note:- If you have to calculate the running total for different partitions separately, it can be done as posted here: Calculating Running totals across rows and grouping by ID
You need to add a width
and a height
of the background image for it to display properly.
For instance,
.header-shadow{
background-image: url('../images/header-shade.jpg');
width: XXpx;
height: XXpx;
}
As you mentioned that you are using it as a shadow, you can remove the width
and add a background-repeat
(either vertically or horizontally if required).
For instance,
.header-shadow{
background-image: url('../images/header-shade.jpg');
background-repeat: repeat-y; /* for vertical repeat */
background-repeat: repeat-x; /* for horizontal repeat */
height: XXpx;
}
PS: XX is a dummy value. You need to replace it with your actual values of your image.
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:
private void ComputeBySalesSalesID(DataSet dataSet)
{
// Presumes a DataTable named "Orders" that has a column named "Total."
DataTable table;
table = dataSet.Tables["Orders"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}
I must add that if you do not need to filter the results, you can always pass an empty string:
sumObject = table.Compute("Sum(Total)", "")
The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.
For example:
Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
"terms": {
"ssn": "123456789"
},
"order": { ... },
...
}
You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.
Adding to Ziav's answer (with thanks to Alexander Savin), I need to be using the old-school <a name="...">...</a>
as we're using <div id="...">...</div>
for another purpose in our code. I had some display issues using display: inline-block
-- the first line of every <p>
element was turning out to be slightly right-indented (on both Webkit and Firefox browsers). I ended up trying other display
values and display: table-caption
works perfectly for me.
.anchor {
padding-top: 60px;
margin-top: -60px;
display: table-caption;
}
The question is old, but I managed to figure out a simple way to have this in my app. You can create a C/C++ macro as shown below use it:
#ifndef MACROS_H
#define MACROS_H
#include <unistd.h>
#define msleep(X) usleep(X * 1000)
#endif // MACROS_H
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
$('#subscribeForm').validate( {
rules: {
list: {
required: true,
minlength: 1
}
}
});
I think this will make sure at least one is checked.
Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4
Example: Support in Angular UI upto ui 1.1.4
<div ui-if="array.length>0"></div>
ng-if available in all the angular version after 1.1.4
<div ng-if="array.length>0"></div>
if you have any data in array variable then only the div will appear
You're looking for the <iframe>
tag, or, better yet, a server-side templating language.
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
In the beaten-up MVC pattern, the Servlet is "C" - controller.
Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.
I would not, though, start writing raw Servlet
classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.
Use the rawurlencode
function instead.
FETCH_HEAD
is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull
first invokes git fetch
, in normal cases fetching a branch from the remote; FETCH_HEAD
points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull
then invokes git merge
, merging FETCH_HEAD
into the current branch.
The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.
This is a bit like doing git fetch
without arguments (or git remote update
), updating all your remote branches, then running git merge origin/<branch>
, but using FETCH_HEAD
internally instead to refer to whatever single ref was fetched, instead of needing to name things.
I solved this by overriding the default .modal.fade
styles in my own LESS stylesheet:
.modal {
&.fade {
.transition(e('opacity .3s linear'));
top: 50%;
}
&.fade.in { top: 50%; }
}
This keeps the fade in / fade out animation but removes the slide up / slide down animation.
I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .
if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);
}
But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !
You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.
To perform a request with a cookie attached just do the following:
var requestify = require('requestify');
requestify.post('http://google.com', {}, {
cookies: {
sessionCookie: 'session-cookie-data'
}
});
I'm using MVC 5 but you could try something like this:
public DateTime JobStart { get; set; }
[AssertThat("StartDate >= JobStart", ErrorMessage = "Time Manager may not begin before job start date")]
[DisplayName("Start Date")]
[Required]
public DateTime? StartDate { get; set; }
In your case you would say something like "IsSenior == true". Then you just need to check the validation on your post action.
I did a small benchmark on this topic. While many of the other posters have made good points about compatibility, my experience has been that PyPy isn't that much faster for just moving around bits. For many uses of Python, it really only exists to translate bits between two or more services. For example, not many web applications are performing CPU intensive analysis of datasets. Instead, they take some bytes from a client, store them in some sort of database, and later return them to other clients. Sometimes the format of the data is changed.
The BDFL and the CPython developers are a remarkably intelligent group of people and have a managed to help CPython perform excellent in such a scenario. Here's a shameless blog plug: http://www.hydrogen18.com/blog/unpickling-buffers.html . I'm using Stackless, which is derived from CPython and retains the full C module interface. I didn't find any advantage to using PyPy in that case.
Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from css. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.
What you can do is style the label:after selector and give it display:none, and set it's content from css. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:
label:after{
content: "my tooltip";
padding: 2px;
display:none;
position: relative;
top: -20px;
right: -30px;
width: 150px;
text-align: center;
background-color: #fef4c5;
border: 1px solid #d4b943;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
-ms-border-radius: 2px;
border-radius: 2px;
}
label:hover:after{
display: block;
}
Or you can use:
echo "1: " | awk '/1/{print $1-":"}'
This is a really funny equation.
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation: https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
Just a thought: maybe you don't need to create a method to return the values of the enum as an array of strings.
Why do you need the array of strings? Maybe you only need to convert the values when you use them, if you ever need to do that.
Examples:
for (State value:values()) {
System.out.println(value); // Just print it.
}
for (State value:values()) {
String x = value.toString(); // Just iterate and do something with x.
}
// If you just need to print the values:
System.out.println(Arrays.toString(State.values()));
It is because display:inline-block
takes into account white-space in the html. If you remove the white-space between the div
's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/
<div id="col1">content</div><div id="col2">content</div>
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
You can use the CHARINDEX
and specify the starting location:
DECLARE @x VARCHAR(32) = 'MS-SQL-Server';
SELECT
STUFF(STUFF(@x,3 , 0, '/'), 8, 0, '/') InsertString
,CHARINDEX('-',LTRIM(RTRIM(@x))) FirstIndexOf
,CHARINDEX('-',LTRIM(RTRIM(@x)), (CHARINDEX('-', LTRIM(RTRIM(@x)) )+1)) SecondIndexOf
,CHARINDEX('-',@x,CHARINDEX('-',@x, (CHARINDEX('-',@x)+1))+1) ThirdIndexOf
,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x)))) LastIndexOf;
GO
It's simple; make a custom cell and take a outlet of button
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.yourButton.tag = indexPath.Row;
- (void)buttonPressedAction:(id)sender
change id in above method to (UIButton *)
You can get the value that which button is being tapped by doing sender.tag.
If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.
You do not need the -p
option in order to expose ports from container to host. By default, all port are exposed. The -p
option allows you to expose a port from the container to the outside of the host.
So, my guess is that you do not need -p
at all and it should be working fine :)
This happend to me when the emulator froze and I had to kill the process. The signal icon always showed the small "x" as in the screenshot and no internet connection was successful.
The only thing that helped was uninstalling and reinstalling the emulator (not the AVD images)
In Android Studio:
Tools-> Android -> SDK Manager Uncheck "Android Emulator" and let it uninstall then check again and let it install again.
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
${RAILS_ENV}
postgres-log:/var/log/postgresql
I, however, use double-quotes for integer
values that need to be converted to strings like:
version: "3.8"
"8080:8080"
However, for special cases like booleans
, floats
, integers
, and other cases, where using double-quotes for the entry values could be interpreted as strings
, please do not use double-quotes.
Here's a sample docker-compose.yml
file to explain this concept:
version: "3"
services:
traefik:
image: traefik:v2.2.1
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.
Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.
Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r
to restore it.
Install alone didn't work for me.
mvn deploy:deploy-file -Durl=file:///home/me/project/lib/ \
-Dfile=target/jzmq-2.1.3-SNAPSHOT.jar -DgroupId=org.zeromq \
-DartifactId=zeromq -Dpackaging=jar -Dversion=2.1.3
In Oracle, you can use NULLS FIRST
or NULLS LAST
: specifies that NULL values should be returned before / after non-NULL values:
ORDER BY { column-Name | [ ASC | DESC ] | [ NULLS FIRST | NULLS LAST ] }
For example:
ORDER BY date DESC NULLS LAST
Ref: http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
The built-in round()
works just fine in Python 2.7 or later.
Example:
>>> round(14.22222223, 2)
14.22
Check out the documentation.
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor.
You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable. Sadly, some of Microsoft's graphical tools put this meaningless clause in.
As for why this might appear in dynamic SQL, I have no idea. You're correct that there's no reason for it, and the result is the same without it (and again, in the case of a view definition or derived table, without both the TOP and ORDER BY clauses).
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
Why not try IS?
$('selector').is(':checked') /* result true or false */
Look a FAQ: jQuery .is() enjoin us ;-)
.process-list:after{
content: "\2191";
position: absolute;
top:50%;
right:-8px;
background-color: #ea1f41;
width:35px;
height: 35px;
border:2px solid #ffffff;
border-radius: 5px;
color: #ffffff;
z-index: 10000;
-webkit-transform: rotate(50deg) translateY(-50%);
-moz-transform: rotate(50deg) translateY(-50%);
-ms-transform: rotate(50deg) translateY(-50%);
-o-transform: rotate(50deg) translateY(-50%);
transform: rotate(50deg) translateY(-50%);
}
you can check this code . i hope you will easily understand.
To amend SDP's answer above, you do NOT need to declarecol-xs-12
in <div class="col-xs-12 col-sm-6">
. Bootstrap 3 is mobile-first, so every div column is assumed to be a 100% width div by default - which means at the "xs" size it is 100% width, it will always default to that behavior regardless of what you set at sm, md, lg
. If you want your xs
columns to be not 100%, then you normally do a col-xs-(1-11)
.