Why not use a PdfPTable
object for this?
Create a fixed width table and use a float array to set the widths of the columns
PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);
addCell(table, "SER.\nNO.", 2);
addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);
addCell(table, "DESCRIPTION OF GOODS", 2);
addCell(table, "LINE DOC. RECL DATE", 1);
addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);
addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);
....
private static void addCell(PdfPTable table, string text, int rowspan)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPCell cell = new PdfPCell(new Phrase(text, times));
cell.Rowspan = rowspan;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.AddCell(cell);
}
have a look at this tutorial too...
Use multiselect function as below.
$('#drp_Books_Ill_Illustrations').multiSelect('select', 'value');
For me it depends on the component. If you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:
PropTypes.oneOfType
If you want to refer to a React component then you will be looking for
PropTypes.element
Although,
PropTypes.node
describes anything that can be rendered - strings, numbers, elements or an array of these things. If this suits you then this is the way.
With very generic components, who can have many types of children, you can also use the below - though bare in mind that eslint and ts may not be happy with this lack of specificity:
PropTypes.any
Both works. Instead of ==
you can write eq
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
Difference between process and thread are given below :
If you want to get back only the first row of a sorted result with the least subqueries, try this:
select *
from ( select a.*
, row_number() over ( order by sysdate_col desc ) as row_num
from table_name a )
where row_num = 1;
Try this
CSS
.header{
height:30px;
}
.Content{
height: 100%;
overflow: auto;
padding-top: 10px;
padding-bottom: 40px;
}
.Footer{
position: relative;
margin-top: -30px; /* negative value of footer height */
height: 30px;
clear:both;
}
HTML
<body>
<div class="Header">Header</div>
<div class="Content">Content</div>
<div class="Footer">Footer</div>
</body>
Since you don't really need the total number, and in fact want to perform an action after a certain number (in your case 5000), you can use java.nio.file.Files.newDirectoryStream
. The benefit is that you can exit early instead having to go through the entire directory just to get a count.
public boolean isOverMax(){
Path dir = Paths.get("C:/foo/bar");
int i = 1;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path p : stream) {
//larger than max files, exit
if (++i > MAX_FILES) {
return true;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return false;
}
The interface doc for DirectoryStream
also has some good examples.
Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).
If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all
, without any external libraries:
function asyncAction(i) {
return new Promise(function(resolve, reject) {
var result = calculateResult();
if (result.hasError()) {
return reject(result.error);
}
return resolve(result);
});
}
var promises = [];
for (var i=0; i < 10; i++) {
promises.push(asyncAction(i));
}
Promise.all(promises).then(function AcceptHandler(results) {
handleResults(results),
}, function ErrorHandler(error) {
handleError(error);
});
A more explicit example, built on Damien's code (calls a test resource at http://httpbin.org/). For python3. Note that if the server redirects to another URL, uri
in add_password
has to contain the new root URL (it's possible to pass a list of URLs, also).
import ssl
import urllib.parse
import urllib.request
def get_resource(uri, user, passwd=False):
"""
Get the content of the SSL page.
"""
uri = 'https://httpbin.org/basic-auth/user/passwd'
user = 'user'
passwd = 'passwd'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, uri, user, passwd)
auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
return urllib.request.urlopen(uri).read()
I just discovered you can do it with this call:
Url.Action(new UrlActionContext
{
Protocol = Request.Scheme,
Host = Request.Host.Value,
Action = "Action"
})
This will maintain the scheme, host, port, everything.
It is very simple to get input in java, all you have to do is:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
The kernel is part of the operating system and closer to the hardware it provides low level services like:
An operating system also includes applications like the user interface (shell, gui, tools, and services).
Z-Index only works for elements that have position: relative;
or position: absolute;
applied to them. If that's not the problem we'll need to see an example page to be more helpful.
EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
NOTE: Not 100% Cross Browser
Check browser compatibility @ http://caniuse.com/#search=FileReader
as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..
The Fiddle: http://jsfiddle.net/d2atnbrt/3/
THE HTML CODE:
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
THE JS CODE:
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed
This is as basic as i could get it,
EDIT - Generating A Table
The Fiddle: http://jsfiddle.net/d2atnbrt/5/
This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..
One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least
Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls
This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.
For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)
This worked for me. You can make the SELECT statement more complex, with WHERE and LIMIT clauses.
First duplicate your large table (without the data), run the following query, and then truncate the larger table.
INSERT INTO table_small (SELECT * FROM table_large WHERE column = 'value' LIMIT 100)
Super simple. :-)
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
I went to system
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php
file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
To round down towards negative infinity, use:
rounded=Math.floor(number);
To round down towards zero (if the number can round to a 32-bit integer between -2147483648 and 2147483647), use:
rounded=number|0;
To round down towards zero (for any number), use:
if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);
You should do a one-time setup of creating an "App password" in Bitbucket web UI with permissions to at least read your repositories and then use it in the command line.
How-to:
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
You can use View.clearFocus()
.
Use View.requestFocus()
called from onResume()
.
How about:
insert into my_table values('hi, my name' + char(39) + 's tim.')
eclipse\configuration\
"config.ini"
Modify the line
osgi.instance.area.default="F:/Workspace/Java"
where "F:/Workspace/Java"
should be your default workspace!
The Form
has two properties called MinimizeBox
and MaximizeBox
, set both of them to false
.
To stop the form closing, handle the FormClosing
event, and set e.Cancel = true;
in there and after that, set WindowState = FormWindowState.Minimized;
, to minimize the form.
Iconv just writes the converted text to stdout. You have to use -o OUTPUTFILE.txt
as an parameter or write stdout to a file. (iconv -f x -t z filename.txt > OUTPUTFILE.txt
or iconv -f x -t z < filename.txt > OUTPUTFILE.txt
in some iconv versions)
Synopsis
iconv -f encoding -t encoding inputfile
Description
The iconv program converts the encoding of characters in inputfile from one coded character set to another.
**The result is written to standard output unless otherwise specified by the --output option.**
--from-code, -f encoding
Convert characters from encoding
--to-code, -t encoding
Convert characters to encoding
--list
List known coded character sets
--output, -o file
Specify output file (instead of stdout)
--verbose
Print progress information.
No, absolutely not - because if acct
is null, it won't even get to isEmpty
... it will immediately throw a NullPointerException
.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of &&
here, rather than your ||
in the previous code; also note how in your previous code, your conditions were wrong anyway - even with &&
you would only have entered the if
body if acct
was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Either use SciPy whl, download the appropriate one and run pip install <whl_file>
OR
Read through SciPy Windows issue and run one of the methods.
OR
Use Miniconda.
Additionally, install Visual C++ compiler for python2.7 in-case it asks for it.
Codeplex is definitively the right place. Recent "post": SofaWPF.codeplex.com based on AvalonDock.codeplex.com, an IDE like framework.
For leaving the console window open you only have to add to the last command line in the batch file:
' & pause'
What’s New In Python 3.4
...
pip should always be available
...
By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.
https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453
so if you have python 3.4 installed, you can just: sudo pip3 install xxx
This works:
Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
if (iter.next() == 5) {
iter.remove();
}
}
I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove()
functionality.
We can replace the code in the AndroidManifest file in the application tag
android:icon="@drawable/logo"
tl;dr
date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s)) / (60*60*24) ))
Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:
DST started March 8th this year in the US, so let's use a date range spanning that:
start_ts=$(date -d "2015-03-05" '+%s')
end_ts=$(date -d "2015-03-11" '+%s')
Let's see what we get with the double parentheses:
echo $(( ( end_ts - start_ts )/(60*60*24) ))
Returns '5'.
Doing this using 'bc' with more accuracy gives us a different result:
echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc
Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.
So how should this be done correctly?
I would suggest using this instead:
printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)
Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.
Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:
date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))
This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
yes, safe to delete, my script searches and nukes every instance it finds, easily modified to a local directory
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
for drive in Swap Media OSX_10.11.6/$HOME
do
pushd /Volumes/${drive} &> /dev/null
gfind . -depth -name 'DerivedData'|xargs -I '{}' /bin/rm -fR '{}'
popd &> /dev/null
done
The following is the un-installation for PostgreSQL 9.1 installed using the EnterpriseDB installer. You most probably have to replace folder /9.1/ with your version number. If /Library/Postgresql/
doesn't exist then you probably installed PostgreSQL with a different method like homebrew
or Postgres.app
.
To remove the EnterpriseDB One-Click install of PostgreSQL 9.1:
Run the uninstaller:
sudo /Library/PostgreSQL/9.1/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
If you installed with the Postgres Installer, you can do:
open /Library/PostgreSQL/9.2/uninstall-postgresql.app
It will ask for the administrator password and run the uninstaller.
Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.
sudo rm -rf /Library/PostgreSQL
Remove the ini file:
sudo rm /etc/postgres-reg.ini
Remove the PostgreSQL user using System Preferences -> Users & Groups.
Restore your shared memory settings:
sudo rm /etc/sysctl.conf
That should be all! The uninstall wizard would have removed all icons and start-up applications files so you don't have to worry about those.
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
/Digger here/
Moving the icu*****.dll
files to /ext/
seems to resolve the issue as well.
( If you specified the extension directory to be there of course )
There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.
I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.
The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>
Here's an enum with status codes and their descriptions that (at time of writing) corresponds to the HTTP status code registry.
Note that the registry might get updated, and that sometimes unofficial status codes are used.
public enum HttpStatusCode {
//1xx: Informational
CONTINUE(100, "Continue"),
SWITCHING_PROTOCOLS(101, "Switching Protocols"),
PROCESSING(102, "Processing"),
EARLY_HINTS(103, "Early Hints"),
//2xx: Success
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
NO_CONTENT(204, "No Content"),
RESET_CONTENT(205, "Reset Content"),
PARTIAL_CONTENT(206, "Partial Content"),
MULTI_STATUS(207, "Multi-Status"),
ALREADY_REPORTED(208, "Already Reported"),
IM_USED(226, "IM Used"),
//3xx: Redirection
MULTIPLE_CHOICES(300, "Multiple Choice"),
MOVED_PERMANENTLY(301, "Moved Permanently"),
FOUND(302, "Found"),
SEE_OTHER(303, "See Other"),
NOT_MODIFIED(304, "Not Modified"),
USE_PROXY(305, "Use Proxy"),
TEMPORARY_REDIRECT(307, "Temporary Redirect"),
PERMANENT_REDIRECT(308, "Permanent Redirect"),
//4xx: Client Error
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
PAYMENT_REQUIRED(402, "Payment Required"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
NOT_ACCEPTABLE(406, "Not Acceptable"),
PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
REQUEST_TIMEOUT(408, "Request Timeout"),
CONFLICT(409, "Conflict"),
GONE(410, "Gone"),
LENGTH_REQUIRED(411, "Length Required"),
PRECONDITION_FAILED(412, "Precondition Failed"),
REQUEST_TOO_LONG(413, "Payload Too Large"),
REQUEST_URI_TOO_LONG(414, "URI Too Long"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
REQUESTED_RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable"),
EXPECTATION_FAILED(417, "Expectation Failed"),
MISDIRECTED_REQUEST(421, "Misdirected Request"),
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
LOCKED(423, "Locked"),
FAILED_DEPENDENCY(424, "Failed Dependency"),
TOO_EARLY(425, "Too Early"),
UPGRADE_REQUIRED(426, "Upgrade Required"),
PRECONDITION_REQUIRED(428, "Precondition Required"),
TOO_MANY_REQUESTS(429, "Too Many Requests"),
REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),
//5xx: Server Error
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
NOT_IMPLEMENTED(501, "Not Implemented"),
BAD_GATEWAY(502, "Bad Gateway"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
GATEWAY_TIMEOUT(504, "Gateway Timeout"),
HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"),
INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
LOOP_DETECTED(508, "Loop Detected"),
NOT_EXTENDED(510, "Not Extended"),
NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");
private final int value;
private final String description;
HttpStatusCode(int value, String description) {
this.value = value;
this.description = description;
}
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return value + " " + description;
}
public static HttpStatusCode getByValue(int value) {
for(HttpStatusCode status : values()) {
if(status.value == value) return status;
}
throw new IllegalArgumentException("Invalid status code: " + value);
}
}
The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.
You can try to see if you can select some data out of the Invoice table to make sure you have access.
Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:
EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO
Now just do your insert statement.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM MyInvoice
Hope this helps!
This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.
if you have many tables you want to change collation on run this query:
select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM
information_schema.tables where table_schema='SCHRMA') t;
this will output the queries needed to convert all the tables to use the correct collation per column
All above methods failed for me and then I found that I was not changing AllowOverride None to AllowOverride All in my virtual host file at /etc/apache2/sites-available/default
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride All <---- replace None with All
</Directory>
<Directory /var/www >
Options Indexes FollowSymLinks MultiViews
AllowOverride All <--- replace None with All
Order allow,deny
allow from all
</Directory>
...
Joseph forgot to add the value in his example with withDefault
.
Here is the code I ended up using:
Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }
you can try this way in Colab
!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers
For Windows and Python 3.x, my two cents contribution about renaming the file on download :
pip install wget
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')
Truely working command line example :
python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"
Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.
In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)
So, in the end your code will become like follow:
func main() {
url := "http://restapi3.apiary.io/notes"
fmt.Println("URL:>", url)
request := gorequest.New()
titleList := []string{"title1", "title2", "title3"}
for _, title := range titleList {
resp, body, errs := request.Post(url).
Set("X-Custom-Header", "myvalue").
Send(`{"title":"` + title + `"}`).
End()
if errs != nil {
fmt.Println(errs)
os.Exit(1)
}
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", body)
}
}
This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.
You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports
via Java Editor
- Save Action
. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.
As I understand your question..
From Java List class you have to methods add(E e)
and get(int position)
.
add(E e)
Appends the specified element to the end of this list (optional operation).
get(int index)
Returns the element at the specified position in this list.
Example:
List<String> myString = new ArrayList<String>();
// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");
// retrieving data from string list array in for loop
for (int i=0;i < myString.size();i++)
{
Log.i("Value of element "+i,myString.get(i));
}
But efficient way to iterate thru loop
for (String value : myString)
{
Log.i("Value of element ",value);
}
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
You can programmatically get the image and check the dimensions using Javascript...
const img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
_x000D_
This can be useful if the image is not a part of the markup.
find_elements_by_xpath("//*[@class='class name']")
is a great solution
Use upper-case HH
for 24h format:
String s = curr.ToString("HH:mm");
In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.
You are able to cut all odd/even columns by using seq:
This would print all odd columns
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)
To print all even columns you could use
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)
By changing the second number of seq you can specify which columns to be printed.
If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like
echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)
This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.
I don't know if this will help you but..
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );
For removing older versions of all installed gems, following 2 commands are useful:
gem cleanup --dryrun
Above command will preview what gems are going to be removed.
gem cleanup
Above command will actually remove them.
If you define the timezone in your PHP app (as you should), which you can do this way:
date_default_timezone_set('Europe/Paris');
Then it's as simple as:
$yesterday = new DateTime('yesterday'); // will use our default timezone, Paris
echo $yesterday->format('Y-m-d'); // or whatever format you want
(You may want to define a constant or environment variable to store your default timezone.)
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
A good way of going about this is not to use nargin
, but to check whether the variables have been set using exist('opt', 'var')
.
Example:
function [a] = train(x, y, opt)
if (~exist('opt', 'var'))
opt = true;
end
end
See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?
var value1=$("id1").val();
var value2=$("id2").val();
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
The best way to use is white-space: nowrap;
This will align the text to one line.
In my case I'm in wrong directory,
My directory Path
eCommerce-shop/eCommerce
I am in inside eCommerce-shop and executing this command composer intsall so that't it throwing this error.
If the bytes use an appropriate character encoding already; you could print them directly:
sys.stdout.buffer.write(data)
or
nwritten = os.write(sys.stdout.fileno(), data) # NOTE: it may write less than len(data) bytes
You can simply delete this folder
/Library/Developer/CommandLineTools
Please note: This is the root /Library, not user's ~/Library).
Both array_push
and the method you described will work.
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
Is the same as:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
I had this problem when I was trying to use the range.AddComment() function. I was able to solve this by calling range.ClearComment() before adding the comment.
As you said..
$Gender = isset($_POST["gender"]); ' it returns a empty string
because, you haven't mention method type either use POST or GET, by default it will use GET method. On the other side, you are trying to retrieve your value by using POST method, but in the form you haven't mentioned POST method. Which means miss-match method will result for empty.
Try this code..
<form name="signup_form" action="./signup.php" onsubmit="return validateForm()" method="post">
<table>
<tr> <td> First Name </td><td> <input type="text" name="fname" size=10/></td></tr>
<tr> <td> Last Name </td><td> <input type="text" name="lname" size=10/></td></tr>
<tr> <td> Your Email </td><td> <input type="text" name="email" size=10/></td></tr>
<tr> <td> Re-type Email </td><td> <input type="text" name="remail"size=10/></td></tr>
<tr> <td> Password </td><td> <input type="password" name="paswod" size=10/> </td></tr>
<tr> <td> Gender </td><td> <select name="gender">
<option value="select"> Select </option>
<option value="male"> Male </option>
<option value="female"> Female </option></select></td></tr>
<tr> <td> <input type="submit" value="Sign up" id="signup"/> </td> </tr>
</table>
</form>
and on signup page
$Gender = $_POST["gender"];
i'm sure.. now, you will get the value..
I had to dig a little to find the source of the following Built-in Functions
as the search would yield thousands of results. (Good luck searching for any of those to find where it's source is)
Anyway, all those functions are defined in bltinmodule.c
Functions start with builtin_{functionname}
Built-in Source: https://github.com/python/cpython/blob/master/Python/bltinmodule.c
For Built-in Types: https://github.com/python/cpython/tree/master/Objects
A one-line bash script would be easy to do - replace *.avi
with your filetype:
for i in *.avi; do ffmpeg -i "$i" -qscale 0 "$(basename "$i" .avi)".mov ; done
Update: capability appears to have been removed by Apple on or around iOS 4
Just to expand on an earlier answer, something like this does it for me:
NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.
At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)
WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey
and so on.
Not sure what, if anything, the others do.
Set below code in RouteConfig.cs in App_Start folder
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}
IF still not working then do below steps
Second Way : You simple follow below steps,
1) Right click on your Project
2) Select Properties
3) Select Web option and then Select Specific Page (Controller/View) and then set your login page
Here, Account is my controller and Login is my action method (saved in Account Controller)
Please take a look attached screenshot.
This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.
You can get the current log file assigned natively to php on any platform at runtime by using:
ini_get('error_log');
This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.
You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.
create json folder in resources as subfolder then add json file in folder then you can use this code :
import com.fasterxml.jackson.core.type.TypeReference;
InputStream is = TypeReference.class.getResourceAsStream("/json/fcmgoogletoken.json");
this works in Docker.
Go to Build Gradle (Module:app) Change the following. In my case, I choose 25.0.3
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.cesarhcq.viisolutions"
minSdkVersion 15
targetSdkVersion 25
After that, it works fine!
No. I create labels above the listbox to serve as headers. You might think that it's a royal pain to change labels every time your lisbox changes. You'd be right - it is a pain. It's a pain to set up the first time, much less changes. But I haven't found a better way.
Here is a workaround to copy all the objects from one arrayList to another:
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
myObject.addAll(myTempObject.subList(0, myTempObject.size()));
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.
In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path
object, to take advantage of its getName(int)
method.
Unfortunately, the static factory Paths.get(uri)
is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.
URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();
To get the last segment in one line of code, simply nest the lines above.
Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()
To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent()
method.
String secondToLast = path.getParent().getFileName().toString();
Note the getParent()
method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent()
would retrieve the third-to-last segment.
In my case it had to do with the Microsoft.Build.Bcl version. My nuget package version was 1.0.21, but my project files were still pointing to version 1.0.14
So I changed my .csproj files from:
<Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
to:
<Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
<Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
And the build was working again.
Perhaps something like this for the first problem, you can simply access the columns by their names:
>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
b e
1 0.071146 0.132145
2 0.495152 0.420219
For the second problem:
>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556, 0.13214495],
[ 0.49515157, 0.42021946]])
Use RegEx.Replace, something like this:
string input = "This is text with far too much " +
"whitespace.";
string pattern = "[;,]";
string replacement = "\n";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Here's more info on this MSDN documentation for RegEx.Replace
You need to read each byte from your InputStream
and write it to a ByteArrayOutputStream
.
You can then retrieve the underlying byte array by calling toByteArray()
:
InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
The reader acts like a generator. On a file with some fake data:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Using operator.itemgetter as Ignacio suggests:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
(As of July 31, 2017)
SWIFT 3
self.yourCustomView.removeFromSuperview()
self.yourCustomViewParentView.addSubview(self.yourCustomView)
Objective C
[self.yourCustomView removeFromSuperview];
[self.yourCustomViewParentView addSubview:self.yourCustomView];
This is the easiest way to quickly remove all constraints that exist on a UIView. Just be sure to add the UIView back with it's new constraints or new frame afterwards =)
As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:
for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i
I Found the esiest soltuion just wrap the button with div and put text-center align-items-center in it like this :
<div text-center align-items-center>
<buttonion-button block class="button-design " text-center>Sign In </button>
</div>
Hi Could you try this line cmd its work for me
python -m pip install --user --upgrade pip
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
I'm still a beginner in JavaScript, but I wrote a small function to recursively print all the properties of an object and its children:
getDescription(object, tabs) {
var str = "{\n";
for (var x in object) {
str += Array(tabs + 2).join("\t") + x + ": ";
if (typeof object[x] === 'object' && object[x]) {
str += this.getDescription(object[x], tabs + 1);
} else {
str += object[x];
}
str += "\n";
}
str += Array(tabs + 1).join("\t") + "}";
return str;
}
A simple example for the usage of JSONP.
client.html
<html>
<head>
</head>
body>
<input type="button" id="001" onclick=gO("getCompany") value="Company" />
<input type="button" id="002" onclick=gO("getPosition") value="Position"/>
<h3>
<div id="101">
</div>
</h3>
<script type="text/javascript">
var elem=document.getElementById("101");
function gO(callback){
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://localhost/test/server.php?callback='+callback;
elem.appendChild(script);
elem.removeChild(script);
}
function getCompany(data){
var message="The company you work for is "+data.company +"<img src='"+data.image+"'/ >";
elem.innerHTML=message;
}
function getPosition(data){
var message="The position you are offered is "+data.position;
elem.innerHTML=message;
}
</script>
</body>
</html>
server.php
<?php
$callback=$_GET["callback"];
echo $callback;
if($callback=='getCompany')
$response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";
else
$response="({\"position\":\"Development Intern\"})";
echo $response;
?>
You will need to go to Project->Clean...,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace.
As other have already suggested it is likely you are getting a NullReferenceException
which can be avoided by first checking to see if the reference is null
. However, you need to ask yourself whether that check is actually warranted. Would you be doing it because the reference really might be null
and it being null
has a special meaning in your code? Or would you be doing it to cover up a bug? The nature of the question leads me to believe it would be the latter. In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.
Building on @JustinBarber's example and noting @eric.frederich's comment, if you want to format negative values like -$1,000.00
rather than $-1,000.00
and don't want to use locale
:
def as_currency(amount):
if amount >= 0:
return '${:,.2f}'.format(amount)
else:
return '-${:,.2f}'.format(-amount)
Yes the tab character is one character. You can match it in java with "\t".
Just for another possibility to check, I came up with exactly the same problem with an incorrect port number specified in connect URL. I created a new oracle11g instance and forgot to kill the former one occupying the same port 1521, so the new instance automatically started on port 1522. Editing port number solved my problem.
Perhaps a code example would help, I'm going to use C#, but you should be able to follow along.
Lets pretend we have an interface called IPayable
public interface IPayable
{
public Pay(double amount);
}
Now, we have two concrete classes that implement this interface:
public class BusinessAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
public class CustomerAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
Now, lets pretend we have a collection of various accounts, to do this we will use a generic list of the type IPayable
List<IPayable> accountsToPay = new List<IPayable>();
accountsToPay.add(new CustomerAccount());
accountsToPay.add(new BusinessAccount());
Now, we want to pay $50.00 to all those accounts:
foreach (IPayable account in accountsToPay)
{
account.Pay(50.00);
}
So now you see how interfaces are incredibly useful.
They are used on instantiated objects only. Not on static classes.
If you had made pay static, when looping through the IPayable's in accountsToPay there would be no way to figure out if it should call pay on BusinessAcount or CustomerAccount.
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order. This worked for me
You defined one oracleCommand but used it in 'for'.
it means you are adding parameter with the same name to one OracleCommand.
you should use cmd.Parameters.clear()
to refresh your parameters.
for(int i=0;i<usersList.Count;i++)
{
if (!(selectedUsersArray[i].Equals("")) && !passwordArray[i].Equals(""))
{
cmd.Parameters.clear();//Add this line
OracleParameter userName = new OracleParameter();
userName.ParameterName = "user";
userName.Value = selectedUsersArray[i];
OracleParameter passwd = new OracleParameter();
passwd.ParameterName = "password";
passwd.Value = passwordArray[i];
cmd.Parameters.Add(userName);
cmd.Parameters.Add(passwd);
cmd.Prepare();
cmd.ExecuteNonQuery();
}
}
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
id
is the method you want to use: to convert it to hex:
hex(id(variable_here))
For instance:
x = 4
print hex(id(x))
Gave me:
0x9cf10c
Which is what you want, right?
(Fun fact, binding two variables to the same int
may result in the same memory address being used.)
Try:
x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))
This gave me identical pairs, even for the large integers.
Adding this in conf.d fixed this issue for me.
Options +Indexes +FollowSymLinks
If you have a DataTable in your application, and this is where the 1000 names are coming from, you can use a table-valued parameter for this.
First, a table type:
CREATE TYPE dbo.Names AS TABLE
(
Name NVARCHAR(255),
email VARCHAR(320),
[password] VARBINARY(32) -- surely you are not storing this as a string!?
);
Then a procedure to use this:
CREATE PROCEDURE dbo.Names_BulkInsert
@Names dbo.Names READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.RealTable(Name, email, password)
SELECT Name, email, password
FROM @Names;
END
GO
Then your C# code can say:
SqlCommand cmd = new SqlCommand("dbo.Names_BulkInsert", connection_object);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter names = cmd.Parameters.AddWithValue("@Names", DataTableName);
names.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
If you just want to generate 1000 rows with random values:
;WITH x AS
(
SELECT TOP (1000) n = REPLACE(LEFT(name,32),'_','')
FROM sys.all_columns ORDER BY NEWID()
)
-- INSERT dbo.sometable(name, email, [password])
SELECT
name = LEFT(n,3),
email = RIGHT(n,5) + '@' + LEFT(n,2) + '.com',
[password] = CONVERT(VARBINARY(32), SUBSTRING(n, 1, 32))
FROM x;
In neither of these cases should you be using while loops or cursors. IMHO.
You do not have to move the mouse to get the cursor's location. The location is also reported on events other than mousemove. Here's a click-event as an example:
document.body.addEventListener('click',function(e)
{
console.log("cursor-location: " + e.clientX + ',' + e.clientY);
});
It's pretty straightforward using [
to extract:
grep
will give you the position in which it matched your search pattern (unless you use value = TRUE
).
grep("^G45", My.Data$x)
# [1] 2
Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [
(where you would use My.Data[rows, cols]
to get specific rows and columns).
My.Data[grep("^G45", My.Data$x), ]
# x y
# 2 G459 2
The help-page for subset
shows how you can use grep
and grepl
with subset
if you prefer using this function over [
. Here's an example.
subset(My.Data, grepl("^G45", My.Data$x))
# x y
# 2 G459 2
As of R 3.3, there's now also the startsWith
function, which you can again use with subset
(or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring
or grepl
.
subset(My.Data, startsWith(as.character(x), "G45"))
# x y
# 2 G459 2
Install from
linux
terminal
sudo apt-get install <php_version>-dev
Example :
sudo apt-get install php5-dev #For `php` version 5
sudo apt-get install php7.0-dev #For `php` version 7.0
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
I think that you'll probably have to use $.ajax()
if you want to change the encoding, see the contentType
param below (the success
and error
callbacks assume you have <div id="success"></div>
and <div id="error"></div>
in the html):
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
I actually just had to do this about an hour ago, what a coincidence!
I simply write it this way
in the AspectType file:
class AspectType {
//blah blah
}
module.exports = AspectType;
and import it like this:
const AspectType = require('./AspectType');
var aspectType = new AspectType;
not() is a function in xpath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]
It works here:
$ wget -S -O - http://google.com
HTTP request sent, awaiting response...
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 25 Aug 2012 10:15:38 GMT
Expires: Mon, 24 Sep 2012 10:15:38 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29-- http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...
...skipped a few more redirections ...
[<=> ] 0 --.-K/s
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti
... skipped ...
perhaps you need to update your wget (~$ wget --version
GNU Wget 1.14 built on linux-gnu.
)
If you don't know where it is, locate nginx first.
ps -ef | grep nginx
Then you will see something like this:
root 4801 1 0 May23 ? 00:00:00 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
root 12427 11747 0 03:53 pts/1 00:00:00 grep --color=auto nginx
nginx 24012 4801 0 02:30 ? 00:00:00 nginx: worker process
nginx 24013 4801 0 02:30 ? 00:00:00 nginx: worker process
So now you already know where nginx is. You can use the -v or -V. Something like:
/opt/nginx/sbin/nginx -v
If you choose Project
and then All Files
in the menu, all files should be displayed in the Solution Explorer that are physically in your project map, but not (yet) included in your project. If you right click on the file you want to add in the Solution Explorer, you can include it.
NOTE : this is just an abbreviation of this answer above
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing
, System.Web.Net
and System.Net.Http
dlls if not there already
Add the following class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Add Application_Start
method if not there already (in global.asax.cs file)
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Right click controllers folder > add new item > web > Add Web API controller
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
}
}
Add this code where you want to click and load Fragment. I hope it's work for you.
Fragment fragment = new yourfragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I also met this problem in a Fragment. And I called startActivityForResult
in a DialogFragment
.
But now this problem has been resolved:
FragmentClassname.this.startActivityForResult
.
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
if you need it in rails you can use first (source code)
'1234567890'.first(5) # => "12345"
there is also last (source code)
'1234567890'.last(2) # => "90"
alternatively check from/to (source code):
"hello".from(1).to(-2) # => "ell"
For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;
You will need the sudo password.
sudo nano /etc/nginx/conf.d/uploads.conf
Replace contents with the following;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
client_max_body_size 24M;
client_body_buffer_size 128k;
client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1
) of variable j
through const reference, i
will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y
to i
Second statement assigns the value 99
to i
Use Android Query library, very cool indeed.You can change it to use ProgressDialog
as you see in other examples, this one will show progress view from your layout and hide it after completion.
File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
if (file != null) {
// do something with file
}
}
});
If you want to run a cron every n
minutes, there are a few possible options depending on the value of n
.
n
divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)
Here, the solution is straightforward by making use of the /
notation:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
m-59/n * * * * command
In the above, n
represents the value n
and m
represents a value smaller than n
or *
. This will execute the command at the minutes m,m+n,m+2n,...
n
does NOT divide 60
If n
does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC
. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n
minutes later.
% date -d '2015-10-21 07:28:00' +%s
1445412480
For a cronjob to run every 42
nd minute after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * * minutetestcmd "2015-10-21 07:28:00" 42 && command
with minutetestcmd
defined as
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))
Remark: UNIX time is not influenced by leap seconds
Remark: cron
has no sub-second accuracy
Sometimes I resolved similar situations (such as using pandas.apply method) using closures
In order to use them, you define a function which dynamically defines and returns a wrapper for your function, effectively making one of the parameters a constant.
Something like this:
def add(x, y):
return x + y
def add_constant(y):
def f(x):
return add(x, y)
return f
Then, add_constant(y)
returns a function which can be used to add y
to any given value:
>>> add_constant(2)(3)
5
Which allows you to use it in any situation where parameters are given one at a time:
>>> map(add_constant(2), [1,2,3])
[3, 4, 5]
edit
If you do not want to have to write the closure function somewhere else, you always have the possibility to build it on the fly using a lambda function:
>>> map(lambda x: add(x, 2), [1, 2, 3])
[3, 4, 5]
In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.
(Optional) Swap off
$ swapoff -a
You have to restart all Docker containers
$ docker restart $(docker ps -a -q)
Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)
$ kubectl get nodes
Restart the node
$ systemctl restart kubelet
Check again the status (now should be in Ready status)
Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
You have to use initiailzers:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
{
}
};
This is also how you construct members of your class that don't have constructors (or that you want to initialize). Any members not mentioned will be default initialized. For example:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
, nc(<insert arguments here>)
//di will be default initialized.
{
}
private:
NeedsConstructor nc;
CanBeDefaultInit di;
};
The order the members are specified in is irrelevant (though the constructors must come first), but the order that they will be constructed in is in declaration order. So nc
will always be constructed before di
.
char mystring[101] = "My sample string";
const char * constcharp = mystring; // (1)
char const * charconstp = mystring; // (2) the same as (1)
char * const charpconst = mystring; // (3)
constcharp++; // ok
charconstp++; // ok
charpconst++; // compile error
constcharp[3] = '\0'; // compile error
charconstp[3] = '\0'; // compile error
charpconst[3] = '\0'; // ok
// String literals
char * lcharp = "My string literal";
const char * lconstcharp = "My string literal";
lcharp[0] = 'X'; // Segmentation fault (crash) during run-time
lconstcharp[0] = 'X'; // compile error
// *not* a string literal
const char astr[101] = "My mutable string";
astr[0] = 'X'; // compile error
((char*)astr)[0] = 'X'; // ok
This may helps:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
WebResourceResponse response = super.shouldInterceptRequest(view, request);
// load native js
if (url != null && url.contains(INJECTION_TOKEN/* scheme define */)) {
response = new WebResourceResponse(
"text/javascript",
"utf-8",
loadJsInputStream(url, JsCache.getJsFilePath(path) /* InputStream */));
}
return response;
}
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
SELECT a AS current_a, COUNT(*) AS b,
(SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
from t group by a order by b desc
I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.
The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.
Yes you can do multi-threading in PHP with pthreads
From the PHP documentation:
pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.
Warning: The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.
Simple Test
#!/usr/bin/php
<?php
class AsyncOperation extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg);
}
}
}
// Create a array
$stack = array();
//Initiate Multiple Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
First Run
12:00:06pm: A -start -sleeps 5
12:00:06pm: B -start -sleeps 3
12:00:06pm: C -start -sleeps 10
12:00:06pm: D -start -sleeps 2
12:00:08pm: D -finish
12:00:09pm: B -finish
12:00:11pm: A -finish
12:00:16pm: C -finish
Second Run
12:01:36pm: A -start -sleeps 6
12:01:36pm: B -start -sleeps 1
12:01:36pm: C -start -sleeps 2
12:01:36pm: D -start -sleeps 1
12:01:37pm: B -finish
12:01:37pm: D -finish
12:01:38pm: C -finish
12:01:42pm: A -finish
Real World Example
error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
public $url;
public $data;
public function __construct($url) {
$this->url = $url;
}
public function run() {
if (($url = $this->url)) {
/*
* If a large amount of data is being requested, you might want to
* fsockopen and read using usleep in between reads
*/
$this->data = file_get_contents($url);
} else
printf("Thread #%lu was not provided a URL\n", $this->getThreadId());
}
}
$t = microtime(true);
$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));
/* starting synchronization */
if ($g->start()) {
printf("Request took %f seconds to start ", microtime(true) - $t);
while ( $g->isRunning() ) {
echo ".";
usleep(100);
}
if ($g->join()) {
printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data));
} else
printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);
}
Have you had a look at getcwd()
?
#include <unistd.h>
char *getcwd(char *buf, size_t size);
Simple example:
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.
Example of what you can't do which you are asking:
Cat c;
c = NULL;//Compiling error
Example of what you can do:
Cat c;
//Set p to hold the memory address of the object c
Cat *p = &c;
//Set p to hold NULL
p = NULL;
You can bind a click handler that returns false:
$('.my-link').click(function () {return false;});
To re-enable it again, unbind the handler:
$('.my-link').unbind('click');
Note that disabled
doesn't work because it is designed for form inputs only.
jQuery has anticipated this already, providing a shortcut as of jQuery 1.4.3:
$('.my-link').bind('click', false);
And to unbind / re-enable:
$('.my-link').unbind('click', false);
That worked for me:
$ export LC_ALL=en_US.UTF-8
$ export LANG=en_US.UTF-8
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
I had a similar problem in spring tool suite(sts). THE .m2 repository was not completely downloaded in the local system which is the reason why I was getting this error. So I reinstalled sts and deleted the old .m2 repository from the system and created a new maven project in sts which downloaded the complete .m2 repository. It worked for me.
Here is another solution suggested by p3trus:
$([IPython.events]).on('notebook_loaded.Notebook', function(){
IPython.toolbar.add_buttons_group([
{
'label' : 'toggle input cells',
'icon' : 'icon-refresh',
'callback': function(){$('.input').slideToggle()}
}
]);
});
As described by p3trus:
"[It] adds a button to the ipython notebook toolbar to hide/show the input code cell. To use it, you have to put the custom.js file in your .ipython_<profile name>/static/custom/
folder, where is the ipython profile in use."
My own comments: I verified this solution and it works with iPython 3.1.0.
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
Based on the List Members Instance docs, the easiest way is to use a PUT
request which according to the docs either "adds a new list member or updates the member if the email already exists on the list".
Furthermore apikey
is definitely not part of the json schema and there's no point in including it in your json request.
Also, as noted in @TooMuchPete's comment, you can use CURLOPT_USERPWD
for basic http auth as illustrated in below.
I'm using the following function to add and update list members. You may need to include a slightly different set of merge_fields
depending on your list parameters.
$data = [
'email' => '[email protected]',
'status' => 'subscribed',
'firstname' => 'john',
'lastname' => 'doe'
];
syncMailchimp($data);
function syncMailchimp($data) {
$apiKey = 'your api key';
$listId = 'your list id';
$memberId = md5(strtolower($data['email']));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => $data['firstname'],
'LNAME' => $data['lastname']
]
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
Disclaimer: I have read this question for days, but it is beyond my knowledge to understand the math.
I tried to solve it using set:
arr=[1,2,4,5,7,8,10] # missing 3,6,9
NMissing=3
arr_origin = list(range(1,arr[-1]+1))
for i in range(NMissing):
arr.append(arr[-1]) ##### assuming you do not delete the last one
arr=set(arr)
arr_origin=set(arr_origin)
missing=arr_origin-arr # 3 6 9
That's the way I use it:
global.ts
export var server: string = 'http://localhost:4200/';
export var var2: number = 2;
export var var3: string = 'var3';
to use it just import like that:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import * as glob from '../shared/global'; //<== HERE
@Injectable()
export class AuthService {
private AuhtorizationServer = glob.server
}
EDITED: Droped "_" prefixed as recommended.
You can set the variable 'fileencodings' in your .vimrc.
This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.
See :help filencodings
If you often work with e.g. cp1252, you can add it there:
set fileencodings=ucs-bom,utf-8,cp1252,default,latin9
An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends
import java.io.printstream;
class PPrint {
static PPrintStream oout = new PPrintStream();
}
class PPrintStream {
void print(String str) {
System.out.println(str)
}
}
class outputstreamDemo {
public static void main(String args[]) {
System.out.println("hello world");
System.out.prinln("this is output stream demo");
}
}
Based on Derek's answer, I verified that
document.getElementById('testTarget')
.dispatchEvent(new MouseEvent('click', {shiftKey: true}))
works as expected even with key modifiers. And this is not a deprecated API, as far as I can see. You can verify on this page as well.
As many have suggested, JRE v1.7 and above has File.toPath();
File yourFile = ...;
Path yourPath = yourFile.toPath();
On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;
File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());
You can try if(typeof object !== 'undefined')
Here's your solution: JsFiddle
Basically, place your button into a div with centred text:
<div class="wrapper">
<button class="button">Button</button>
</div>
With the following styles:
.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 50%;
}
There are many ways to skin a cat, and this is just one.
You can specify that the data to be returned is not JSON using responseType
.
In your example, you can use a responseType
string value of text
, like this:
return this.http.post(
'http://10.0.1.19/login',
{email, password},
{responseType: 'text'})
The full list of options for responseType
is:
json
(the default)text
arraybuffer
blob
See the docs for more information.
From sun docs:
\s A whitespace character: [ \t\n\x0B\f\r]
The simplest way is to use it with regex.
For more information, the following page describes why you never need to use new Array()
You never need to use
new Object()
in JavaScript. Use the object literal{}
instead. Similarly, don’t usenew Array()
, use the array literal[]
instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.Do not use
new Number
,new String
, ornew Boolean
. These forms produce unnecessary object wrappers. Just use simple literals instead.
Also check out the comments - the new Array(length)
form does not serve any useful purpose (at least in today's implementations of JavaScript).
protected $primaryKey = 'SongID';
After adding to my model to tell the primary key because it was taking id(SongID) by default
In C char
gets promoted to int
in expressions. That pretty much explains every question, if you think about it.
Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie
A must read if you want to learn C.
Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.
try this:
function showDiv(divId, element)_x000D_
{_x000D_
document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';_x000D_
}
_x000D_
#hidden_div {_x000D_
display: none;_x000D_
}
_x000D_
<select id="test" name="form_select" onchange="showDiv('hidden_div', this)">_x000D_
<option value="0">No</option>_x000D_
<option value="1">Yes</option>_x000D_
</select>_x000D_
<div id="hidden_div">This is a hidden div</div>
_x000D_
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
Ex:
CREATE TABLE 'test'.'pic' (
'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'caption' VARCHAR(45) NOT NULL,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('idpic')
)
As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.
Nowadays we have to use match_parent
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background">
</RelativeLayout>
With Spring OAuth 2.0.7-RELEASE the following command works for me
curl -v -u [email protected]:12345678 -d "grant_type=client_credentials" http://localhost:9999/uaa/oauth/token
It works with Chrome POSTMAN too, just make sure you client and secret in "Basic Auth" tab, set method to "POST" and add grant type in "form data" tab.
This always works for me:
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
#wrapper {
min-height: 100%;
}
</style>
<!--[if lte IE 6]>
<style type="text/css">
#container {
height: 100%;
}
</style>
<![endif]-->
</head>
<body>
<div id="wrapper">some content</div>
</body>
This is probably the simplest solution to this problem. Only need to set four CSS attributes (although one of them is only to make IE happy).
Your E
class doesn't have a member of type struct X
, you've just defined a nested struct X
in there (i.e. you've defined a new type).
Try:
#include <iostream>
class E
{
public:
struct X { int v; };
X x; // an instance of `struct X`
};
int main(){
E object;
object.x.v = 1;
return 0;
}
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
It's a conceptual problem.
Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.
Check this out: How to replace all occurrences of a string in JavaScript?
Short answer:
str.replace(/%20/g, " ");
EDIT: In this case you could also do the following:
decodeURI(str)
A little late, but thought I might share anyway. I found it useful to add a prototype extension to Object. That way I can pad numbers and strings, left or right. I have a module with similar utilities I include in my scripts.
// include the module in your script, there is no need to export
var jsAddOns = require('<path to module>/jsAddOns');
~~~~~~~~~~~~ jsAddOns.js ~~~~~~~~~~~~
/*
* method prototype for any Object to pad it's toString()
* representation with additional characters to the specified length
*
* @param padToLength required int
* entire length of padded string (original + padding)
* @param padChar optional char
* character to use for padding, default is white space
* @param padLeft optional boolean
* if true padding added to left
* if omitted or false, padding added to right
*
* @return padded string or
* original string if length is >= padToLength
*/
Object.prototype.pad = function(padToLength, padChar, padLeft) {
// get the string value
s = this.toString()
// default padToLength to 0
// if omitted, original string is returned
padToLength = padToLength || 0;
// default padChar to empty space
padChar = padChar || ' ';
// ignore padding if string too long
if (s.length >= padToLength) {
return s;
}
// create the pad of appropriate length
var pad = Array(padToLength - s.length).join(padChar);
// add pad to right or left side
if (padLeft) {
return pad + s;
} else {
return s + pad;
}
};
(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...
function isScrollable( el ){_x000D_
var y1 = el.scrollTop;_x000D_
el.scrollTop += 1;_x000D_
var y2 = el.scrollTop;_x000D_
el.scrollTop -= 1;_x000D_
var y3 = el.scrollTop;_x000D_
el.scrollTop = y1;_x000D_
var x1 = el.scrollLeft;_x000D_
el.scrollLeft += 1;_x000D_
var x2 = el.scrollLeft;_x000D_
el.scrollLeft -= 1;_x000D_
var x3 = el.scrollLeft;_x000D_
el.scrollLeft = x1;_x000D_
return {_x000D_
horizontallyScrollable: x1 !== x2 || x2 !== x3,_x000D_
verticallyScrollable: y1 !== y2 || y2 !== y3_x000D_
}_x000D_
}_x000D_
function check( id ){_x000D_
alert( JSON.stringify( isScrollable( document.getElementById( id ))));_x000D_
}
_x000D_
#outer1, #outer2, #outer3 {_x000D_
background-color: pink;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
}_x000D_
#inner {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
}_x000D_
button { margin: 2em 0 0 1em; }
_x000D_
<div id="outer1" style="width: 100px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer1')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer2" style="width: 200px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer2')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer3" style="width: 100px; height: 180px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer3')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>
_x000D_
open your Redis cli and There two possible option that you could use:
FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.
Synchronous option in-case if you are not a JS expert like me. Had to spend some time on how to access the inline function variable
var token = crypto.randomBytes(64).toString('hex');
In order to get last N records you can execute below query:
db.yourcollectionname.find({$query: {}, $orderby: {$natural : -1}}).limit(yournumber)
if you want only one last record:
db.yourcollectionname.findOne({$query: {}, $orderby: {$natural : -1}})
Note: In place of $natural
you can use one of the columns from your collection.
Here is a general purpose readable function that avoids using regex:
// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
int iStart = text.IndexOf(start);
iStart = (iStart == -1) ? 0 : iStart + start.Length;
int iEnd = text.LastIndexOf(end);
if(iEnd == -1)
{
iEnd = text.Length;
}
int len = iEnd - iStart;
return text.Substring(iStart, len);
}
To call it in your particular example you can do:
string result = ExtractBetween("User name (sales)", "(", ")");
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read()
reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while
cycle). So if you write 25
+ Enter, it will return the unicode value of 2
that is 50
. If you redo a second Console.Read()
it will return immediately with 53
(the unicode value of 5
). A third and a fourth Console.Read()
will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine()
reads a string
(so then you need to change the string to a double
)
I recently updated from PHP 5.4.44 to PHP 5.6.12 on my Windows 8.1 OS and got this phpMyAdmin missing mbstring error message.
After trying the above suggestions, none of which worked for me, I discovered version 5.4.44 placed the DLL extensions in the PHP root directory whereas version 5.6.12 placed them in the PHP\ext subdirectory.
All very fine except unfortunately someone forgot to change the php.ini accordingly. So two possible solutions:
I chose the easier first and phpMyAdmin now works fine.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, r As Range
Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
If rng Is Nothing Then Exit Sub
For Each r In rng
If Not IsEmpty(r.Value) Then
r.Copy Destination:=Sheets("sheet2").Range("a2")
End If
Next
Set rng = Nothing
End Sub
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
From what the other answers have proposed, I believe this might help:
var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;
However, this is not tested, just an assumption based on the constant repetition of:
object["string"] = value;
//object = {string: value}
Download and install Visual C++ Express.
Download and extract "freeglut 2.8.0 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/
Installation for Windows 32 bit:
(a) Copy all files from include/GL folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl folder.
(b) Copy all files from lib folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib folder.
(c) Copy freeglut.dll and paste into C:\windows\system32 folder.
Maybe this is what you need...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* LogToFile class
* This class is intended to be use with the default logging class of java
* It save the log in an XML file and display a friendly message to the user
* @author Ibrabel <[email protected]>
*/
public class LogToFile {
protected static final Logger logger=Logger.getLogger("MYLOG");
/**
* log Method
* enable to log all exceptions to a file and display user message on demand
* @param ex
* @param level
* @param msg
*/
public static void log(Exception ex, String level, String msg){
FileHandler fh = null;
try {
fh = new FileHandler("log.xml",true);
logger.addHandler(fh);
switch (level) {
case "severe":
logger.log(Level.SEVERE, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Error", JOptionPane.ERROR_MESSAGE);
break;
case "warning":
logger.log(Level.WARNING, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Warning", JOptionPane.WARNING_MESSAGE);
break;
case "info":
logger.log(Level.INFO, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Info", JOptionPane.INFORMATION_MESSAGE);
break;
case "config":
logger.log(Level.CONFIG, msg, ex);
break;
case "fine":
logger.log(Level.FINE, msg, ex);
break;
case "finer":
logger.log(Level.FINER, msg, ex);
break;
case "finest":
logger.log(Level.FINEST, msg, ex);
break;
default:
logger.log(Level.CONFIG, msg, ex);
break;
}
} catch (IOException | SecurityException ex1) {
logger.log(Level.SEVERE, null, ex1);
} finally{
if(fh!=null)fh.close();
}
}
public static void main(String[] args) {
/*
Create simple frame for the example
*/
JFrame myFrame = new JFrame();
myFrame.setTitle("LogToFileExample");
myFrame.setSize(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
JPanel pan = new JPanel();
JButton severe = new JButton("severe");
pan.add(severe);
JButton warning = new JButton("warning");
pan.add(warning);
JButton info = new JButton("info");
pan.add(info);
/*
Create an exception on click to use the LogToFile class
*/
severe.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"severe","You can't divide anything by zero");
}
}
});
warning.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"warning","You can't divide anything by zero");
}
}
});
info.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"info","You can't divide anything by zero");
}
}
});
/*
Add the JPanel to the JFrame and set the JFrame visible
*/
myFrame.setContentPane(pan);
myFrame.setVisible(true);
}
}
Why not use a PdfPTable
object for this?
Create a fixed width table and use a float array to set the widths of the columns
PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);
addCell(table, "SER.\nNO.", 2);
addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);
addCell(table, "DESCRIPTION OF GOODS", 2);
addCell(table, "LINE DOC. RECL DATE", 1);
addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);
addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);
....
private static void addCell(PdfPTable table, string text, int rowspan)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPCell cell = new PdfPCell(new Phrase(text, times));
cell.Rowspan = rowspan;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.AddCell(cell);
}
have a look at this tutorial too...
I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.
function check_ajax_call_count()
{
if ( window.ajax_call_count==window.ajax_calls_completed )
{
// do whatever needs to be done after the last ajax call finished
}
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);
Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).
Auto Refresh Workbook for example every 5 sec. Apply to module
Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub
Apply to Workbook on Open
Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub
:)
Here is a production ready pure JavaScript solution:
<View styles={{backgroundColor: `the main color you want`}}>
<Image source={`A white to transparent gradient png`}>
</View>
Here is the source code of a npm package using this solution: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329
Here is the gradient palette screenshot of saturation and brightness using this npm package: https://github.com/flyskywhy/react-native-slider-color-picker
Using a list comprehension:
from datetime import date, timedelta
d1 = date(2008,8,15)
d2 = date(2008,9,15)
# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
for d in dd:
print d
# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)
setUpBeforeClass is run before any method execution right after the constructor (run only once)
setUp is run before each method execution
tearDown is run after each method execution
tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)
Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range
idea, and resolves some of the issues with that answer such as being able to have the Includes
methods within a generic class by constraining T
as IComparable<T>
. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime
.
public struct Range<T> where T : IComparable<T>
{
public Range(T start, T end)
{
Start = start;
End = end;
}
public T Start { get; }
public T End { get; }
public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;
public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}
If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:
I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.
First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:
//Declaring
public EditText etPesquisa;
public ContasPagarAdapter adapterNormal;
public List<ContasPagar> lstBkp;
public List<ContasPagar> lstCp;
//Within the onCreate method, type the following:
etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);
etPesquisa.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
filter(String.valueOf(cs));
}
@Override
public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable e){
}
});
//Before moving objects to lists first initializes them as below:
lstCp = new ArrayList<ContasPagar>();
lstBkp = new ArrayList<ContasPagar>();
//When you add objects to the main list, repeat the procedure also for bkp list, as follows:
lstCp.add(cp);
lstBkp.add(cp);
//Now initializes the adapter and let the listener, as follows:
adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);
lvContasPagar.setAdapter(adapterNormal);
lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));
//Now create the methods inside actito filter the text entered by the user, as follows:
public void filter(String charText){
charText = charText.toLowerCase();
lstCp.clear();
if (charText.length() == 0){
lstCp.addAll(lstBkp);
appendAddItem(lstBkp);
}
else {
for (int i = 0; i < lstBkp.size(); i++){
if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){
lstCp.add(lstBkp.get(i));
}
}
appendAddItem(lstCp);
}
}
private void appendAddItem(final List<ContasPagar> novaLista){
runOnUiThread(new Runnable(){
@Override
public void run(){
adapterNormal.notifyDataSetChanged();
}
});
}
What about this:
otherfunction(thing_collection, thing)
Rather than expose something so implementation-dependent like a list index in a function interface, pass the collection and the thing and let otherfunction deal with the "test for membership" issues. If otherfunction is written to be collection-type-agnostic, then it would probably start with:
if thing in thing_collection:
... proceed with operation on thing
which will work if thing_collection is a list, tuple, set, or dict.
This is possibly clearer than:
if thing_index != MAGIC_VALUE_INDICATING_NOT_A_MEMBER:
which is the code you already have in otherfunction.
I managed to find network.http.connect.timeout for much older versions of Mozilla:
This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).
Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.
It would seem that network.http.connect.timeout
hasn't done anything for some time.
I also saw references to network.http.request.timeout
, so I did a Google search. The results include lots of links to people recommending that others include it in about:config
in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:
Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.
The same page includes additional information about network.http.connect.timeout
:
Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.
Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
For completeness, using the Guava library, you'd do: Splitter.on(",").split(“dog,cat,fox”)
Another example:
String animals = "dog,cat, bear,elephant , giraffe , zebra ,walrus";
List<String> l = Lists.newArrayList(Splitter.on(",").trimResults().split(animals));
// -> [dog, cat, bear, elephant, giraffe, zebra, walrus]
Splitter.split()
returns an Iterable, so if you need a List, wrap it in Lists.newArrayList()
as above. Otherwise just go with the Iterable, for example:
for (String animal : Splitter.on(",").trimResults().split(animals)) {
// ...
}
Note how trimResults()
handles all your trimming needs without having to tweak regexes for corner cases, as with String.split()
.
If your project uses Guava already, this should be your preferred solution. See Splitter documentation in Guava User Guide or the javadocs for more configuration options.
You can also try following,
long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
You can delete the browser cache by setting these headers:
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
I met this in kubernetes/minikube + nodejs + mongoose environment. The problem was that DNS service was up with a kind of latency. Checking DNS is ready solved my problem.
const dns = require('dns');_x000D_
_x000D_
var dnsTimer = setInterval(() => {_x000D_
dns.lookup('mongo-0.mongo', (err, address, family) => {_x000D_
if (err) {_x000D_
console.log('DNS LOOKUP ERR', err.code ? err.code : err);_x000D_
} else {_x000D_
console.log('DNS LOOKUP: %j family: IPv%s', address, family);_x000D_
clearTimeout(dnsTimer);_x000D_
mongoose.connect(mongoURL, db_options);_x000D_
}_x000D_
});_x000D_
}, 3000);_x000D_
_x000D_
_x000D_
var db = mongoose.connection;_x000D_
var db_options = {_x000D_
autoReconnect:true,_x000D_
_x000D_
poolSize: 20,_x000D_
socketTimeoutMS: 480000,_x000D_
keepAlive: 300000,_x000D_
_x000D_
keepAliveInitialDelay : 300000,_x000D_
connectTimeoutMS: 30000,_x000D_
reconnectTries: Number.MAX_VALUE,_x000D_
reconnectInterval: 1000,_x000D_
useNewUrlParser: true_x000D_
};
_x000D_
(the numbers in db_options are arbitrary found on stackoverflow and similar like sites)