You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:
jQuery('.bookmarkMeLink').click(function() {
if (window.sidebar && window.sidebar.addPanel) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title,window.location.href,'');
}
else if(window.sidebar && jQuery.browser.mozilla){
//for other version of FF add rel="sidebar" to link like this:
//<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
jQuery(this).attr('rel', 'sidebar');
}
else if(window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(location.href,document.title);
} else if(window.opera && window.print) {
// Opera Hotlist
this.title=document.title;
return true;
} else {
// webkit - safari/chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
}
});
You have to target screen size using media query for different screen size.
for iphone:
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio : 2)
{ }
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio : 2)
{ }
and for desktop version:
@media only screen (max-width: 1080){
}
stderr will not do IO Cache buffering so if our application need to print critical message info (some errors ,exceptions) to console or to file use it where as use stdout to print general log info as it use IO Cache buffering there is a chance that before writing our messages to file application may close ,leaving debugging complex
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
There is another case where 'Java Class' don't show, maybe some reserved words exist in the package name, for example:
com.liuyong.package.case
com.liuyong.import.package
It's the same reason as @kuporific 's answer: the package name is invalid.
This worked for me with about 1cm margin
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
html
{
background-color: #FFFFFF;
margin: 0mm; /* this affects the margin on the html before sending to printer */
}
body
{
padding:30px; /* margin you want for the content */
}
Here's a function eachWithIndex
that works with anything iterable.
You could also write a similar function eachWithKey
that works with objets using for...in
.
// example generator (returns an iterator that can only be iterated once)
function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }
// convers an iterable to an array (potential infinite loop)
function eachToArray(iterable) {
const result = []
for (const val of iterable) result.push(val)
return result
}
// yields every value and index of an iterable (array, generator, ...)
function* eachWithIndex(iterable) {
const shared = new Array(2)
shared[1] = 0
for (shared[0] of iterable) {
yield shared
shared[1]++
}
}
console.log('iterate values and indexes from a generator')
for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)
console.log('create an array')
const anArray = eachToArray(eachFromTo(10, 13))
console.log(anArray)
console.log('iterate values and indexes from an array')
for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)
The good thing with generators is that they are lazy and can take another generator's result as an argument.
Well the data src attribute is just used for binding data for example ASP.NET ...
Have you tried this?
ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);
This will change the col_name's type to VARCHAR(65353)
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
Here's the JavaScript rejex for YYYY-MM-DD format
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
As an alternative, Bintray provides free hosting of maven repositories. That's probably a good alternative to Sonatype OSS and Maven Central if you absolutely don't want to rename the groupId. But please, at least make an effort to get your changes integrated upstream or rename and publish to Central. It makes it much easier for others to use your fork.
If only to 0 then you can use memset
:
int* a = new int[6];
memset(a, 0, 6*sizeof(int));
Just to add on top of the other answers. In order to initialize a complex static member, you can do it as follows:
Declare your static member as usual.
// myClass.h
class myClass
{
static complexClass s_complex;
//...
};
Make a small function to initialize your class if it's not trivial to do so. This will be called just the one time the static member is initialized. (Note that the copy constructor of complexClass will be used, so it should be well defined).
//class.cpp
#include myClass.h
complexClass initFunction()
{
complexClass c;
c.add(...);
c.compute(...);
c.sort(...);
// Etc.
return c;
}
complexClass myClass::s_complex = initFunction();
Try this, Examples:
Math.Floor() vs Math.Truncate()
Math.Floor(2.56) = 2
Math.Floor(3.22) = 3
Math.Floor(-2.56) = -3
Math.Floor(-3.26) = -4
Math.Truncate(2.56) = 2
Math.Truncate(2.00) = 2
Math.Truncate(1.20) = 1
Math.Truncate(-3.26) = -3
Math.Truncate(-3.96) = -3
Also Math.Round()
Math.Round(1.6) = 2
Math.Round(-8.56) = -9
Math.Round(8.16) = 8
Math.Round(8.50) = 8
Math.Round(8.51) = 9
math.floor()
Returns the largest integer less than or equal to the specified number. MSDN system.math.floor
math.truncate()
Calculates the integral part of a number. MSDN system.math.truncate
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
The question doesn't specify the origin of x
but it makes sense to defend, if we can, against malicious (or just unexpected, from our own application) input. For example, suppose x
has a value of & <script>alert('hello');</script>
. A safe and simple way to handle this in jQuery is:
var x = "& <script>alert('hello');</script>";
var safe = $('<div />').html(x).text();
// => "& alert('hello');"
Found via https://gist.github.com/jmblog/3222899. I can't see many reasons to avoid using this solution given it is at least as short, if not shorter than some alternatives and provides defence against XSS.
(I originally posted this as a comment, but am adding it as an answer since a subsequent comment in the same thread requested that I do so).
If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case foo.id) and the on update and on delete actions.
I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.
EDIT: Make sure both of the tables have the InnoDB engine selected.
I am a bit late in the game, but I couldn't find what I needed here- or anywhere else - so I wrote something myself.
My requirements for a configuration mechanism are the following:
settings-overrides.js
- which looks the same but allows overrides of configuration at settings.js
. The idea here is to modify configuration easily without changing the code. I find it useful for saas. Even though I care less about supporting environments - the will explain how to add it easily to my solution
var publicConfiguration = {
"title" : "Hello World"
"demoAuthToken" : undefined,
"demoUserId" : undefined,
"errorEmail" : null // if null we will not send emails on errors.
};
var privateConfiguration = {
"port":9040,
"adminAuthToken":undefined,
"adminUserId":undefined
}
var meConf = null;
try{
meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}
var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;
function getPublicConfiguration(){
if (!publicConfigurationInitialized) {
publicConfigurationInitialized = true;
if (meConf != null) {
for (var i in publicConfiguration) {
if (meConf.hasOwnProperty(i)) {
publicConfiguration[i] = meConf[i];
}
}
}
}
return publicConfiguration;
}
function getPrivateConfiguration(){
if ( !privateConfigurationInitialized ) {
privateConfigurationInitialized = true;
var pubConf = getPublicConfiguration();
if ( pubConf != null ){
for ( var j in pubConf ){
privateConfiguration[j] = pubConf[j];
}
}
if ( meConf != null ){
for ( var i in meConf ){
privateConfiguration[i] = meConf[i];
}
}
}
return privateConfiguration;
}
exports.sendPublicConfiguration = function( req, res ){
var name = req.param("name") || "conf";
res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};
var prConf = getPrivateConfiguration();
if ( prConf != null ){
for ( var i in prConf ){
if ( prConf[i] === undefined ){
throw new Error("undefined configuration [" + i + "]");
}
exports[i] = prConf[i];
}
}
return exports;
undefined
means this property is requirednull
means it is optional meConf
- currently the code is target to a file under app
. meConf
is the overrides files which is targeted to conf/dev
- which is ignored by my vcs. publicConfiguration
- will be visible from front-end and back-end. privateConfiguration
- will be visible from back-end only. sendPublicConfiguration
- a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf
.
app.get("/backend/conf", require("conf").sendPublicConfiguration);
Even though I don't find an "environment support" useful, maybe someone will.
To add environment support you need to change the meConf require statement to something like this (pseudocode)
if ( environment == "production" ) { meConf = require("../conf/dev/meConf").production; }
if ( environment == "development" ) { meConf = require("../conf/dev/meConf").development; }
Similarly you can have a file per environment
meConf.development.js
meConf.production.js
and import the right one. The rest of the logic stays the same.
To run a command as root, and pass it the password at the command prompt, you could do it as so:
import subprocess
from getpass import getpass
ls = "sudo -S ls -al".split()
cmd = subprocess.run(
ls, stdout=subprocess.PIPE, input=getpass("password: "), encoding="ascii",
)
print(cmd.stdout)
For your example, probably something like this:
import subprocess
from getpass import getpass
restart_apache = "sudo /usr/sbin/apache2ctl restart".split()
proc = subprocess.run(
restart_apache,
stdout=subprocess.PIPE,
input=getpass("password: "),
encoding="ascii",
)
You can use arg(), as follow:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
You can set the max_fails and fail_timeout directives of nginx to indicate that the nginx should retry the x number of connection requests to the container before failing on the upstream server unavailability.
You can tune these two numbers as per your infrastructure and speed at which the whole setup is coming up. You can read more details about the health checks section of the below URL: http://nginx.org/en/docs/http/load_balancing.html
Following is the excerpt from http://nginx.org/en/docs/http/ngx_http_upstream_module.html#server
max_fails=number
sets the number of unsuccessful attempts to communicate with the server that should happen in the duration set by the fail_timeout parameter to consider the server unavailable for a duration also set by the fail_timeout parameter. By default, the number of unsuccessful attempts is set to 1. The zero value disables the accounting of attempts. What is considered an unsuccessful attempt is defined by the proxy_next_upstream, fastcgi_next_upstream, uwsgi_next_upstream, scgi_next_upstream, and memcached_next_upstream directives.
fail_timeout=time
sets the time during which the specified number of unsuccessful attempts to communicate with the server should happen to consider the server unavailable; and the period of time the server will be considered unavailable. By default, the parameter is set to 10 seconds.
To be precise your modified nginx config file should be as follows (this script is assuming that all the containers are up by 25 seconds at least, if not, please change the fail_timeout or max_fails in below upstream section): Note: I didn't test the script myself, so you could give it a try!
upstream phpupstream {
server waapi_php_1:9000 fail_timeout=5s max_fails=5;
}
server {
listen 80;
root /var/www/test;
error_log /dev/stdout debug;
access_log /dev/stdout;
location / {
# try to serve file directly, fallback to app.php
try_files $uri /index.php$is_args$args;
}
location ~ ^/.+\.php(/|$) {
# Referencing the php service host (Docker)
fastcgi_pass phpupstream;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
# We must reference the document_root of the external server ourselves here.
fastcgi_param SCRIPT_FILENAME /var/www/html/public$fastcgi_script_name;
fastcgi_param HTTPS off;
}
}
Also, as per the following Note from docker (https://github.com/docker/docker.github.io/blob/master/compose/networking.md#update-containers), it is evident that the retry logic for checking the health of the other containers is not docker's responsibility and rather the containers should do the health check themselves.
Updating containers
If you make a configuration change to a service and run docker-compose up to update it, the old container will be removed and the new one will join the network under a different IP address but the same name. Running containers will be able to look up that name and connect to the new address, but the old address will stop working.
If any containers have connections open to the old container, they will be closed. It is a container's responsibility to detect this condition, look up the name again and reconnect.
You can use the parseInt method for no rounding. Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.
var intValue = parseInt(floatValue, 10);
In addition to el.clientHeight
and el.offsetHeight
, when you need the height of the content inside the element (regardless of the height set on the element itself) you can use el.scrollHeight
. more info
This can be useful if you want to set the element height or max-height to the exact height of it's internal dynamic content. For example:
var el = document.getElementById('myDiv')
el.style.maxHeight = el.scrollHeight+'px'
I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored
try
{
Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
ErrorReport.StoreError("CartMinifiedPartial-Company", e);
-- storing the error for reference
}
Storing
public static void StoreError(string ErrorPage, Exception e)
{
try
{
eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
Err.ErrorPage = ErrorPage;
if (e.Message != null)
{
Err.ErrorDetails = e.Message;
}
if (e.InnerException != null)
{
Err.InnerException = e.InnerException.Message.ToString();
}
Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
DB.ErrorTables.AddObject(Err);
DB.SaveChanges();
}
This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.
First you need a Singleton class in, let's say, "./utils/Singleton.ts":
module utils {
export class Singleton {
private _initialized: boolean;
private _setSingleton(): void {
if (this._initialized) throw Error('Singleton is already initialized.');
this._initialized = true;
}
get setSingleton() { return this._setSingleton; }
}
}
Now imagine you need a Router singleton "./navigation/Router.ts":
/// <reference path="../utils/Singleton.ts" />
module navigation {
class RouterClass extends utils.Singleton {
// NOTICE RouterClass extends from utils.Singleton
// and that it isn't exportable.
private _init(): void {
// This method will be your "construtor" now,
// to avoid double initialization, don't forget
// the parent class setSingleton method!.
this.setSingleton();
// Initialization stuff.
}
// Expose _init method.
get init { return this.init; }
}
// THIS IS IT!! Export a new RouterClass, that no
// one can instantiate ever again!.
export var Router: RouterClass = new RouterClass();
}
Nice!, now initialize or import wherever you need:
/// <reference path="./navigation/Router.ts" />
import router = navigation.Router;
router.init();
router.init(); // Throws error!.
The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.
I've have the same problem like this, but using my own server. Maybe APACHE is allowing only limited connection to the same server. I'm increasing the max_connection and KeepAlive setting. So far so good.
interface
with a Singleton class, but a class's static methods (or e.g. a C# static class
) cannot.Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:
exestub.sh:
#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
case $1 in
-Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
-D*) JAVA_OPT="$JAVA_OPT $1" ;;
*) PROG_OPT="$PROG_OPT $1" ;;
esac
shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT
Then you create your runnable file from your jar:
$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable
It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>
, as <myexe>
is a valid zip/jar file.
I am not experienced with Eclipse or Maven so the other answers seemed a bit over complicated.
The following simpler set of steps worked for me:
Prerequisite: Make sure you have Maven plugin installed in your Eclipse IDE: How to add Maven plugin to Eclipse
pom.xml
file)2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
Actually, it is quite easy to write sufficiently clean and compact code with DI (I wonder, will it be/stay pythonic then, but anyway :) ), for example I actually perefer this way of coding:
def polite(name_str):
return "dear " + name_str
def rude(name_str):
return name_str + ", you, moron"
def greet(name_str, call=polite):
print "Hello, " + call(name_str) + "!"
_
>>greet("Peter")
Hello, dear Peter!
>>greet("Jack", rude)
Hello, Jack, you, moron!
Yes, this can be viewed as just a simple form of parameterizing functions/classes, but it does its work. So, maybe Python's default-included batteries are enough here too.
P.S. I have also posted a larger example of this naive approach at Dynamically evaluating simple boolean logic in Python.
Swift 4.0
string.capitalized(with: nil)
or
string.capitalized
However this capitalizes first letter of every word
Apple's documentation:
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators. Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings. See the getLineStart(_:end:contentsEnd:for:) method for additional information.
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.
Incredibly old question, but bearing in mind that the OP said he does not want to use Do While
and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop
:
This never runs anything if the status is already at "Fail"...
While (i < 20 And Not bShouldStop)
If (Status = "Fail") Then
bShouldStop = True
Else
i = i + 1
'
' Do Something
'
End If
Wend
Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.
While (i < 20 And Not bShouldStop)
i = i + 1
'
' Do Something
'
If (Status = "Fail") Then
bShouldStop = True
End If
Wend
Ultimately, if the variable Status
is being modified inside the While
(and assuming you don't need i
outside the while, it makes no difference really, but just wanted to present multiple options...
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
If you get this error while compiling in Microsoft Mobile Center
? Code signing is required for product type 'Application' in SDK 'iOS 10.3'
** ARCHIVE FAILED **
be aware that Mobile center doesn't yet support automatic signing with certificates of type app-store, ad-hoc and enterprise. Automatic signing only works with development certificates.
There are two things you can do to work around that limitation:
Use a development certificate. You'll have to create a new one in the developer.apple.com portal, download it to your machine, export it to a .p12 file using keychain, then finally provide it to Mobile Center. You know the drill.
Disable automatic signing. You will find that setting in Xcode in your project targets. Once disabled, a little "i" button will be displayed next to the "Xcode managed profile" label. Click that button, some info about the profile will be displayed. On the top left corner of that window, a "PROV" icon is displayed. That is the provisioning profile that you should provide to Mobile Center. Drag and drop the icon into the corresponding field in Mobile Center.
Use a concrete list type, e.g. ArrayList
instead of just List
.
Floating div's will help what your trying to achieve.
HTML
<div class="container">
<div class="content1 content">
</div>
<div class="content2 content">
</div>
</div>
CSS
.container{
width:100%;
height:200px;
background-color:grey;
}
.content{
float:left;
height:30px;
}
.content1{
background-color:blue;
width:300px;
}
.content2{
width:200px;
background-color:green;
}
Zoom in the page to see the effects.
Hope it helps.
This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row
<div class="row" >
<div class="span9">
<%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>
</div>
</div>
For float you could use this:
def format_float(num):
return ('%i' if num == int(num) else '%s') % num
Test it:
>>> format_float(1.00000)
'1'
>>> format_float(1.1234567890000000000)
'1.123456789'
For Decimal see solution here: https://stackoverflow.com/a/42668598/5917543
okkk you have take id INTEGER PRIMARY KEY AUTOINCREMENT and still u r passing value... that is the problem :) for more detail see this still getting problem then post code and logcat
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply
, so in this case you need:
$.when.apply($, my_array).then( ___ );
See http://jsfiddle.net/YNGcm/21/
In ES6, you can use the ...
spread operator instead:
$.when(...my_array).then( ___ );
In either case, since it's unlikely that you'll known in advance how many formal parameters the .then
handler will require, that handler would need to process the arguments
array in order to retrieve the result of each promise.
How to Find a Stored Procedure Containing Text or String
Many time we need to find the text or string in the stored procedure. Here is the query to find the containing text.
SELECT OBJECT_NAME(id)
FROM SYSCOMMENTS
WHERE [text] LIKE '%Text%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
For more information please check the given URL given below.
http://www.freshcodehub.com/Article/34/how-to-find-a-stored-procedure-containing-text-or-string
select max(Salary) from Employee
where Salary
not in (Select top4 salary from Employee);
because answer is as follows
max(5,6,7,8)
so 5th highest record will be displayed, first four will not be considered
On Windows there is an experimental build that does this, as described on the mailing list, Filter by local process name
Try something like this it will help you
$("#from").click(function () {
$('#from').attr('readonly', true);
});
Thanks
The data in COL1 is in dd-mon-yy
No it's not. A DATE
column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.
If COL1 is really a DATE
column using to_date()
on it is useless because to_date()
converts a string to a DATE.
You only need to_char(), nothing else:
SELECT TO_CHAR(col1, 'mm/dd/yyyy')
FROM TABLE1
What happens in your case is that calling to_date()
converts the DATE
into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.
Edit
So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.
The best (and to be honest: only sensible) solution is to convert that column to a DATE
. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.
But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR
instead of YY
:
SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1
should do the trick. Note that I also changed mon
to mm
as your example is 27-11-89
which has a number for the month, not an "word" (like NOV)
For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215
For those who have this problem with collection of enums here is how to solve it:
@Enumerated(EnumType.STRING)
@Column(name = "OPTION")
@CollectionTable(name = "MY_ENTITY_MY_OPTION")
@ElementCollection(targetClass = MyOptionEnum.class, fetch = EAGER)
Collection<MyOptionEnum> options;
To create your custom log file, try this code
Mage::log('your debug message', null, 'yourlog_filename.log');
Refer this Answer
Just use this script to dynamically backup all databases on the server. Then create batch file according to the article. It is usefull to create two batch files, one for full backup a and one for diff backup. Then Create two tasks in Task Scheduler, one for full and one for diff.
-- // Copyright © Microsoft Corporation. All Rights Reserved.
-- // This code released under the terms of the
-- // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
@databaseName sysname = null,
@backupType CHAR(1),
@backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE @DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from @DBs
INSERT INTO @DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=@DatabaseName
OR @DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF @backupType='F'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF @backupType='D'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF @backupType='L'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE @BackupName varchar(100)
DECLARE @BackupFile varchar(100)
DECLARE @DBNAME varchar(300)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @dateTime NVARCHAR(20)
DECLARE @Loop int
-- Loop through the databases one by one
SELECT @Loop = min(ID) FROM @DBs
WHILE @Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF @backupType = 'F'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'D'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'L'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF @backupType = 'F'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
IF @backupType = 'D'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
IF @backupType = 'L'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
IF @backupType = 'F'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'D'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'L'
BEGIN
SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END
And batch file can look like this:
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='F'" >> c:\Dropbox\backup\DB\full.log 2>&1
and
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='D'" >> c:\Dropbox\backup\DB\diff.log 2>&1
The advantage of this method is that you don't need to change anything if you add new database or delete a database, you don't even need to list the databases in the script. Answer from JohnB is better/simpler for server with one database, this approach is more suitable for multi database servers.
The negated set of everything that is not alphanumeric & underscore for ASCII chars:
/[^\W]/g
For email or username validation i've used the following expression that allows 4 standard special characters - _ . @
/^[-.@_a-z0-9]+$/gi
For a strict alphanumeric only expression use:
/^[a-z0-9]+$/gi
Test @ RegExr.com
Without jQuery:
var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;
Or:
function hasClass(e,c){
return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');
This is WAY faster than jQuery!
I'd like to contribute another option to solve this issue; since the solutions proposed above did not solve my scenario.
(function()
{
// Initialize the previous-attribute
var selects = $('select');
selects.data('previous', selects.val());
// Listen on the body for changes to selects
$('body').on('change', 'select',
function()
{
$(this).data('previous', $(this).val());
}
);
}
)();
This does use jQuery so that def. is a dependency here, but this can be adapted to work in pure javascript. (Add a listener to the body, check if the original target was a select, execute function, ...).
By attaching the change listener to the body, you can pretty much be sure this will fire after specific listeners for the selects, otherwise the value of 'data-previous' will be overwritten before you can even read it.
This is of course assuming that you prefer to use separate listeners for your set-previous and check-value. It fits right in with the single-responsibility pattern.
Note: This adds this 'previous' functionality to all selects, so be sure to fine-tune the selectors if needed.
If someone is interested, it is also possible to create an event source manually by adding some registry values.
Save the following lines as a .reg file, then import it to registry by double clicking it:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\YOUR_EVENT_SOURCE_NAME_GOES_HERE]
"EventMessageFile"="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\EventLogMessages.dll"
"TypesSupported"=dword:00000007
This creates an event source named YOUR_EVENT_SOURCE_NAME_GOES_HERE
.
for installing multiple packages, i am using a setup.py file with following code:
import sys
import subprocess
import pkg_resources
required = {'numpy','pandas','<etc>'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])
I've created a fiddle using your screenshot as a background image and stripping out the extra mark-up, and it seems to work fine
http://jsfiddle.net/fLdQG/2/ (webkit browser required)
Does this work for you? If not, can you update the fiddle with your exact mark-up and CSS?
This can help you
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
You can use Regular Expression for Sanitization. Inside filter before calling chain.doFilter(request, response) method, call this code. Here is Sample Code:
for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
for(int i=0; i < n; i++) {
values[i] = values[i].replaceAll("[^\\dA-Za-z ]","").replaceAll("\\s+","+").trim();
}
}
Here is one that will accept both phone numbers and phone numbers with extensions.
function phoneNumber(tel) {
var toString = String(tel),
phoneNumber = toString.replace(/[^0-9]/g, ""),
countArrayStr = phoneNumber.split(""),
numberVar = countArrayStr.length,
closeStr = countArrayStr.join("");
if (numberVar == 10) {
var phone = closeStr.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"); // Change number symbols here for numbers 10 digits in length. Just change the periods to what ever is needed.
} else if (numberVar > 10) {
var howMany = closeStr.length,
subtract = (10 - howMany),
phoneBeginning = closeStr.slice(0, subtract),
phoneExtention = closeStr.slice(subtract),
disX = "x", // Change the extension symbol here
phoneBeginningReplace = phoneBeginning.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"), // Change number symbols here for numbers greater than 10 digits in length. Just change the periods and to what ever is needed.
array = [phoneBeginningReplace, disX, phoneExtention],
afterarray = array.splice(1, 0, " "),
phone = array.join("");
} else {
var phone = "invalid number US number";
}
return phone;
}
phoneNumber("1234567891"); // Your phone number here
It's very simple try integrate these lines of code first take permission in the Android Manifest file
<uses-permission android:name="android.permission.INTERNET" />
then write some code in you Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.MainActivity">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/help_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Then write these code in your MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity{
private WebView mWebview ;
String link = "";// global variable
Resources res;// global variable
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_modernherbal_main);
mWebview = (WebView) findViewById(R.id.help_webview);
WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://www.example.com");
}
}
Try this it'll help you to solve your problem
Update on the answer December 2019 Xcode 11.1.2
Apple has moved Network Link Conditioner Tool to additional tools for Xcode
Go to the below link
https://developer.apple.com/download/more/?q=Additional%20Tools
Install the dmg file, select hardware from installer
JSONObject jsonResult = new JSONObject();
try {
jsonResult.put("clave", "valor");
jsonResult.put("username", "iesous");
jsonResult.put("password", "1234");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("DEV","jsonResult->"+jsonResult);
If the number of the set would be within 32, 64 or a machine native primitive size, then you can do it with a simple bit manipulation.
template<typename T>
void combo(const T& c, int k)
{
int n = c.size();
int combo = (1 << k) - 1; // k bit sets
while (combo < 1<<n) {
pretty_print(c, combo);
int x = combo & -combo;
int y = combo + x;
int z = (combo & ~y);
combo = z / x;
combo >>= 1;
combo |= y;
}
}
this example calls pretty_print() function by the dictionary order.
For example. You want to have 6C3 and assuming the current 'combo' is 010110. Obviously the next combo MUST be 011001. 011001 is : 010000 | 001000 | 000001
010000 : deleted continuously 1s of LSB side. 001000 : set 1 on the next of continuously 1s of LSB side. 000001 : shifted continuously 1s of LSB to the right and remove LSB bit.
int x = combo & -combo;
this obtains the lowest 1.
int y = combo + x;
this eliminates continuously 1s of LSB side and set 1 on the next of it (in the above case, 010000 | 001000)
int z = (combo & ~y)
this gives you the continuously 1s of LSB side (000110).
combo = z / x;
combo >> =1;
this is for 'shifted continuously 1s of LSB to the right and remove LSB bit'.
So the final job is to OR y to the above.
combo |= y;
Some simple concrete example :
#include <bits/stdc++.h>
using namespace std;
template<typename T>
void pretty_print(const T& c, int combo)
{
int n = c.size();
for (int i = 0; i < n; ++i) {
if ((combo >> i) & 1)
cout << c[i] << ' ';
}
cout << endl;
}
template<typename T>
void combo(const T& c, int k)
{
int n = c.size();
int combo = (1 << k) - 1; // k bit sets
while (combo < 1<<n) {
pretty_print(c, combo);
int x = combo & -combo;
int y = combo + x;
int z = (combo & ~y);
combo = z / x;
combo >>= 1;
combo |= y;
}
}
int main()
{
vector<char> c0 = {'1', '2', '3', '4', '5'};
combo(c0, 3);
vector<char> c1 = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
combo(c1, 4);
return 0;
}
result :
1 2 3
1 2 4
1 3 4
2 3 4
1 2 5
1 3 5
2 3 5
1 4 5
2 4 5
3 4 5
a b c d
a b c e
a b d e
a c d e
b c d e
a b c f
a b d f
a c d f
b c d f
a b e f
a c e f
b c e f
a d e f
b d e f
c d e f
a b c g
a b d g
a c d g
b c d g
a b e g
a c e g
b c e g
a d e g
b d e g
c d e g
a b f g
a c f g
b c f g
a d f g
b d f g
c d f g
a e f g
b e f g
c e f g
d e f g
One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal "Hello" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.
The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.
angular.module('app')
.directive('my-slider',
['$timeout', function($timeout) {
return {
restrict:'E',
scope: true,
template: '<div id="{{ id }}"></div>',
link: function($scope) {
$scope.id = String(Math.random()).substr(2, 8);
$timeout(function() {
angular.element('#'+$scope.id).slider();
});
}
};
}]
);
You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>
:
<InstallExecuteSequence>
...
<Custom Action="FileCleaner" After='InstallFinalize'>
Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
Then you will also have to define your Action under <Product>
:
<Product>
...
<CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE'
ExeCommand='' Return='asyncNoWait' />
Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>
:
<Product>
...
<Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />
The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE
condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.
On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.
I had the same issue and took a whole day to figure out the problem. This error message by Facebook SDK is very vague. I had this problem due to openURL: method being overwritten in MyApplication. I removed the overwritten method and facebook login worked fine.
if you want the object on the stack, try this:
MyClass myclass;
myclass.DoSomething();
If you need a pointer to that object:
MyClass* myclassptr = &myclass;
myclassptr->DoSomething();
well looking for a simpler variation I found this:
it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.
demo and credit => http://codepen.io/Ahrengot/pen/bKdLC
@keyframes fadeIn { _x000D_
from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
jQuery now supports .data();
, so if you have
<div id='author' data-content='stuff!'>
use
var author = $('#author').data("content"); // author = 'stuff!'
At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:
sed -i '' -e's/[[:space:]]*$//' "$1"
A less verbose approach:
int number = [dict[@"integer"] intValue];
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
First, thanks to William.
Second - i needed a dynamic version. And it works!
An example:
CSS:
p[id^="detailView-"]
{
display: none;
}
p[id^="detailView-"]:target
{
display: block;
}
HTML:
<a href="#detailView-1">Show View1</a>
<p id="detailView-1">View1</p>
<a href="#detailView-2">Show View2</a>
<p id="detailView-2">View2</p>
If you're using jQuery 1.5, then statusCode
will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
You should see the status code from the first alert.
Cloud: is simply an aggregate of computing power. You can think of the entire "cloud" as single server, for your purposes. It's conceptually much like an old school mainframe where you could submit your jobs to and have it return the result, except that nowadays the concept is applied more widely. (I.e. not just raw computing, also entire services, or storage ...)
Grid: a grid is simply many computers which together might solve a given problem/crunch data. The fundamental difference between a grid and a cluster is that in a grid each node is relatively independent of others; problems are solved in a divide and conquer fashion.
Cluster: conceptually it is essentially smashing up many machines to make a really big & powerful one. This is a much more difficult architecture than cloud or grid to get right because you have to orchestrate all nodes to work together, and provide consistency of things such as cache, memory, and not to mention clocks. Of course clouds have much the same problem, but unlike clusters clouds are not conceptually one big machine, so the entire architecture doesn't have to treat it as such. You can for instance not allocate the full capacity of your data center to a single request, whereas that is kind of the point of a cluster: to be able to throw 100% of the oomph at a single problem.
Those errors :
"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"
means you haven't installed mingw32-base.
Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files
and then make sure you select "mingw32-base"
Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"
After that open CMake and Select Installation --> Delete Cache.
And click configure button again. I solved the problem this way, hope you solve the problem.
A couple of years ago, location
did not work for me in IE and location.href
did (and both worked in other browsers). Since then I have always just used location.href
and never had trouble again. I can't remember which version of IE that was.
You could also use stringstream.
I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).
Enterprise Architect will build a UML diagram from imported source code.
In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.
Type ILP64 LP64 LLP64
char 8 8 8
short 16 16 16
int 64 32 32
long 64 64 32
long long 64 64 64
pointer 64 64 64
The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.
Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.
If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h>
header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):
int8_t
- 8-bit integersint16_t
- 16-bit integersint32_t
- 32-bit integersint64_t
- 64-bit integersuintptr_t
- unsigned integers big enough to hold pointersintmax_t
- biggest size of integer on the platform (might be larger than int64_t
)You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t
type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t
values (ptrdiff_t
).
But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.
You can also try this:
Python 2.x:
python -c "import sys; print '\n'.join(sys.path)"
Python 3.x:
python3 -c "import sys; print('\n'.join(sys.path))"
The output will be more readable and clean, like so:
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /Library/Python/2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
Compile python source file to code object
char * filename = "xxx.py";
char * source = read_file( filename );
PyObject *co = Py_CompileString( source, filename, Py_file_input );
Iterate code object, wrap bytecode of each code object as the following format
0 JUMP_ABSOLUTE n = 3 + len(bytecode)
3
...
... Here it's obfuscated bytecode
...
n LOAD_GLOBAL ? (__armor__)
n+3 CALL_FUNCTION 0
n+6 POP_TOP
n+7 JUMP_ABSOLUTE 0
Serialize code object and obfuscate it
char *original_code = marshal.dumps( co );
char *obfuscated_code = obfuscate_algorithm( original_code );
Create wrapper script "xxx.py", ${obfuscated_code} stands for string constant generated in previous step.
__pyarmor__(__name__, b'${obfuscated_code}')
When import or run this wrapper script, the first statement is to call a CFunction:
int __pyarmor__(char *name, unsigned char *obfuscated_code)
{
char *original_code = resotre_obfuscated_code( obfuscated_code );
PyObject *co = marshal.loads( original_code );
PyObject *mod = PyImport_ExecCodeModule( name, co );
}
This function accepts 2 parameters: module name and obfuscated code, then
After module imported, when any code object in this module is called first time, from the wrapped bytecode descripted in above section, we know
First op JUMP_ABSOLUTE
jumps to offset n
At offset n, the instruction is to call a PyCFunction. This function will restore those obfuscated bytecode between offset 3 and n, and place the original bytecode at offset 0
After function call, the last instruction jumps back to offset 0. The real bytecode is now executed
Refer to Pyarmor
Do a while True
inside your for loop, put your try
code inside, and break from that while
loop only when your code succeeds.
for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break
Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
Depending on how it will be used, you can either do this with two maps Map<K1, V>
and Map<K2, V>
or with two maps Map<K1, V>
and Map<K2, K1>
. If one of the keys is more permanent than the other, the second option may make more sense.
Using dblink would be more convenient!
truncate table tableA;
insert into tableA
select *
from dblink('hostaddr=xxx.xxx.xxx.xxx dbname=mydb user=postgres',
'select a,b from tableA')
as t1(a text,b text);
You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.
# List Java versions installed
/usr/libexec/java_home -V
# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)
# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)
You can set the default value in the .bashrc, .profile, or .zprofile
You can also use this option
#include <conio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
.
.
.
getch();
return 0;
}
Short story: links. Make use of something like:
a[href='red'] {
color: red;
pointer-events: none;
cursor: default;
text-decoration: none;
}
_x000D_
<a href="red">Look, ma! Red!</a>
_x000D_
(HTML above for demonstration purposes)
And in your md source:
[Look, ma! Red!](red)
If you don't want to add an extra extension the following code should work with jQuery.
$('a[href=#target]').
click(function(){
var target = $('a[name=target]');
if (target.length)
{
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 1000);
return false;
}
});
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
I think you missed this step:
source ~/.nvm/nvm.sh
You can run this command on the bash OR you can put it in the file /.bashrc or ~/.profile or ~/.zshrc to automatically load it
Download "javamail1_4_5.zip" file from http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.5-oth-JPR
Extract zip file and put the relevant jar file ("mail.jar") in the classpath
Now I'm using this:
Dialoglar.Confirm = function (_title, _question, callback_OK) {
var confirmArguments = arguments;
bootbox.dialog({
title: "<b>" + _title + "</b>",
message: _question,
buttons: {
success: {
label: "OK",
className: "btn-success",
callback: function () {
if (typeof(callback_OK) == "function") { callback_OK.apply(this,Array.prototype.slice.call(confirmArguments, 3));
}
}
},
danger: {
label: "Cancel",
className: "btn-danger",
callback: function () {
$(this).hide();
}
}
}
});
};
use app.render
in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.
You can use either [[
or ((
keyword. When you use [[
keyword, you have to use string operators such as -eq
, -lt
. I think, ((
is most preferred for arithmetic, because you can directly use operators such as ==
, <
and >
.
Using [[
operator
a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
echo "Error"
else
echo "No Error"
fi
Using ((
operator
a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
echo "Error"
else
echo "No Error"
fi
Do not use -a
or -o
operators Since it is not Portable.
Easy install for ubuntu:
Just run:
sudo apt-get install php5-pgsql
then
sudo service apache2 restart //restart apache
or
Uncomment the following in php.ini by removing the ;
;extension=php_pgsql.dll
then restart apache
Well the correct answer for the default Json formater based on Json.net is to set ReferenceLoopHandling
to Ignore
.
Just add this to the Application_Start
in Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
This is the correct way. It will ignore the reference pointing back to the object.
Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.
Using the JsonIgnore
attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.
I believe VirtualBox is throwing this error for a number of reasons. Very annoying that it's one error for so many things but, I guess it's the same requirement it's just that the root cause is different.
Potential gotchas:
So for my little mess around machine that I'm resurrecting that has 8GB RAM but only a ye-olde Core i3, I'm having success if I install: 32 bit version of linux, allocating 2.5GB RAM.
Oh, and wherever I say "VT-x" above, that obviously applies equally to AMD's "AMD-V" virtualization tech.
I hope that helps.
Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.
It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 3 ways to do this today:
When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.
Your new class:
public class TimeWatch {
long starts;
public static TimeWatch start() {
return new TimeWatch();
}
private TimeWatch() {
reset();
}
public TimeWatch reset() {
starts = System.currentTimeMillis();
return this;
}
public long time() {
long ends = System.currentTimeMillis();
return ends - starts;
}
public long time(TimeUnit unit) {
return unit.convert(time(), TimeUnit.MILLISECONDS);
}
}
Usage:
TimeWatch watch = TimeWatch.start();
// do something
long passedTimeInMs = watch.time();
long passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
Afterwards, the time passed can be converted to whatever format you like, with a calender for example
Greetz, GHad
This is probably because of the column() and row() functions. I am not sure how they are applied in conditional formatting. Try creating a new column with the value from this formula and then use it for your formatting needs.
I tried all the solutions listed and none of them worked. I ended up having to do a sp_detach_db, then deleting the ldf file and re-attaching the database forcing it to create a new ldf file. That worked.
While you unfortunately cannot convert an existing member function pointer to a plain function pointer, you can create an adapter function template in a fairly straightforward way that wraps a member function pointer known at compile-time in a normal function like this:
template <class Type>
struct member_function;
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...)>
{
template <Ret(Type::*Func)(Args...)>
static Ret adapter(Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...) const>
{
template <Ret(Type::*Func)(Args...) const>
static Ret adapter(const Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
int (*func)(A&) = &member_function<decltype(&A::f)>::adapter<&A::f>;
Note that in order to call the member function, an instance of A
must be provided.
I had this problem too but the cause was different. I'm using VS2017 with F# 4.0.
Firstly, the console in Visual Studio does not give you enough details why the tests could not be found; it will just fail to the load the DLL with the tests. So use NUnit3console.exe on the command line as this gives you more details.
In my case, it was because the test adapter was looking for a newer version of the F# Core DLL (4.4.1.0) (F# 4.1) whereas I'm still using 4.4.0.0 (F# 4.0). So I just added this to the app.config of the test project:-
<dependentAssembly>
<assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="4.4.0.0" />
</dependentAssembly>
i.e. redirect to the earlier F# core.
Answers here seem outdated. Pandas now has a factorize()
function and you can create categories as:
df.col.factorize()
Function signature:
pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
Coming here from first Google hit:
You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1
.
On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1
the warning will go away.
It's probably because you are building a gem from source and the gemspec shells out to git
, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git
but addressing that is for another day :)
My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");
The first parameter is the path. The second is the search pattern you want to use.
Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:
>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0 0.41
1 0.99
2 0.10
or
>>> pd.set_option('display.float_format', '{:.2f}'.format)
Ugh- nothing worked for me! I have a CentOS 7.4 machine running mariadb 5.5.64.
What I had to do was this, right after installation of mariadb from yum;
# systemctl restart mariadb
# mysql_secure_installation
The mysql_secure_installation
will take you through a number of steps, including "Set root password? [Y/n]". Just say "y" and give it a password. Answer the other questions as you wish.
Then you can get in with your password, using
# mysql -u root -p
It will survive
# systemctl restart mariadb
The Key
Then, I checked the /bin/mysql_secure_installation
source code to find out how it was magically able to change the root password and none of the other answers here could. The import bit is:
do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"
...It says SET Password=...
and not SET authentication_string = PASSWORD...
. So, the proper procedure for this version (5.5.64) is:
login using mysql -u root -p , using the password you already set.
Or, stop the database and start it with:
mysql_safe --skip-grant-tables --skip-networking &
From the mysql> prompt:
use mysql;
select host,user,password from user where user = 'root';
(observe your existing passwords for root).
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root' AND host = 'localhost';
select host,user,password from user where user = 'root';
flush privileges;
quit;
kill the running mysqld_safe. restart mariadb. Login as root: mysql -u -p
. Use your new password.
If you want, you can set all the root passwords at once. I think this is wise:
mysql -u root -p
(login)
use mysql;
select host,user,password from user where user = 'root';
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root';
select host,user,password from user where user = 'root';
flush privileges;
quit;
This will perform updates on all the root passwords: ie, for "localhost", "127.0.0.1", and "::1"
In the future, when I go to RHEL8 or what have you, I will try to remember to check the /bin/mysql_secure_installation and see how the guys did it, who were the ones that configured mariadb for this OS.
like Paul said, use
conda create --prefix=/users/.../yourEnvName python=x.x
if you are located in the folder in which you want to create your virtual environment, just omit the path and use
conda create --prefix=yourEnvName python=x.x
conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with
source activate yourEnvName
While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment
$twig->registerUndefinedFunctionCallback(function ($name) {
// security
$allowed = false;
switch ($name) {
// example of calling a wordpress function
case 'get_admin_page_title':
$allowed = true;
break;
}
if ($allowed && function_exists($name)) {
return new Twig_Function_Function($name);
}
return false;
});
This is from the Twig recipe page
Haven't tried calling a function on an object as the original question requested
In 8.0+ it looks like this was moved into the project. If you open your project and go to the gear icon on the right, then "Edit Project" you can set the default branch for the project.
function removeHash () {
history.pushState("", document.title, window.location.pathname
+ window.location.search);
}
App.$router.replace({name:"my-route", hash: '#update'})
App.$router.replace({name:"my-route", hash: ' ', params: {a: 100} })
setTimeout(removeHash, 0)
Notes:
#
must have some value after it.setTimeout
, not $nextTick
to keep the url clean.I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo
HTML:
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
<i class="far fa-square"></i>
</button>
</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>$320,800</td>
</tr>
<tr>
<td></td>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>$170,750</td>
</tr>
<tr>
<td></td>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>$86,000</td>
</tr>
<tr>
<td></td>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>$433,060</td>
</tr>
<tr>
<td></td>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>$162,700</td>
</tr>
<tr>
<td></td>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>$372,000</td>
</tr>
<tr>
<td></td>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>$137,500</td>
</tr>
<tr>
<td></td>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>$327,900</td>
</tr>
<tr>
<td></td>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>$205,500</td>
</tr>
<tr>
<td></td>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>$103,600</td>
</tr>
<tr>
<td></td>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>$90,560</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
Javascript:
$(document).ready(function() {
let myTable = $('#example').DataTable({
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0,
}],
select: {
style: 'os', // 'single', 'multi', 'os', 'multi+shift'
selector: 'td:first-child',
},
order: [
[1, 'asc'],
],
});
$('#MyTableCheckAllButton').click(function() {
if (myTable.rows({
selected: true
}).count() > 0) {
myTable.rows().deselect();
return;
}
myTable.rows().select();
});
myTable.on('select deselect', function(e, dt, type, indexes) {
if (type === 'row') {
// We may use dt instead of myTable to have the freshest data.
if (dt.rows().count() === dt.rows({
selected: true
}).count()) {
// Deselect all items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
return;
}
if (dt.rows({
selected: true
}).count() === 0) {
// Select all items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-square');
return;
}
// Deselect some items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
}
});
});
The term "forward declaration" in C++ is mostly only used for class declarations. See (the end of) this answer for why a "forward declaration" of a class really is just a simple class declaration with a fancy name.
In other words, the "forward" just adds ballast to the term, as any declaration can be seen as being forward in so far as it declares some identifier before it is used.
(As to what is a declaration as opposed to a definition, again see What is the difference between a definition and a declaration?)
You're all doing too much work:
right(str(100+@x),2)
-- for a function, same idea:
--
create function zeroPad( @yourNum int, @wid int)
as
begin
return right( 1000000+@yourNum), @wid)
end
Some modern browsers have support for parsing JSON into a native object:
var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);
For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.
For .NET Core, add System.Configuration.ConfigurationManager from NuGet manager.
And read appSetting from App.config
<appSettings>
<add key="appSetting1" value="1000" />
</appSettings>
Add System.Configuration.ConfigurationManager from NuGet Manager
ConfigurationManager.AppSettings.Get("appSetting1")
There's a difference between the header and body of a HTTP response. PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code. Why do you want to do this?
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
After lots of searching This code work for me:
Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?
if(isReadStorageAllowed()){
//If permission is already having then showing the toast
//Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
//Existing the method with return
return;
}else{
requestStoragePermission();
}
private boolean isReadStorageAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
//Requesting permission
private void requestStoragePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}
Implement Override onRequestPermissionsResult method for checking is the user allow or denie
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == REQUEST_WRITE_STORAGE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
}
}
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
I know this question is pretty old, but figured I'd share some demo code this question helped me with.
Button
and a DataGridView
Click
event for button1CellClick
event for DataGridView1EditMode
to EditProgrammatically
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable m_dataTable;
DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }
private const string m_nameCol = "Name";
private const string m_choiceCol = "Choice";
public Form1()
{
InitializeComponent();
}
class Options
{
public int m_Index { get; set; }
public string m_Text { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
table = new DataTable();
table.Columns.Add(m_nameCol);
table.Rows.Add(new object[] { "Foo" });
table.Rows.Add(new object[] { "Bob" });
table.Rows.Add(new object[] { "Timn" });
table.Rows.Add(new object[] { "Fred" });
dataGridView1.DataSource = table;
if (!dataGridView1.Columns.Contains(m_choiceCol))
{
DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
txtCol.Name = m_choiceCol;
dataGridView1.Columns.Add(txtCol);
}
List<Options> oList = new List<Options>();
oList.Add(new Options() { m_Index = 0, m_Text = "None" });
for (int i = 1; i < 10; i++)
{
oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
{
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
//Setup A
c.DataSource = oList;
c.Value = oList[0].m_Text;
c.ValueMember = "m_Text";
c.DisplayMember = "m_Text";
c.ValueType = typeof(string);
////Setup B
//c.DataSource = oList;
//c.Value = 0;
//c.ValueMember = "m_Index";
//c.DisplayMember = "m_Text";
//c.ValueType = typeof(int);
//Result is the same A or B
dataGridView1[m_choiceCol, i] = c;
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
{
DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
dataGridView1.CurrentCell = cell;
dataGridView1.BeginEdit(true);
}
}
}
}
}
Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.
See this bug: https://bugs.launchpad.net/ubuntu/+source/mysql-5.6/+bug/1435823
There seems to be a temporary fix there
Create a newfile /etc/tmpfiles.d/mysql.conf:
# systemd tmpfile settings for mysql
# See tmpfiles.d(5) for details
d /var/run/mysqld 0755 mysql mysql -
After reboot, mysql should start normally.
Recent Versions
Window -> Restore Default Layout
(Thanks to Seven4X's answer)
Older Versions
You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config
while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.
It depends on the OS:
While this doesn't necessarily check if a key exists, it does check for the truthiness of a value. Which undefined
and null
fall under.
Boolean(obj.foo)
This solution works best for me because I use typescript, and using strings like so 'foo' in obj
or obj.hasOwnProperty('foo')
to check whether a key exists or not does not provide me with intellisense.
Here's the code I came up with to remove items selected by a user from a listbox It seems to work ok in a multiselect listbox (selectionmode prop is set to multiextended).:
Private Sub cmdRemoveList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemoveList.Click
Dim knt As Integer = lstwhatever.SelectedIndices.Count
Dim i As Integer
For i = 0 To knt - 1
lstwhatever.Items.RemoveAt(lstwhatever.SelectedIndex)
Next
End Sub
Syntex for latest MySQL versions has been changed.
So try RENAME command without SINGLE QUOTES in table names.
RENAME TABLE old_name_of_table TO new_name_of_table;
Remember for jQuery 1.6+ you should use the .prop()
function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
For Windows 7
You may specify an alternate path for \data\db
with the dbpath setting for mongod.exe,
as in the following example:
c:\mongodb\bin\mongod.exe --dbpath c:\mongodb\data\db
or
you can set dbpath through Configuration File.
equals()
function is a method of Object
class which should be overridden by programmer. String
class overrides it to check if two strings are equal i.e. in content and not reference.
==
operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc
and xyz
, both refer to same String
"Awesome"
. Hence the expression (abc == xyz)
is true
.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc
and xyz
are two different strings with the same content "Hello World"
. Hence here the expression (abc == xyz)
is false
where as (abc.equals(xyz))
is true
.
Hope you understood the difference between ==
and <Object>.equals()
Thanks.
Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:
var result = someCollection.Select( x => new { x.Name, x.Address });
Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:
button1.Click += (sender, e) => { /* Do Some Work */ }
Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:
var filteredResults =
someCollection.Where(x => x.someCriteriaHolder == someCriteria);
I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.
def wordCount(mystring):
tempcount = 0
count = 1
try:
for character in mystring:
if character == " ":
tempcount +=1
if tempcount ==1:
count +=1
else:
tempcount +=1
else:
tempcount=0
return count
except Exception:
error = "Not a string"
return error
mystring = "I am having a very nice 23!@$ day."
print(wordCount(mystring))
output is 8
For integers:
Use arithmetic expansion: $((EXPR))
num=$((num1 + num2))
num=$(($num1 + $num2)) # Also works
num=$((num1 + 2 + 3)) # ...
num=$[num1+num2] # Old, deprecated arithmetic expression syntax
Using the external expr
utility. Note that this is only needed for really old systems.
num=`expr $num1 + $num2` # Whitespace for expr is important
For floating point:
Bash doesn't directly support this, but there are a couple of external tools you can use:
num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc) # Whitespace for echo is important
You can also use scientific notation (for example, 2.5e+2
).
Common pitfalls:
When setting a variable, you cannot have whitespace on either side of =
, otherwise it will force the shell to interpret the first word as the name of the application to run (for example, num=
or num
)
num= 1
num =2
bc
and expr
expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like 3+
+4
.
num=`expr $num1+ $num2`
you can not stop user from seeing our code but you can avoid it by disabling some keys
simply you can do <body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;"><!--Your body context--> </body>
After doing this following keys get disabled automatically
1. Ctrl + Shift + U 2. Ctrl + Shift + C 3. Ctrl + Shift + I 4. Right Click of mouse 5. F12 Key
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr = new String[3];
addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";
addresses.add(addressesArr);
change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/
When you need an outer join the second syntax is not always required:
Oracle:
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x(+)
MSSQLServer (although it's been deprecated in 2000 version)/Sybase:
SELECT a.foo, b.foo
FROM a, b
WHERE a.x *= b.x
But returning to your question. I don't know the answer, but it is probably related to the fact that a join is more natural (syntactically, at least) than adding an expression to a where clause when you are doing exactly that: joining.
I know its too late but this solution is working perfect for both .net framework and .net core:
@System.Web.HttpUtility.JavaScriptStringEncode()
From my experience in SQL Server,I found one of the scenarios where CTE outperformed Temp table
I needed to use a DataSet(~100000) from a complex Query just ONCE in my stored Procedure.
Temp table was causing an overhead on SQL where my Procedure was performing slowly(as Temp Tables are real materialized tables that exist in tempdb and Persist for the life of my current procedure)
On the other hand, with CTE, CTE Persist only until the following query is run. So, CTE is a handy in-memory structure with limited Scope. CTEs don't use tempdb by default.
This is one scenario where CTEs can really help simplify your code and Outperform Temp Table. I had Used 2 CTEs, something like
WITH CTE1(ID, Name, Display)
AS (SELECT ID,Name,Display from Table1 where <Some Condition>),
CTE2(ID,Name,<col3>) AS (SELECT ID, Name,<> FROM CTE1 INNER JOIN Table2 <Some Condition>)
SELECT CTE2.ID,CTE2.<col3>
FROM CTE2
GO
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times: in milli seconds.
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.
A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.
By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!
If only the incoming stream stalls for more than a millisecond you are running into a timeout.
Are you trying to run Windows Python from Cygwin? I'm having the same problem. Python in Cygwin fails to import site. Python in Cmd works.
It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw
to make them Windows paths. Also, python seems to be using some incorrect paths.
I think I'll need to install python through cygwin to get it working.
Simple solution would be to create a directive which you can apply to any control.
import { Directive, ElementRef, Input, Renderer, HostListener, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[ngModel][debounce]',
})
export class Debounce
{
@Output() public onDebounce = new EventEmitter<any>();
@Input('debounce') public debounceTime: number = 500;
private modelValue = null;
constructor(public model: NgControl, el: ElementRef, renderer: Renderer){
}
ngOnInit(){
this.modelValue = this.model.value;
if (!this.modelValue){
var firstChangeSubs = this.model.valueChanges.subscribe(v =>{
this.modelValue = v;
firstChangeSubs.unsubscribe()
});
}
this.model.valueChanges
.debounceTime(this.debounceTime)
.distinctUntilChanged()
.subscribe(mv => {
if (this.modelValue != mv){
this.modelValue = mv;
this.onDebounce.emit(mv);
}
});
}
}
usage would be
<textarea [ngModel]="somevalue"
[debounce]="2000"
(onDebounce)="somevalue = $event"
rows="3">
</textarea>
public static string Encryption(string strText)
{
var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
// client encrypting data with public key issued by server
rsa.FromXmlString(publicKey.ToString());
var encryptedData = rsa.Encrypt(testData, true);
var base64Encrypted = Convert.ToBase64String(encryptedData);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
public static string Decryption(string strText)
{
var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
var base64Encrypted = strText;
// server decrypting data with private key
rsa.FromXmlString(privateKey);
var resultBytes = Convert.FromBase64String(base64Encrypted);
var decryptedBytes = rsa.Decrypt(resultBytes, true);
var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
return decryptedData.ToString();
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
Use btoa("yourstring")
more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs
This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string
, like so:
require 'json'
JSON.parse(json_string)
If you’re using an older Ruby, you may need to install the json gem.
There are also other implementations of JSON for Ruby that may fit some use-cases better:
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
dynamic_cast
can determine if the type contains the target type anywhere in the inheritance hierarchy (yes, it's a little-known feature that if B
inherits from A
and C
, it can turn an A*
directly into a C*
). typeid()
can determine the exact type of the object. However, these should both be used extremely sparingly. As has been mentioned already, you should always be avoiding dynamic type identification, because it indicates a design flaw. (also, if you know the object is for sure of the target type, you can do a downcast with a static_cast
. Boost offers a polymorphic_downcast
that will do a downcast with dynamic_cast
and assert
in debug mode, and in release mode it will just use a static_cast
).
It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:
class Program
{
static void Main(string[] args)
{
Task task1 = Task.Factory.StartNew(() => doStuff());
Task task2 = Task.Factory.StartNew(() => doStuff());
Task task3 = Task.Factory.StartNew(() => doStuff());
Task.WaitAll(task1, task2, task3);
Console.WriteLine("All threads complete");
}
static void doStuff()
{
//do stuff here
}
}
In previous versions of .NET you could use the BackgroundWorker
object, use ThreadPool.QueueUserWorkItem()
, or create your threads manually and use Thread.Join()
to wait for them to complete:
static void Main(string[] args)
{
Thread t1 = new Thread(doStuff);
t1.Start();
Thread t2 = new Thread(doStuff);
t2.Start();
Thread t3 = new Thread(doStuff);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("All threads complete");
}
I don't have enough reputation to comment on Manni's answer, but [paths objectAtIndex:0] is the standard way of getting the application's Documents Directory
Because the NSSearchPathForDirectoriesInDomains function was designed originally for Mac OS X, where there could be more than one of each of these directories, it returns an array of paths rather than a single path. In iOS, the resulting array should contain the single path to the directory. Listing 3-1 shows a typical use of this function.
Listing 3-1 Getting the path to the application’s Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener
then add the variable Button button1;
then add this to your onCreate()
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
when you implement OnClickListener you need to add the inherited method onClick()
where you will handle your clicks
Sounds like more work than its worth.
1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.
2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
I use Mock (which is now unittest.mock on py3.3+) for this:
from mock import patch
from PyQt4 import Qt
@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
self.win.actionAboutQt.trigger()
self.assertTrue(mock.called)
For your case, it could look like this:
import mock
from mock import patch
def testClearWasCalled(self):
aw = aps.Request("nv1")
with patch.object(aw, 'Clear') as mock:
aw2 = aps.Request("nv2", aw)
mock.assert_called_with(42) # or mock.assert_called_once_with(42)
Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.
Caveat emptor! (Buyer beware!)
If you mistype assert_called_with
(to assert_called_once
or assert_called_wiht
) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true
. For more info read assert_called_once: Threat or Menace.
Check this out:
Imports System.IO
Imports System.Management
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
Process.Start(TextBox1.Text)
End Sub
End Class
This is one of those things that can be difficult to search for if you don't already know where to look.
[
is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.
There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.
[
is equivalent to the test
command, except that [
requires ]
as its last argument, and test
does not.
Assuming the bash documentation is installed on your system, if you type info bash
and search for 'test'
or '['
(the apostrophes are part of the search), you'll find the documentation for the [
command, also known as the test
command. If you use man bash
instead of info bash
, search for ^ *test
(the word test
at the beginning of a line, following some number of spaces).
Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne
, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, !=
is the string inequality operator.
You can also find bash documentation on the web.
test
and [
)-ne
is under "arg1 OP arg2")test
The official definition of the test
command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).
$('div[id ^= "player_"]');
This worked for me..select all Div starts with "players_" keyword and display it.
Create a bi-directional relationship, like this:
@Entity
public class Parent implements Serializable {
@Id
@GeneratedValue
private long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private Set<Child> children;
}
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore
to the getter.
Which you've tried:
Add @JsonIgnore on the getter method only
Do this, and also add a specific @JsonProperty
annotation for your JSON "password" field name to the setter method for the password on your object.
More recent versions of Jackson have added READ_ONLY
and WRITE_ONLY
annotation arguments for JsonProperty
. So you could also do something like:
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Docs can be found here.
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
public interface Foo {
public static int bar();
}
and
public interface Foo {
public static int bar() {
...
}
}
The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.
Java could allow the latter; and in fact, starting in Java 8, it does!
From the excellent resources available at RStudio's Sparklyr package page:
SPARK DEFINITIONS:
It may be useful to provide some simple definitions for the Spark nomenclature:
Node: A server
Worker Node: A server that is part of the cluster and are available to run Spark jobs
Master Node: The server that coordinates the Worker nodes.
Executor: A sort of virtual machine inside a node. One Node can have multiple Executors.
Driver Node: The Node that initiates the Spark session. Typically, this will be the server where sparklyr is located.
Driver (Executor): The Driver Node will also show up in the Executor list.
Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:
What is Anonymous FTP?
Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".
…
Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.
These are general recommendations, though. Each FTP server may have its own guidelines.
For sample use of the ftp
command on anonymous FTP access, see appendix A:
atlas.arc.nasa.gov% ftp naic.nasa.gov Connected to naic.nasa.gov. 220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready. Name (naic.nasa.gov:amarine): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230----------------------------------------------------------------- 230-Welcome to the NASA Network Applications and Info Center Archive 230- 230- Access to NAIC's online services is also available through: 230- 230- Gopher - naic.nasa.gov (port 70) 230- World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html 230- 230- If you experience any problems please send email to 230- 230- [email protected] 230- 230- or call +1 (800) 858-9947 230----------------------------------------------------------------- 230- 230-Please read the file README 230- it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago 230 Guest login ok, access restrictions apply. ftp> cd files/rfc 250-Please read the file README.rfc 250- it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago 250 CWD command successful. ftp> get rfc959.txt 200 PORT command successful. 150 Opening ASCII mode data connection for rfc959.txt (147316 bytes). 226 Transfer complete. local: rfc959.txt remote: rfc959.txt 151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s) ftp> quit 221 Goodbye. atlas.arc.nasa.gov%
See also the example session at the University of Edinburgh site.
Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId
to create common id so that I can inner join them:
Insert Into #TempResult
select CountA, CountB, CountC from
(
select Count(A_Id) as CountA, 1 as commonId from tableA
where ....
and ...
and ...
) as tempA
inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
where ...
and ...
and ...
) as tempB
on tempA.commonId = tempB.commonId
inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and ...
) as tempC
on tmepB.commonId = tempC.commonId
--view insert result
select * from #TempResult
A major factor will be whether you're using a transactional engine and whether you have autocommit on.
Autocommit is on by default and you probably want to leave it on; therefore, each insert that you do does its own transaction. This means that if you do one insert per row, you're going to be committing a transaction for each row.
Assuming a single thread, that means that the server needs to sync some data to disc for EVERY ROW. It needs to wait for the data to reach a persistent storage location (hopefully the battery-backed ram in your RAID controller). This is inherently rather slow and will probably become the limiting factor in these cases.
I'm of course assuming that you're using a transactional engine (usually innodb) AND that you haven't tweaked the settings to reduce durability.
I'm also assuming that you're using a single thread to do these inserts. Using multiple threads muddies things a bit because some versions of MySQL have working group-commit in innodb - this means that multiple threads doing their own commits can share a single write to the transaction log, which is good because it means fewer syncs to persistent storage.
On the other hand, the upshot is, that you REALLY WANT TO USE multi-row inserts.
There is a limit over which it gets counter-productive, but in most cases it's at least 10,000 rows. So if you batch them up to 1,000 rows, you're probably safe.
If you're using MyISAM, there's a whole other load of things, but I'll not bore you with those. Peace.
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with
statement in Python). In your case you could do something like this:
with pd.option_context('display.float_format', '${:0.2f}'.format):
print(df)
If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.
This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
Well, there really is a lot to this. I'm assuming you have an account on http://github.com/. If not, go get one.
After that, you really can just follow their guide, its very simple and easy and the explanation is much more clear than mine: http://help.github.com/ >> http://help.github.com/mac-set-up-git/
To answer your specific question: You upload files to github through the git push
command after you have added your files you needed through git add 'files'
and commmited them git commit -m "my commit messsage"
To write it with a while loop you can do:
ls -f /var | while read -r file; do cmd $file; done
The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)
you will get the time without specifying the date format. convert the string to date using Date
object
var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
working solution:
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
You can use convert
from hablar
to change a column of the data frame quickly.
library(tidyverse)
library(hablar)
x <- tibble(var = c(1.34, 4.45, 6.98))
x %>%
convert(int(var))
gives you:
# A tibble: 3 x 1
var
<int>
1 1
2 4
3 6
From some where I found below :-
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
Class fooClass = Class.forName("FooBar");
Method fooMethod =
fooClass.getMethod("fooMethod", new Class[] { String.class });
String fooReturned =
(String) fooMethod.invoke(fooClass.newInstance(), "I did it");
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
In modern browsers, there are two types of notifications:
The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.
Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost://
or HTTPS.
// request permission on page load_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
if (!Notification) {_x000D_
alert('Desktop notifications not available in your browser. Try Chromium.');_x000D_
return;_x000D_
}_x000D_
_x000D_
if (Notification.permission !== 'granted')_x000D_
Notification.requestPermission();_x000D_
});_x000D_
_x000D_
_x000D_
function notifyMe() {_x000D_
if (Notification.permission !== 'granted')_x000D_
Notification.requestPermission();_x000D_
else {_x000D_
var notification = new Notification('Notification title', {_x000D_
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',_x000D_
body: 'Hey there! You\'ve been notified!',_x000D_
});_x000D_
notification.onclick = function() {_x000D_
window.open('http://stackoverflow.com/a/13328397/1269037');_x000D_
};_x000D_
}_x000D_
}
_x000D_
<button onclick="notifyMe()">Notify me!</button>
_x000D_
We're using the W3C Notifications API. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.
W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.
Note that Chrome doesn't honor the notification icon on Linux, due to this bug.
Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.
Now the latest standard is at https://notifications.spec.whatwg.org/.
As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.
See also notify.js for a helper library.
if(mas[i].indexOf("bird") == 0)
//there is bird
You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp
I tried the above example with slight modification-
public static void main(final String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 2;
return i;
} finally {
i = 12;
System.out.println("finally trumps return.");
}
}
The above code outputs:
finally trumps return.
2
This is because when return i;
is executed i
has a value 2. After this the finally
block is executed where 12 is assigned to i
and then System.out
out is executed.
After executing the finally
block the try
block returns 2, rather than returning 12, because this return statement is not executed again.
If you will debug this code in Eclipse then you'll get a feeling that after executing System.out
of finally
block the return
statement of try
block is executed again. But this is not the case. It simply returns the value 2.
this should work:
public void setSections (Context c, List<Section> sectionList){
this.sectionList = sectionList;
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
String sectionListString = new Gson().toJson(sectionList,sectionListType);
SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
editor.apply();
}
them, to catch it just:
public List<Section> getSections(Context c){
if(this.sectionList == null){
String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);
if(sSections == null){
return new ArrayList<>();
}
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
try {
this.sectionList = new Gson().fromJson(sSections, sectionListType);
if(this.sectionList == null){
return new ArrayList<>();
}
}catch (JsonSyntaxException ex){
return new ArrayList<>();
}catch (JsonParseException exc){
return new ArrayList<>();
}
}
return this.sectionList;
}
it works for me.
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
It would be this
array=($(ls -d */))
EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.
To get the child process and thread,
pstree -p PID
.
It also show the hierarchical tree
You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes.
var prop=false;
if(value == 1) {
prop=true;
}
$('#checkbox').prop('checked',prop);
or simply,
$('#checkbox').prop('checked',(value == 1));
Snippet
$(document).ready(function() {_x000D_
var chkbox = $('.customcheckbox');_x000D_
$(".customvalue").keyup(function() {_x000D_
chkbox.prop('checked', this.value==1);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
As one user states, Arrays are the "old school" collection (yes, arrays are considered a collection though not part of System.Collections
). But, what is "old school" about arrays in comparison to other collections, i.e the ones you have listed in your title (here, ArrayList and List(Of T))? Let's start with the basics by looking at Arrays.
To start, Arrays in Microsoft .NET are, "mechanisms that allow you to treat several [logically-related] items as a single collection," (see linked article). What does that mean? Arrays store individual members (elements) sequentially, one after the other in memory with a starting address. By using the array, we can easily access the sequentially stored elements beginning at that address.
Beyond that and contrary to programming 101 common conceptions, Arrays really can be quite complex:
Arrays can be single dimension, multidimensional, or jadded (jagged arrays are worth reading about). Arrays themselves are not dynamic: once initialized, an array of n size reserves enough space to hold n number of objects. The number of elements in the array cannot grow or shrink. Dim _array As Int32() = New Int32(100)
reserves enough space on the memory block for the array to contain 100 Int32 primitive type objects (in this case, the array is initialized to contain 0s). The address of this block is returned to _array
.
According to the article, Common Language Specification (CLS) requires that all arrays be zero-based. Arrays in .NET support non-zero-based arrays; however, this is less common. As a result of the "common-ness" of zero-based arrays, Microsoft has spent a lot of time optimizing their performance; therefore, single dimension, zero-based (SZs) arrays are "special" - and really the best implementation of an array (as opposed to multidimensional, etc.) - because SZs have specific intermediary language instructions for manipulating them.
Arrays are always passed by reference (as a memory address) - an important piece of the Array puzzle to know. While they do bounds checking (will throw an error), bounds checking can also be disabled on arrays.
Again, the biggest hindrance to arrays is that they are not re-sizable. They have a "fixed" capacity. Introducing ArrayList and List(Of T) to our history:
The ArrayList (along with List(Of T)
- though there are some critical differences, here, explained later) - is perhaps best thought of as the next addition to collections (in the broad sense). ArrayList inherit from the IList (a descendant of 'ICollection') interface. ArrayLists, themselves, are bulkier - requiring more overhead - than Lists.
IList
does enable the implementation to treat ArrayLists as fixed-sized lists (like Arrays); however, beyond the additional functionallity added by ArrayLists, there are no real advantages to using ArrayLists that are fixed size as ArrayLists (over Arrays) in this case are markedly slower.
From my reading, ArrayLists cannot be jagged: "Using multidimensional arrays as elements... is not supported". Again, another nail in the coffin of ArrayLists. ArrayLists are also not "typed" - meaning that, underneath everything, an ArrayList is simply a dynamic Array of Objects: Object[]
. This requires a lot of boxing (implicit) and unboxing (explicit) when implementing ArrayLists, again adding to their overhead.
Unsubstantiated thought: I think I remember either reading or having heard from one of my professors that ArrayLists are sort of the bastard conceptual child of the attempt to move from Arrays to List-type Collections, i.e. while once having been a great improvement to Arrays, they are no longer the best option as further development has been done with respect to collections
The difference in memory usage is significant enough to where a List(Of Int32) consumed 56% less memory than an ArrayList containing the same primitive type (8 MB vs. 19 MB in the above gentleman's linked demonstration: again, linked here) - though this is a result compounded by the 64-bit machine. This difference really demonstrates two things: first (1), a boxed Int32-type "object" (ArrayList) is much bigger than a pure Int32 primitive type (List); second (2), the difference is exponential as a result of the inner-workings of a 64-bit machine.
So, what's the difference and what is a List(Of T)? MSDN defines a List(Of T)
as, "... a strongly typed list of objects that can be accessed by index." The importance here is the "strongly typed" bit: a List(Of T) 'recognizes' types and stores the objects as their type. So, an Int32
is stored as an Int32
and not an Object
type. This eliminates the issues caused by boxing and unboxing.
MSDN specifies this difference only comes into play when storing primitive types and not reference types. Too, the difference really occurs on a large scale: over 500 elements. What's more interesting is that the MSDN documentation reads, "It is to your advantage to use the type-specific implementation of the List(Of T) class instead of using the ArrayList class...."
Essentially, List(Of T) is ArrayList, but better. It is the "generic equivalent" of ArrayList. Like ArrayList, it is not guaranteed to be sorted until sorted (go figure). List(Of T) also has some added functionality.
I would use this syntax. It achives the same as Josh and Chris's suggestions, but with the advantage it is ANSI complient and not tied to a particular database vendor.
select count(case when myColumn = 1 then 1 else null end)
from AD_CurrentView
You could also download Xcode to your mac and use iPhone simulator.
The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.
dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;
dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;
the value changed event function
void Dtp_ValueChanged(object sender, EventArgs e)
{
if(((DateTimePicker)sender).ShowCheckBox==true)
{
if(((DateTimePicker)sender).Checked==false)
{
((DateTimePicker)sender).CustomFormat = " ";
((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
Actually openssl
command is a better tool than curl
for checking and debugging SSL. Here is an example with openssl
:
openssl s_client -showcerts -connect stackoverflow.com:443 < /dev/null
and < /dev/null
is for adding EOL to the STDIN
otherwise it hangs on the Terminal.
But if you liked, you can wrap some useful openssl
commands with curl
(as I did with curly) and make it more human readable like so:
# check if SSL is valid
>>> curly --ssl valid -d stackoverflow.com
Verify return code: 0 (ok)
issuer=C = US
O = Let's Encrypt
CN = R3
subject=CN = *.stackexchange.com
option: ssl
action: valid
status: OK
# check how many days it will be valid
>>> curly --ssl date -d stackoverflow.com
Verify return code: 0 (ok)
from: Tue Feb 9 16:13:16 UTC 2021
till: Mon May 10 16:13:16 UTC 2021
days total: 89
days passed: 8
days left: 81
option: ssl
action: date
status: OK
# check which names it supports
curly --ssl name -d stackoverflow.com
*.askubuntu.com
*.blogoverflow.com
*.mathoverflow.net
*.meta.stackexchange.com
*.meta.stackoverflow.com
*.serverfault.com
*.sstatic.net
*.stackexchange.com
*.stackoverflow.com
*.stackoverflow.email
*.superuser.com
askubuntu.com
blogoverflow.com
mathoverflow.net
openid.stackauth.com
serverfault.com
sstatic.net
stackapps.com
stackauth.com
stackexchange.com
stackoverflow.blog
stackoverflow.com
stackoverflow.email
stacksnippets.net
superuser.com
option: ssl
action: name
status: OK
# check the CERT of the SSL
>>> curly --ssl cert -d stackoverflow.com
-----BEGIN CERTIFICATE-----
MIIG9DCCBdygAwIBAgISBOh5mcfyJFrMPr3vuAuikAYwMA0GCSqGSIb3DQEBCwUA
MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD
EwJSMzAeFw0yMTAyMDkxNjEzMTZaFw0yMTA1MTAxNjEzMTZaMB4xHDAaBgNVBAMM
Eyouc3RhY2tleGNoYW5nZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDRDObYpjCvb2smnCP+UUpkKdSr6nVsIN8vkI6YlJfC4xC72bY2v38lE2xB
LCaL9MzKhsINrQZRIUivnEHuDOZyJ3Xwmxq3wY0qUKo2c963U7ZJpsIFsj37L1Ac
Qp4pubyyKPxTeFAzKbpfwhNml633Ao78Cy/l/sYjNFhMPoBN4LYBX7/WJNIfc3UZ
niMfh230NE2dwoXGqA0MnkPQyFKlIwHcmMb+ZI5T8TziYq0WQiYUY3ssOEu1CI5n
wh0+BTAwpx7XBUe5Z+B9SrFp8BUDYWcWuVEIh2btYvo763mrr+lmm8PP23XKkE4f
287Iwlfg/IqxxIxKv9smFoPkyZcFAgMBAAGjggQWMIIEEjAOBgNVHQ8BAf8EBAMC
BaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAw
HQYDVR0OBBYEFMnjX41T+J1bbLgG9TjR/4CvHLv/MB8GA1UdIwQYMBaAFBQusxe3
WFbLrlAJQOYfr52LFMLGMFUGCCsGAQUFBwEBBEkwRzAhBggrBgEFBQcwAYYVaHR0
cDovL3IzLm8ubGVuY3Iub3JnMCIGCCsGAQUFBzAChhZodHRwOi8vcjMuaS5sZW5j
ci5vcmcvMIIB5AYDVR0RBIIB2zCCAdeCDyouYXNrdWJ1bnR1LmNvbYISKi5ibG9n
b3ZlcmZsb3cuY29tghIqLm1hdGhvdmVyZmxvdy5uZXSCGCoubWV0YS5zdGFja2V4
Y2hhbmdlLmNvbYIYKi5tZXRhLnN0YWNrb3ZlcmZsb3cuY29tghEqLnNlcnZlcmZh
dWx0LmNvbYINKi5zc3RhdGljLm5ldIITKi5zdGFja2V4Y2hhbmdlLmNvbYITKi5z
dGFja292ZXJmbG93LmNvbYIVKi5zdGFja292ZXJmbG93LmVtYWlsgg8qLnN1cGVy
dXNlci5jb22CDWFza3VidW50dS5jb22CEGJsb2dvdmVyZmxvdy5jb22CEG1hdGhv
dmVyZmxvdy5uZXSCFG9wZW5pZC5zdGFja2F1dGguY29tgg9zZXJ2ZXJmYXVsdC5j
b22CC3NzdGF0aWMubmV0gg1zdGFja2FwcHMuY29tgg1zdGFja2F1dGguY29tghFz
dGFja2V4Y2hhbmdlLmNvbYISc3RhY2tvdmVyZmxvdy5ibG9nghFzdGFja292ZXJm
bG93LmNvbYITc3RhY2tvdmVyZmxvdy5lbWFpbIIRc3RhY2tzbmlwcGV0cy5uZXSC
DXN1cGVydXNlci5jb20wTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC3xMB
AQEwKDAmBggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcwggEE
BgorBgEEAdZ5AgQCBIH1BIHyAPAAdgBElGUusO7Or8RAB9io/ijA2uaCvtjLMbU/
0zOWtbaBqAAAAXeHyHI8AAAEAwBHMEUCIQDnzDcCrmCPdfgcb/ojY0WJV1rCj+uE
hCiQi0+4fBP9lgIgSI5mwEqBmVcQwRfKikUzhkH0w6K/6wq0e/1zJA0j5a4AdgD2
XJQv0XcwIhRUGAgwlFaO400TGTO/3wwvIAvMTvFk4wAAAXeHyHIoAAAEAwBHMEUC
IHd0ZLB3j0b31Sh/D3RIfF8C31NxIRSG6m/BFSCGlxSWAiEAvYlgPjrPcBZpX4Xm
SdkF39KbVicTGnFOSAqDpRB3IJwwDQYJKoZIhvcNAQELBQADggEBABZ+2WXyP4w/
A+jJtBgKTZQsA5VhUCabAFDEZdnlWWcV3WYrz4iuJjp5v6kL4MNzAvAVzyCTqD1T
m7EUn/usz59m02mZF82+ELLW6Mqix8krYZTpYt7Hu3Znf6HxiK3QrjEIVlwSGkjV
XMCzOHdALreTkB+UJaL6bEs1sB+9h20zSnZAKrPokGL/XwgxUclXIQXr1uDAShJB
Ts0yjoSY9D687W9sjhq+BIjNYIWg1n9NJ7HM48FWBCDmV3NlCR0Zh1Yx15pXCUhb
UqWd6RzoSLmIfdOxgfi9uRSUe0QTZ9o/Fs4YoMi5K50tfRycLKW+BoYDgde37As5
0pCUFwVVH2E=
-----END CERTIFICATE-----
option: ssl
action: cert
status: OK