By adding the external jar into your build path just adds the jar to your package, but it will not be available during runtime.
In order for the jar to be available at runtime, you need to:
assets
folder The solution that work for me is the following:
You can also sort the column by importing the spark sql functions
import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))
Or
import org.apache.spark.sql.functions._
df.sort(desc("col1"))
importing sqlContext.implicits._
import sqlContext.implicits._
df.orderBy($"col1".desc)
Or
import sqlContext.implicits._
df.sort($"col1".desc)
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Change div to span. And space the icons using
HTML
<div class="nav3" style="height:705px;">
<span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
</span>
<span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
</span>
</div>
CSS
.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}
.icons{
display:inline-block;
width: 64px;
height: 64px;
}
a.icons:hover {
background: #C93;
}
span does not break line, div does.
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class);
No code? For shame!
Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).
But rather than cry, I decided to try:
This code works OK for parsing most Esri results for findAddressCandidate
and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
var address = {_x000D_
street: "",_x000D_
city: "",_x000D_
state: "",_x000D_
postalCode: ""_x000D_
};_x000D_
_x000D_
// tokenize by space (retain commas in tokens)_x000D_
var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
var tokenCount = tokens.length;_x000D_
var lastToken = tokens.pop();_x000D_
if (_x000D_
// if numeric assume postal code (ignore length, for now)_x000D_
!isNaN(lastToken) ||_x000D_
// if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
lastToken.split("-").length - 1 === 1) {_x000D_
address.postalCode = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
_x000D_
if (lastToken && isNaN(lastToken)) {_x000D_
if (address.postalCode.length && lastToken.length === 2) {_x000D_
// assume state/province code ONLY if had postal code_x000D_
// otherwise it could be a simple address like "714 S OAK ST"_x000D_
// where "ST" for "street" looks like two-letter state code_x000D_
// possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
address.state = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
if (address.state.length === 0) {_x000D_
// check for special case: might have State name instead of State Code._x000D_
var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found separator, ignore stuff on left side_x000D_
tokens.push(lastToken); // put it back_x000D_
break;_x000D_
} else {_x000D_
stateNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.state = stateNameParts.join(' ');_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
}_x000D_
_x000D_
if (lastToken) {_x000D_
// here is where it gets trickier:_x000D_
if (address.state.length) {_x000D_
// if there is a state, then assume there is also a city and street._x000D_
// PROBLEM: city may be multiple words (spaces)_x000D_
// but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
// most cities are single-name. It would be very helpful if we knew more context, like_x000D_
// the name of the city user is in. But ignore that for now._x000D_
// ideally would have zip code service or lookup to give city name for the zip code._x000D_
var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// assumption / RULE: street and city must have comma delimiter_x000D_
// addresses that do not follow this rule will be wrong only if city has space_x000D_
// but don't care because Esri formats put comma before City_x000D_
var streetNameParts = [];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found end of street address (may include building, etc. - don't care right now)_x000D_
// add token back to end, but remove trailing comma (it did its job)_x000D_
tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
streetNameParts = tokens;_x000D_
break;_x000D_
} else {_x000D_
cityNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.city = cityNameParts.join(' ');_x000D_
address.street = streetNameParts.join(' ');_x000D_
} else {_x000D_
// if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
// reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
// put last token back in list, then rejoin on space_x000D_
tokens.push(lastToken);_x000D_
address.street = tokens.join(' ');_x000D_
}_x000D_
}_x000D_
// when parsing right-to-left hard to know if street only vs street + city/state_x000D_
// hack fix for now is to shift stuff around._x000D_
// assumption/requirement: will always have at least street part; you will never just get "city, state" _x000D_
// could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
if (!address.city && address.state) {_x000D_
address.city = address.state;_x000D_
address.state = '';_x000D_
}_x000D_
if (!address.street) {_x000D_
address.street = address.city;_x000D_
address.city = '';_x000D_
}_x000D_
_x000D_
return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
.filter(function(o) {_x000D_
return o.length > 0_x000D_
})_x000D_
.map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll & Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
Try using below:
SELECT
(RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
col_1,
col_2
FROM
s_cols
WHERE
col_any_condition = ''
;
Just setting height to 100% won't be the solution if you have a background page whose height extends beyond browser height.
Adding to Bhargavi's answer, this is the solution when you have scrollable page in the background.
.modal-backdrop.in
{
opacity:0.5 !important;
position:fixed;// This makes it cover the entire scrollable page, not just browser height
height:100%;
}
grep LMN20113456 LMN2011*
or if you want to search recursively through subdirectories:
find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;
This could be done using reshape
. It is possible with dplyr
though.
colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
colnames(df)[2] <- "Date"
res <- reshape(df, idvar=c("id", "Date"), varying=3:8, direction="long", sep="_")
row.names(res) <- 1:nrow(res)
head(res)
# id Date time Q3.2 Q3.3
#1 1 2009-01-01 1 1.3709584 0.4554501
#2 2 2009-01-02 1 -0.5646982 0.7048373
#3 3 2009-01-03 1 0.3631284 1.0351035
#4 4 2009-01-04 1 0.6328626 -0.6089264
#5 5 2009-01-05 1 0.4042683 0.5049551
#6 6 2009-01-06 1 -0.1061245 -1.7170087
Or using dplyr
library(tidyr)
library(dplyr)
colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
df %>%
gather(loop_number, "Q3", starts_with("Q3")) %>%
separate(loop_number,c("L1", "L2"), sep="_") %>%
spread(L1, Q3) %>%
select(-L2) %>%
head()
# id time Q3.2 Q3.3
#1 1 2009-01-01 1.3709584 0.4554501
#2 1 2009-01-01 1.3048697 0.2059986
#3 1 2009-01-01 -0.3066386 0.3219253
#4 2 2009-01-02 -0.5646982 0.7048373
#5 2 2009-01-02 2.2866454 -0.3610573
#6 2 2009-01-02 -1.7813084 -0.7838389
With new version of tidyr
, we can use pivot_longer
to reshape multiple columns. (Using the changed column names from gsub
above)
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = starts_with("Q3"),
names_to = c(".value", "Q3"), names_sep = "_") %>%
select(-Q3)
# A tibble: 30 x 4
# id time Q3.2 Q3.3
# <int> <date> <dbl> <dbl>
# 1 1 2009-01-01 0.974 1.47
# 2 1 2009-01-01 -0.849 -0.513
# 3 1 2009-01-01 0.894 0.0442
# 4 2 2009-01-02 2.04 -0.553
# 5 2 2009-01-02 0.694 0.0972
# 6 2 2009-01-02 -1.11 1.85
# 7 3 2009-01-03 0.413 0.733
# 8 3 2009-01-03 -0.896 -0.271
#9 3 2009-01-03 0.509 -0.0512
#10 4 2009-01-04 1.81 0.668
# … with 20 more rows
NOTE: Values are different because there was no set seed in creating the input dataset
One curious thing about views are that they are seen by Microsoft Access as tables: when you attach a Microsoft Access front-end to an SQL database using ODBC, you see the tables and views in the list of available tables. So if you are preparing complicated reports in MS Access, you can let the SQL server do the joining and querying, and greatly simplify your life. Ditto for preparing a query in MS Excel.
You are right about AccelerateInterpolator; you should use LinearInterpolator instead.
You can use the built-in android.R.anim.linear_interpolator
from your animation XML file with android:interpolator="@android:anim/linear_interpolator"
.
Or you can create your own XML interpolation file in your project, e.g. name it res/anim/linear_interpolator.xml
:
<?xml version="1.0" encoding="utf-8"?>
<linearInterpolator xmlns:android="http://schemas.android.com/apk/res/android" />
And add to your animation XML:
android:interpolator="@anim/linear_interpolator"
Special Note: If your rotate animation is inside a set, setting the interpolator does not seem to work. Making the rotate the top element fixes it. (this will save your time.)
Well, you need to look at the answers above, but you'll find that the manager app requires you to have a user with the role 'manager', I believe, so you'll probably want to add the following to your tomcat-users.xml file:
<role rolename="manager"/>
<user username="youruser" password="yourpass" roles="manager"/>
This might seem simplistic, but it's just a simple implementation that you can extend / replace with other authentication mechanisms.
The std::string::append()
method expects its argument to be a NULL terminated string (char*
).
There are several approaches for producing a string
containg an int
:
#include <sstream>
std::ostringstream s;
s << "select logged from login where id = " << ClientID;
std::string query(s.str());
std::to_string
(C++11)
std::string query("select logged from login where id = " +
std::to_string(ClientID));
#include <boost/lexical_cast.hpp>
std::string query("select logged from login where id = " +
boost::lexical_cast<std::string>(ClientID));
If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?
In version 2, instead of
from module import attribute1
you can do
attribute1 = module.attribute1
Currently (up to version 2.4.4), if any path (dbpath/logpath/config) contains spaces, then the service won't start, and show the error: "The service is not responding to the control function".
You have in your module
import {Routes, RouterModule} from '@angular/router';
you have to export the module RouteModule
example:
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
to be able to access the functionalities for all who import this module.
Upgrade to the latest SDK, for the android emulator:
You can leave the default disk space.
You can return Observable.of(empty_variable), for example
Observable.of('');
// or
Observable.of({});
// etc
I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well.
Example:
//Place at top of your code
public UseAutoDebug = true;
//Place anywhere in your code including catch areas in try/catch blocks
Debug.Assert(!this.UseAutoDebug);
Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing.
You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well.
You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily:
You need enctype="multipart/form-data"
otherwise you will load only the file name and not the data.
Go to the first line from which you would like to delete, and press the keys dG
I used the following code to get the last character of a string.
substr(output, nchar(stringOfInterest), nchar(stringOfInterest))
You can play with the nchar(stringOfInterest) to figure out how to get last few characters.
Below is my Script which show/hide table row with id "agencyrow".
<script type="text/javascript">
function showhiderow() {
if (document.getElementById("<%=RadioButton1.ClientID %>").checked == true) {
document.getElementById("agencyrow").style.display = '';
} else {
document.getElementById("agencyrow").style.display = 'none';
}
}
</script>
Just call function showhiderow()
upon radiobutton onClick
event
How about using good(?) old goto
?
:loop
echo Ooops
goto loop
See also this for a more useful example.
I think sometimes stupid mistakes can give us this error.
<div id="#main"> <--- id with hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
To
<div id="main"> <--- id without hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
Another way is to add the folder to your source lookup path: http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdebug%2Fref-editsourcelookup.htm
Here's a tip sheet I wrote up once, with the commands I actually use regularly:
<Esc>
gets you out of any mode and back to command modeAll insertion commands are terminated with <Esc>
to return to command mode.
<motion>
changes text in the direction of the motion<motion>
deletes in the direction of the motionname
write file to disk as name
tags
file); ^T return to previous position (arbitrary stack of positions maintained)Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff
You probably have syntax error.
You most likely forgot to put a }
or ;
somewhere above this function.
Try this:
$('element').attr('id', 'value');
So it becomes;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...
The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.
If all you want to do is remove the changes made in revision 3, you might want to use git revert.
Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.
What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.
This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.
To get this i tried following code :
protected T GetObject<T>()
{
T obj = default(T);
obj =Activator.CreateInstance<T>();
return obj ;
}
date under Mac OSX is slightly different.
For yesterday
date -v-1d +%F
For Last week
date -v-1w +%F
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
Given this file:
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
Prints:
line1
word1
word2
line2
...
word6
Similarly, if you want to flatten the file into a single flat list of words in the file, you might do something like this:
with open('words.txt') as f:
flat_list=[word for line in f for word in line.split()]
>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
Which can create the same output as the first example with print '\n'.join(flat_list)
...
Or, if you want a nested list of the words in each line of the file (for example, to create a matrix of rows and columns from a file):
with open('words.txt') as f:
matrix=[line.split() for line in f]
>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
If you want a regex solution, which would allow you to filter wordN
vs lineN
type words in the example file:
import re
with open("words.txt") as f:
for line in f:
for word in re.findall(r'\bword\d+', line):
# wordN by wordN with no lineN
Or, if you want that to be a line by line generator with a regex:
with open("words.txt") as f:
(word for line in f for word in re.findall(r'\w+', line))
a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat
some formatting examples
/** delta: 1234567890, @locale: 'en-US', @style: 'long' */
/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds
/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890
/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms
/* D,h:m:s.f */
14,06:56:07.890
/* D~, h:m:s.f */
14 days, 06:56:07.890
/* h~ m~ s~ */
342 hours 56 minutes 7 seconds
/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days
/* up D~, h:m */
up 14 days, 06:56
the code & test
/**
Init locale formatter:
timespan.locale(@locale, @style)
Example:
timespan.locale('en-US', 'long');
timespan.locale('es', 'narrow');
Format time delta:
timespan.format(@pattern, @milliseconds)
@pattern tokens:
D: days, h: hours, m: minutes, s: seconds, f: millis
@pattern token extension:
h => '0'-padded value,
h# => raw value,
h~ => locale formatted value
Example:
timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
output: 14 days 6 hours 56 minutes 7 seconds 890 millis
NOTES:
* milliseconds unit have no locale translation
* may encounter declension issues for some locales
* use quoted text for raw inserts
*/
const timespan = (() => {
let rtf, tokensRtf;
const
tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
map = [
{t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
{t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
{t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
{t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
{t: [['f', 3], ['f#'], ['f~']], u: 1}
],
locale = (value, style = 'long') => {
try {
rtf = new Intl.RelativeTimeFormat(value, {style});
} catch (e) {
if (rtf) throw e;
return;
}
const h = rtf.format(1, 'hour').split(' ');
tokensRtf = new Set(rtf.format(1, 'day').split(' ')
.filter(t => t != 1 && h.indexOf(t) > -1));
return true;
},
fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
mapper = {
number: (t, u) => (u + '').padStart(t.fmt, '0'),
string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
.filter(t => !tokensRtf.has(t)).join(' ')
.trim().replace(/[+-]/g, '') : fallback(t, u),
},
replace = (out, t) => out[t] || t.slice(1, t.length - 1),
format = (pattern, value) => {
if (typeof pattern !== 'string')
throw Error('invalid pattern');
if (!Number.isFinite(value))
throw Error('invalid value');
if (!pattern)
return '';
const out = {};
value = Math.abs(value);
pattern.match(tokens)?.forEach(t => out[t] = null);
map.forEach(m => {
let u = null;
m.t.forEach(t => {
if (out[t.token] !== null)
return;
if (u === null) {
u = Math.floor(value / m.u);
value %= m.u;
}
out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
})
});
return pattern.replace(tokens, replace.bind(null, out));
};
map.forEach(m => m.t = m.t.map(t => ({
token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
})));
locale('en');
return {format, locale};
})();
/************************** test below *************************/
const
cfg = {
locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
try {
const tv = new Date(td.value);
if (isNaN(tv)) throw Error('invalid "datetime2" value');
timespan.locale(loc.value || locale.value, style.value);
const delta = fd.getTime() - tv.getTime();
out.innerHTML = timespan.format(fmt.value, delta);
} catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
const elm = el(id);
value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
You can do the following with Swift 2.2:
let alertController: UIAlertController = ...
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
And Swift 3.0:
let alertController: UIAlertController = ...
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
In Kotlin you can use extension
fun Context.getMyDrawable(id : Int) : Drawable?{
return ContextCompat.getDrawable(this, id)
}
then use like
context.getMyDrawable(R.drawable.my_icon)
I'm surprised no one posted this simple solution. That is if your strings are going to be "true" or "false".
def to_boolean(str)
eval(str)
end
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use; 1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
If not all of your document scrolls, say, when you have a scrolling div
within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:
$('#someScrollingDiv').on('scroll', function() {
let div = $(this).get(0);
if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
// do the lazy loading here
}
});
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
Different ways to handle button event
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Button 1",
Toast.LENGTH_LONG).show();
}
});
[Check this article for more details about button event handlers]
Traditionally whenever I've wanted to commit and empty directory structure, I create the structure and then in the leaf directories place an empty file called empty.txt
.
Then when I put stuff in that's ready to commit, I can simply remove the empty.txt
file and commit the real files.
i.e.
There’s a function in Gary Bernhardt’s .vimrc that handles this.
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.
But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.
We have plenty of options to validate the react js forms. Maybe the npm packages have some own limitations. Based up on your needs you can choose the right validator packages. I would like to recommend some, those are listed below.
If anybody knows a better solution than this, please put it on the comment section for other people references.
I recommend unlist
, which keeps the names.
unlist(df[1,])
a b c
1.0 2.0 2.6
is.vector(unlist(df[1,]))
[1] TRUE
If you don't want a named vector:
unname(unlist(df[1,]))
[1] 1.0 2.0 2.6
function dateFormat($date)
{
$m = preg_replace('/[^0-9]/', '', $date);
if (preg_match_all('/\d{2}+/', $m, $r)) {
$r = reset($r);
if (count($r) == 4) {
if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
}
$y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
}
}
var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31
The concept of POD and the type trait std::is_pod
will be deprecated in C++20. See this question for further information.
im using only this
import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;
I had this problem updating from VS2017 to VS2019
For me the problem was simply solved by deleting the .VC.db
file of the project.
Reinstalling python based on instructions from here solved this problem for me: How can I install a previous version of Python 3 in macOS using homebrew?
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE: sc start MyService
In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient
. When installing the npm package, a duplicate node_modules
directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client
is the module containing the service):
Obviously, the dependency to HttpClient
is not resolved correctly, as the locations of HttpClientModule
injected into the service (lives in the duplicate node_modules
directory) and the one injected in app.module
(the correct node_modules
) don't match.
I've also had this error in other setups containing a duplicate node_modules
directory due to a wrong npm install
call.
This defective setup also leads to the described runtime exception No provider for HttpClient!
.
TL;DR; Check for duplicate
node_modules
directories, if none of the other solutions work!
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
This is my work around:
1) Add a wrapper div to the recaptcha div.
<div id="recaptcha-wrapper"><div class="g-recaptcha" data-sitekey="..."></div></div>
2) Add javascript/jquery code.
$(function(){
// global variables
captchaResized = false;
captchaWidth = 304;
captchaHeight = 78;
captchaWrapper = $('#recaptcha-wrapper');
captchaElements = $('#rc-imageselect, .g-recaptcha');
resizeCaptcha();
$(window).on('resize', function() {
resizeCaptcha();
});
});
function resizeCaptcha() {
if (captchaWrapper.width() >= captchaWidth) {
if (captchaResized) {
captchaElements.css('transform', '').css('-webkit-transform', '').css('-ms-transform', '').css('-o-transform', '').css('transform-origin', '').css('-webkit-transform-origin', '').css('-ms-transform-origin', '').css('-o-transform-origin', '');
captchaWrapper.height(captchaHeight);
captchaResized = false;
}
} else {
var scale = (1 - (captchaWidth - captchaWrapper.width()) * (0.05/15));
captchaElements.css('transform', 'scale('+scale+')').css('-webkit-transform', 'scale('+scale+')').css('-ms-transform', 'scale('+scale+')').css('-o-transform', 'scale('+scale+')').css('transform-origin', '0 0').css('-webkit-transform-origin', '0 0').css('-ms-transform-origin', '0 0').css('-o-transform-origin', '0 0');
captchaWrapper.height(captchaHeight * scale);
if (captchaResized == false) captchaResized = true;
}
}
3) Optional: add some styling if needed.
#recaptcha-wrapper {
text-align:center;
margin-bottom:15px;
}
.g-recaptcha {
display:inline-block;
}
1) Method1 saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2 using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
imprime en linea los datos con un espaciado determinado, así tendrás columnas de datos de la misma variable y será más claro
Print all data in line, so you have rows with the data you need, i just solve the same problem like this, just make sur you had asignad a constant data size and spacement between, I made this
Serial.print("cuenta q2: ");
Serial.print( cuenta_pulsos_encoder_1,3);
Serial.print("\t");
Serial.print(q2_real,4);
Serial.print("\t");
Serial.print("cuenta q3: ");
Serial.print( cuenta_pulsos_encoder_2,3);
Serial.print("\t");
Serial.print(q3_real,4);
Serial.print("\t");
Serial.print("cuenta q4: ");
Serial.print( cuenta_pulsos_encoder_3,3);
Serial.print("\t");
Serial.println(q4_real,4);
PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.
I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowException
s. For instance, if I had these objects
public class A{
Long id;
String name;
List<B> children;
}
public class B{
Long id;
A parent;
}
I would want to programmatically ignore the parent
field in B if I were looking at A, and ignore the children
field in A if I were looking at B.
I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.
It allows you programmatically specify what fields to ignore:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(B.class, match()
.exclude("parent")));
It also lets you easily specify very simplified views through wildcard matchers:
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(A.class, match()
.exclude("*")
.include("id", "name")));
In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.
All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:
@Controller
public class JsonController {
private JsonResult json = JsonResult.instance();
@Autowired
private TestObjectService service;
@RequestMapping(method = RequestMethod.GET, value = "/bean")
@ResponseBody
public List<TestObject> getTestObject() {
List<TestObject> list = service.list();
return json.use(JsonView.with(list)
.onClass(TestObject.class, Match.match()
.exclude("int1")
.include("ignoredDirect")))
.returnValue();
}
}
Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.
In response to ffpf - I had exactly the same argument with a colleague years ago, and the answer is no, it doesn't work with negative numbers.
The C standard stipulates that negative numbers can be represented in 3 ways:
Checking like this:
isEven = (x & 1);
will work for 2's complement and sign and magnitude representation, but not for 1's complement.
However, I believe that the following will work for all cases:
isEven = (x & 1) ^ ((-1 & 1) | ((x < 0) ? 0 : 1)));
Thanks to ffpf for pointing out that the text box was eating everything after my less than character!
private int GetYearDiff(DateTime start, DateTime end)
{
int diff = end.Year - start.Year;
if (end.DayOfYear < start.DayOfYear) { diff -= 1; }
return diff;
}
[Fact]
public void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()
{
//arrange
var now = DateTime.Now;
//act
//assert
Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed
Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed
Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed
}
Fields in interfaces are implicitly public static final
. (Also methods are implicitly public, so you can drop the public
keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final
of a primitive or immutable object reference) private
. More generally "prefer composition to inheritance" - a Tile
is-not-a Rectangle
(of course, you can play word games with "is-a" and "has-a").
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:
<android:theme="@android:style/Theme.NoTitleBar">
Just add it to your application
tag to apply it app-wide.
Answer is as follows:
super.Mymethod();
super(); // calls base class Superclass constructor.
super(parameter list); // calls base class parameterized constructor.
super.method(); // calls base class method.
Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.
The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.
If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.
document.getElementById('child')
should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.
The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.
I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).
For the test, I set:
the GoalSeek cell H18 = (G18^3)+(3*G18^2)+6
the Goal cell H32 = 11
the ChangingCell G18 = 0
The code was:
Sub GSeek()
With Worksheets("Sheet1")
.Range("H18").GoalSeek _
Goal:=.Range("H32").Value, _
ChangingCell:=.Range("G18")
End With
End Sub
And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.
In my case, it was sufficient to drop the database which was hanging in state "Restoring..." with the SQL command
drop database <dbname>
in a query window.
Then I right-clicked on Databases and selected Refresh which removed the entry in Management Studio. Afterwards I did a new restore which worked fine (note that bringing it offline did not work, a restart of the SQL service did not work, a server reboot did not work as well).
Appcompat21 GridLayout
has the column and row weights which can be used like below to evenly create each grid item in the gridlayout like the image above.
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
grid:alignmentMode="alignBounds"
grid:columnCount="4" >
<Button android:layout_width="0dp"
style="?buttonStyle"
android:layout_height="0dp"
android:text="-1"
grid:layout_columnWeight="1"
grid:layout_rowWeight="1"
grid:layout_gravity="fill" />
...
</<android.support.v7.widget.GridLayout>
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
You could use the Fisher-Yates Shuffle (code adapted from this site):
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
Similar to the selected answer, a table source can be used, in this case a derived query:
delete from dd
from (
select top 1 *
from my_table
) dd
Feel free to add orderbys and conditions.
For the next example, I'll assume that the restriction on 'where' is due to not wanting to select a row based on its values. So assuming that we want to delete a row based on position (in this case the first position):
delete from dd
from (
select
*,
row = row_number() over (order by (select 1))
from my_table
) dd
where row = 1
Note that the (select 1) makes it the sort order that the tables or indexes are in. You can replace that with a newid to get fairly random rows.
You can also add a partition by to delete the top row of each color, for example.
same with speed regulator
public class SmoothScrollLinearLayoutManager extends LinearLayoutManager {
private static final float MILLISECONDS_PER_INCH = 110f;
private Context mContext;
public SmoothScrollLinearLayoutManager(Context context,int orientation, boolean reverseLayout) {
super(context,orientation,reverseLayout);
mContext = context;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext()){
//This controls the direction in which smoothScroll looks for your view
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return new PointF(0, 1);
}
//This returns the milliseconds it takes to scroll one pixel.
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SmoothScrollLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
}
The basic difference between all these annotations is as follows -
All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Important: Version 1.0 of the reCAPTCHA API is no longer supported, please upgrade to Version 2.0.
You can use grecaptcha.reset(); to reset the captcha.
Source : https://developers.google.com/recaptcha/docs/verify#api-request
An improvement on var dict = {}
is to use var dict = Object.create(null)
.
This will create an empty object that does not have Object.prototype
as it's prototype.
var dict1 = {};
if (dict1["toString"]){
console.log("Hey, I didn't put that there!")
}
var dict2 = Object.create(null);
if (dict2["toString"]){
console.log("This line won't run :)")
}
It's rather hacky, but you could use one1
as a Float64Index
to do everything in one go:
df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)
Note that as of 0.20.3, sorting the index is necessary, and the legend is a bit wonky.
Manually resolving instances involves using the IServiceProvider
interface:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<IMyService>();
}
public void Configure(
IApplicationBuilder application,
IServiceProvider serviceProvider)
{
// By type.
var service1 = (MyService)serviceProvider.GetService(typeof(MyService));
// Using extension method.
var service2 = serviceProvider.GetService<MyService>();
// ...
}
public void Configure(
IApplicationBuilder application,
IWebHostEnvironment webHostEnvironment)
{
application.ApplicationServices.GetService<MyService>();
}
Some types can be injected as method parameters:
public class Startup
{
public Startup(
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory)
{
}
public void ConfigureServices(
IServiceCollection services)
{
}
public void Configure(
IApplicationBuilder application,
IHostingEnvironment hostingEnvironment,
IServiceProvider serviceProvider,
ILoggerFactory loggerfactory,
IApplicationLifetime applicationLifetime)
{
}
}
[HttpGet("/some-action")]
public string SomeAction([FromServices] IMyService myService) => "Hello";
If you use Kotlin (which works seamlessly with Java), you can make such an enum:
enum class AnsiColor(private val colorNumber: Byte) {
BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);
companion object {
private const val prefix = "\u001B"
const val RESET = "$prefix[0m"
private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
}
val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}
And then use is as such: (code below showcases the different styles for all colors)
val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}
If running on Windows where these ANSI codes are not supported, the isCompatible
check avoids issues by replacing the codes with empty string.
$scope.$eval
With AngularJS, one can use the $scope.$eval
method to access nested objects:
$scope.someObject = someObject;
console.log( $scope.$eval("someObject.part3[0].name") ); //Part 3A
For more information, see
angular.module("app",[])
.run(function($rootScope) {
$rootScope.someObject = {
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
},{
name: 'Part 3B'
}]
};
console.log(
"part3[0].name =",
$rootScope.$eval("someObject.part3[0].name")
);
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"
</body>
_x000D_
you can use
<a href="\\computername\folder">Open folder</a>
in Internet Explorer
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
Use herDatabase
GO ;
Code says to execute the instructions above the GO
marker.
My default database is myDatabase, so instead of using myDatabase GO
and makes current query to use herDatabase
Use the drive letter with forward slashes to get started (c:/apache/...).
You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.
6.7.8 Initialization
...
3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
There are different ways to achieve it. The latest approach is using CardView for each ListItem component. Here are some steps.
**listitem.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alignmentMode="alignMargins"
android:columnCount="1"
android:columnOrderPreserved="false"
android:rowCount="1">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="6dp"
app:cardCornerRadius="8dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/sampleiconimageID"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/titleoflistview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Heading"
android:textStyle="bold" />
<TextView
android:id="@+id/samplesubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sub Heading"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</GridLayout>
</LinearLayout>
RowItem.Class
public class RowItem {
private String heading;
private String subHeading;
private int smallImageName;
private String datetime;
private int count;
public void setHeading( String theHeading ) {
this.heading = theHeading;
}
public String getHeading() {
return this.heading;
}
public void setSubHeading( String theSubHeading ) {
this.subHeading = theSubHeading;
}
public String getSubHeading( ) {
return this.subHeading;
}
public void setSmallImageName(int smallName) {
this.smallImageName = smallName;
}
public int getSmallImageName() {
return this.smallImageName;
}
public void setDate(String datetime) {
this.datetime = datetime;
}
public String getDate() {
return this.datetime;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return this.count;
}
}
Sample ListAdapter
public class ListAdapter extends BaseAdapter {
private ArrayList<RowItem> singleRow;
private LayoutInflater thisInflater;
public ListAdapter(Context context, ArrayList<RowItem> aRow){
this.singleRow = aRow;
thisInflater = ( LayoutInflater.from(context) );
}
@Override
public int getCount() {
return singleRow.size(); }
@Override
public Object getItem(int position) {
return singleRow.get( position ); }
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = thisInflater.inflate( R.layout.mylist2, parent, false );
//set listview objects here
//example
TextView titleText = (TextView) view.findViewById(R.id.titleoflistview);
RowItem currentRow = (RowItem) getItem(position);
titleText.setText( currentRow.getHeading() );
}
return view;
// LayoutInflater inflater=.getLayoutInflater();
// View rowView=inflater.inflate(R.layout.mylist, null,true);
//
// titleText.setText(maintitle[position]);
// subtitleText.setText(subtitle[position]);
// return null;
};
}
I hope this helps:
import string
alphas = list(string.ascii_letters[:26])
for chr in alphas:
print(chr)
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.
try:
from urllib import quote # Python 2.X
except ImportError:
from urllib.parse import quote # Python 3+
You could also use the python compatibility wrapper six to handle this.
from six.moves.urllib.parse import quote
This creates a fullscreen window. Pressing Escape
resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape
toggles between the current geometry and the previous geometry.
import Tkinter as tk
class FullScreenApp(object):
def __init__(self, master, **kwargs):
self.master=master
pad=3
self._geom='200x200+0+0'
master.geometry("{0}x{1}+0+0".format(
master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
master.bind('<Escape>',self.toggle_geom)
def toggle_geom(self,event):
geom=self.master.winfo_geometry()
print(geom,self._geom)
self.master.geometry(self._geom)
self._geom=geom
root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()
We can add drawable .xml like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="@color/color_C4CDD5"/>
<corners android:radius="8dp"/>
<solid
android:color="@color/color_white"/>
</shape>
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('@Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '@Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action
to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.
For example: If you configure your http server to host the generated bundle under /assets/
you should write: publicPath: "/assets/"
<table id="table1"></table>
<table id="table2"></table>
or
<table class="table1"></table>
<table class="table2"></table>
Use the helper classes VisualTreeHelper
or LogicalTreeHelper
depending on which tree you're interested in. They both provide methods for getting the children of an element (although the syntax differs a little). I often use these classes for finding the first occurrence of a specific type, but you could easily modify it to find all objects of that type:
public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
if (obj.GetType() == type)
{
return obj;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject childReturn = FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type);
if (childReturn != null)
{
return childReturn;
}
}
}
return null;
}
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
This was my solution for evaluating file sizes without using VB/perl/etc. and sticking with native windows shell commands:
FOR /F "tokens=4 delims= " %%i in ('dir /-C %temp% ^| find /i "filename.txt"') do (
IF %%i GTR 1000000 (
echo filename.txt filesize is greater than 1000000
) ELSE (
echo filename.txt filesize is less than 1000000
)
)
Not the cleanest solution, but it gets the job done.
As Lambdageek pointed out float multiplication is not associative and you can get less accuracy, but also when get better accuracy you can argue against optimisation, because you want a deterministic application. For example in game simulation client/server, where every client has to simulate the same world you want floating point calculations to be deterministic.
You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.
ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values
private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {
//OBJECT
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
//loop through all elements in object
for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
JsonElement array = entry.getValue();
findMyKeyValue(array, entry.getKey(), searchKey);
}
//ARRAY
} else if(element.isJsonArray()) {
//when an array is found keep 'key' as that is the array's name i.e. pass it down
JsonArray jsonArray = element.getAsJsonArray();
//loop through all elements in array
for (JsonElement childElement : jsonArray) {
findMyKeyValue(childElement, key, searchKey);
}
//NEITHER
} else {
//System.out.println("SKey: " + searchKey + " Key: " + key );
if (key.equals(searchKey)){
listOfValues.add(element.getAsString());
}
}
return listOfValues;
}
In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).
No, there's no way to do it. That would essentially be scoping in reverse.
Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.
Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.
You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this
object, which the prototype methods (along with everything else) will have access to. For example:
function Person(name, secret) {
// public
this.name = name;
// private
var secret = secret;
// public methods have access to private members
this.setSecret = function(s) {
secret = s;
}
this.getSecret = function() {
return secret;
}
}
// Must use getters/setters
Person.prototype.spillSecret = function() { alert(this.getSecret()); };
You don't need to specify PropertyConfigurator.configure("log4j.properties");
in your Log4J class, If you have already defined the log4j.properties in your project structure.
In case of Web Dynamic Project: -
You need to save your log4j.properties under WebContent -> WEB-INF -> log4j.properties
I hope this may help you.
Struggled with the same problem: Many applications, BUT make at least this part "pleasant": The trick is called Batch-Uninstall
.
So use one of these three programs i can recommend:
Take no.2 in imho, 1 is nice but sometimes encounters some bugs :-)
In my case it should be:
from multiprocessing import JoinableQueue
Since in python2, Queue has methods like .task_done()
, but in python3 multiprocessing.Queue
doesn't have this method, and multiprocessing.JoinableQueue
does.
Best one
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
Here is a solution that works on my machine : MacBook Pro running VIM 8.1
These commands will not delete your lines at the top or bottom of your buffer.
Using the actual symbols that Alt-J and Alt-K output is a workaround for their key-codes not mapping properly in my environment.
Throw this in the old .vimrc and see if works for you.
" Maps Alt-J and Alt-K to macros for moving lines up and down
" Works for modes: Normal, Insert and Visual
nnoremap ? :m .+1<CR>==
nnoremap ° :m .-2<CR>==
inoremap ? <Esc>:m .+1<CR>==gi
inoremap ° <Esc>:m .-2<CR>==gi
vnoremap ? :m '>+1<CR>gv=gv
vnoremap ° :m '<-2<CR>gv=gv
From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/
Adding this in the config.inc.php
file worked for me (under the last $cfg line):
$cfg['RowActionLinksWithoutUnique'] = 'true';
The file should be located in the phpMyAdmin
folder on your local computer
I have tested all of them but only the following worked out:
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent,
new MouseButtonEventHandler(SelectivelyHandleMouseButton), true);
EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent,
new RoutedEventHandler(SelectAllText), true);
EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotFocusEvent,
new RoutedEventHandler(GotFocus), true);
}
private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e)
{
var textbox = (sender as TextBox);
if (textbox != null)
{
int hc = textbox.GetHashCode();
if (hc == LastHashCode)
{
if (e.OriginalSource.GetType().Name == "TextBoxView")
{
e.Handled = true;
textbox.Focus();
LastHashCode = -1;
}
}
}
if (textbox != null) textbox.Focus();
}
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
private static int LastHashCode;
private static void GotFocus(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
LastHashCode = textBox.GetHashCode();
}
You just need 775
for /var/www/html
as long as you are logging in as myuser. The 7
octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:
chmod -R g+w /var/www/html
I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.
main() {
void something(char[]);
char s[100] = "";
something(s);
printf("%s", s);
}
void something(char s[]) {
// ... do something, pass the output to s
// no need to add s[i] = '\0'; because all unused slot is already set to '\0'
}
numpy.dot(a, b, out=None)
Dot product of two arrays.
For N dimensions it is a sum product over the last axis of a
and the second-to-last of b
.
Documentation: numpy.dot.
After generating a random number using a computer program, it is still consider as a random number if the picked number is a part or the full one of the initial one. But if it was changed, then mathematicians are not accept it as a random number and they can call it a biased number. But if you are developing a program for a simple task, this will not be a case to consider. But if you are developing a program to generate a random number for a valuable stuff such as lottery program, or gambling game, then your program will be rejected by the management if you are not consider about the above case.
So for those kind of people, here is my suggestion:
Generate a random number using Math.random()
.(say this n
)
Now for [0,10) ==> n*10 (i.e. one digit) and for[10,100) ==> n*100 (i.e. two digits) and so on. Here squire bracket indicates that boundary is inclusive and round bracket indicates boundary is exclusive.
Then remove the rest after the decimal point. (i.e. get floor) - using Math.floor(), this can be done.
If you know how to read random number table to pick a random number, you know above process(multiplying by 1, 10, 100 and so on) is not violates the one that I was mentioned at the beginning.( Because it changes only the place of the decimal point.)
Study the following example and develop it to your needs.
If you need a sample [0,9] then floor of n*10 is your answer and if need [0,99] then floor of n*100 is your answer and so on.
Now let enter into your role:
You've asked numbers among specific range. (In this case you are biased among that range. - By taking a number from [1,6] by roll a die, then you are biased into [1,6] but still it is a random if and only if die is unbiased.)
So consider your range ==> [78, 247] number of elements of the range = 247 - 78 + 1 = 170; (since both the boundaries are inclusive.
/*Mthod 1:*/
var i = 78, j = 247, k = 170, a = [], b = [], c, d, e, f, l = 0;
for(; i <= j; i++){ a.push(i); }
while(l < 170){
c = Math.random()*100; c = Math.floor(c);
d = Math.random()*100; d = Math.floor(d);
b.push(a[c]); e = c + d;
if((b.length != k) && (e < k)){ b.push(a[e]); }
l = b.length;
}
console.log('Method 1:');
console.log(b);
/*Method 2:*/
var a, b, c, d = [], l = 0;
while(l < 170){
a = Math.random()*100; a = Math.floor(a);
b = Math.random()*100; b = Math.floor(b);
c = a + b;
if(c <= 247 || c >= 78){ d.push(c); }else{ d.push(a); }
l = d.length;
}
console.log('Method 2:');
console.log(d);
Note: In method one, first I created an array which contains numbers that you need and then randomly put them into another array. In method two, generate numbers randomly and check those are in the range that you need. Then put it into an array. Here I generated two random numbers and used total of them to maximize the speed of the program by minimizing the failure rate that obtaining a useful number. However adding generated numbers will also give some biassness. So I would recommend my first method to generate random numbers within a specific range.
In both methods, your console will show the result.(Press f12 in Chrome to open the console)
This is a supplement answer related to the OP:
An easy and reliable solution to add Javadocs comments in Eclipse:
To use this tool, right-click on class and click on JAutodoc.
Try this code. It will work
Uri smsUri = Uri.parse("tel:123456");
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("sms_body", "sms text");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
Hope this will help you.
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
This difference is due to the behavior of Promises more than fetch()
specifically.
When a .then()
callback returns an additional Promise
, the next .then()
callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post
is provided by the Promise returned from response.json()
.
When you return a plain Object
, though, .then()
considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post
in this case is simply the Object
you created, which holds a Promise
in its data
property. The wait for that promise to be fulfilled is still incomplete.
It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal
and oldVal
refer to the same object. Vue will not keep an old copy of an object that you mutated.
Had you replaced the object with another one, Vue would have provided you with correct references.
Read the Note
section in the docs. (vm.$watch
)
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
If you want nice button with rounded corners, then use this class:
.link_button {_x000D_
-webkit-border-radius: 4px;_x000D_
-moz-border-radius: 4px;_x000D_
border-radius: 4px;_x000D_
border: solid 1px #20538D;_x000D_
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);_x000D_
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
background: #4479BA;_x000D_
color: #FFF;_x000D_
padding: 8px 12px;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#" class="link_button">Example</a>
_x000D_
Multiple folks have already pointed that
$ screen -ls
would list the screen sessions.
Here is another trick that may be useful to you.
If you add the following command as a last line in your .bashrc file on server xxx, then it will automatically reconnect to your screen session on login.
screen -d -r
Hope you find it useful.
open task manager, click in Service button and search MySql service, now you can stop and restart
Links and inputs are very different things, used for very different purposes. Looks to me like you need a button for the cancel:
<button>Cancel</button>
Or maybe an input:
<input type="button" value="Cancel"/>
Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:
All non-alphanumeric characters other than
\
,-
,^
(at the start) and the terminating]
are non-special in character classes, but it does no harm if they are escaped.
For more info about Java regular expressions, see the docs.
Select Name,
case
when Age = 13 then 'Thirteen'
when Age = 14 then 'Fourteen'
when Age = 15 then 'Fifteen'
when Age = 16 then 'Sixteen'
when Age = 17 then 'Seventeen'
when Age = 18 then 'Eighteen'
when Age = 19 then 'Nineteen'
else 'Adult'
end as AgeBracket
FROM Person
When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.
In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.
A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.
Taken from The Open University M362 Unit 3 "Interacting process" course material.
Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
With python 3.6, these two lines return a list (may be empty)
>>[int(x) for x in re.findall('\d+', your_string)]
Similar to
>>list(map(int, re.findall('\d+', your_string))
Do it like this:
Parentdivimage should have specified width and height, and its position should be:
position: relative;
Just inside the parentdivimage, next to other divs that parent contains you should put:
<a href="linkt.to.smthn.com"><span class="clickable"></span></a>
Then in css file:
.clickable {
height: 100%;
width: 100%;
left: 0;
top: 0;
position: absolute;
z-index: 1;
}
The span tag will fill out its parent block which is parentdiv, because of height and width set to 100%. Span will be on the top of all of surrounding elements because of setting z-index higher than other elements. Finally span will be clickable, because it's inside of an 'a' tag.
The following will only work if you do not have spaces in your input:
xargs -L 1
xargs --max-lines=1 # synonym for the -L option
from the man page:
-L max-lines
Use at most max-lines nonblank input lines per command line.
Trailing blanks cause an input line to be logically continued on
the next input line. Implies -x.
The error message you are getting is a result of Git still thinking that you have not resolved the merge conflicts. In fact, you already have, but you need to tell Git that you have done this by adding the resolved files to the index.
This has the side effect that you could actually just add the files without resolving the conflicts, and Git would still think that you have. So you should be diligent in making sure that you have really resolved the conflicts. You could even run the build and test the code before you commit.
How we can count the duplicated values?? either it is repeated 2 times or greater than 2. just count them, not group wise.
as simple as
select COUNT(distinct col_01) from Table_01
You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:
alias sshb="ssh buck@host"
To make the alias available in your terminal, you can either close and open your terminal, or run
source ~/.bashrc
Then you can connect by just typing in:
sshb
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic('../angularjs'), {default: 'angular.min.js'}); app.listen(3000);
Create a custom cell for your table cell and in the custom cell class.m put the code below, it will work fine. You need to place the desired color image in selectionBackground
UIImage.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
self.selectedBackgroundView=iview;
}
I think you are near to a possible solution.
Execute mainloop
in a separate thread and extend it with the property shutdown_flag
. The signal can be caught with signal.signal(signal.SIGTERM, handler)
in the main thread (not in a separate thread). The signal handler should set shutdown_flag
to True and wait for the thread to end with thread.join()
Good day
for some guys the order by in the sub-query is questionable. the order by in sub-query is a must to use if you need to delete some records based on some sorting. like
delete from someTable Where ID in (select top(1) from sometable where condition order by insertionstamp desc)
so that you can delete the last insertion form table. there are three way to do this deletion actually.
however, the order by in the sub-query can be used in many cases.
for the deletion methods that uses order by in sub-query review below link
i hope it helps. thanks you all
I'm in a particular situation where I do not have permissions to turn logging on, and wouldn't have permissions to see the logs if they were turned on. I could not add a trigger, but I did have permissions to call show processlist. So, I gave it a best effort and came up with this:
Create a bash script called "showsqlprocesslist":
#!/bin/bash
while [ 1 -le 1 ]
do
mysql --port=**** --protocol=tcp --password=**** --user=**** --host=**** -e "show processlist\G" | grep Info | grep -v processlist | grep -v "Info: NULL";
done
Execute the script:
./showsqlprocesslist > showsqlprocesslist.out &
Tail the output:
tail -f showsqlprocesslist.out
Bingo bango. Even though it's not throttled, it only took up 2-4% CPU on the boxes I ran it on. I hope maybe this helps someone.
As of 10/22/2019, I think the best answer is simply
conda install opencv
It appears opencv
is now in the main Anaconda
channel.
To see which packages (including opencv
) are in the main Anaconda
channel go to Anaconda Package Lists and follow the link corresponding to your python version and os version.
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
This works on firefox v-27.0
.buttonClassName:focus {
outline:none;
}
Increasing the font size on a text box will usually expand its size automatically.
<input type="text" style="font-size:16pt;">
If you want to set a height that is not proportional to the font size, I would recommend using something like the following. This prevents browsers like IE from rendering the text inside at the top rather than vertically centered.
.form-text{
padding:15px 0;
}
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
This will not only change the max_retries but also enable a backoff strategy which makes requests to all http:// addresses sleep for a period of time before retrying (to a total of 5 times):
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
s = requests.Session()
retries = Retry(total=5,
backoff_factor=0.1,
status_forcelist=[ 500, 502, 503, 504 ])
s.mount('http://', HTTPAdapter(max_retries=retries))
s.get('http://httpstat.us/500')
As per documentation for Retry
: if the backoff_factor is 0.1, then sleep() will sleep for [0.1s, 0.2s, 0.4s, ...] between retries. It will also force a retry if the status code returned is 500, 502, 503 or 504.
Various other options to Retry
allow for more granular control:
MaxRetryError
, or to return a response with a response code in the 3xx range.NB: raise_on_status is relatively new, and has not made it into a release of urllib3 or requests yet. The raise_on_status keyword argument appears to have made it into the standard library at most in python version 3.6.
To make requests retry on specific HTTP status codes, use status_forcelist. For example, status_forcelist=[503] will retry on status code 503 (service unavailable).
By default, the retry only fires for these conditions:
TimeoutError
HTTPException
raised (from http.client in Python 3 else httplib).
This seems to be low-level HTTP exceptions, like URL or protocol not
formed correctly.SocketError
ProtocolError
Notice that these are all exceptions that prevent a regular HTTP response from being received. If any regular response is generated, no retry is done. Without using the status_forcelist, even a response with status 500 will not be retried.
To make it behave in a manner which is more intuitive for working with a remote API or web server, I would use the above code snippet, which forces retries on statuses 500, 502, 503 and 504, all of which are not uncommon on the web and (possibly) recoverable given a big enough backoff period.
EDITED: Import Retry
class directly from urllib3.
You can use this:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
Besides, you might want to use -iname
instead of -name
to catch files with ".PDF" (upper-case) extension as well.
The way you're doing it now isn't faster (apart from it being an indefinite loop, I guess you meant to do i--
.
If you want to make it faster do:
for (i = 10; i--;) {
//super fast loop
}
of course you wouldn't notice it on such a small loop. The reason it's faster is because you're decrementing i while checking that it's "true" (it evaluates to "false" when it reaches 0)
Other solutions attach a counter attribute to the function, usually with convoluted logic to handle the initialization. This is inappropriate for new code.
In Python 3, the right way is to use a nonlocal
statement:
counter = 0
def foo():
nonlocal counter
counter += 1
print(f'counter is {counter}')
See PEP 3104 for the specification of the nonlocal
statement.
If the counter is intended to be private to the module, it should be named _counter
instead.
Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
It seems that GSon don't support JAXB. By using JAXB annotated class to create or process the JSON message, I can share the same class to create the Restful Web Service interface by using spring MVC.
One more solution:
<a data-toggle="modal" data-target="#exampleModalCenter">
<span
class="tags"
data-toggle="tooltip"
data-placement="right"
title="Tooltip text"
>
Text
</span>
</a>
It worked for me. in MVC 5
in ~\Global.asax
void Application_Error(object sender, EventArgs e)
{
FTools.LogException();
Response.Redirect("/Error");
}
in ~\Controllers
Create ErrorController.cs
using System.Web.Mvc;
namespace MVC_WebApp.Controllers
{
public class ErrorController : Controller
{
// GET: Error
public ActionResult Index()
{
return View("Error");
}
}
}
in ~\Models
Create FunctionTools.cs
using System;
using System.Web;
namespace MVC_WebApp.Models
{
public static class FTools
{
private static string _error;
private static bool _isError;
public static string GetLastError
{
get
{
string cashe = _error;
HttpContext.Current.Server.ClearError();
_error = null;
_isError = false;
return cashe;
}
}
public static bool ThereIsError => _isError;
public static void LogException()
{
Exception exc = HttpContext.Current.Server.GetLastError();
if (exc == null) return;
string errLog = "";
errLog += "**********" + DateTime.Now + "**********\n";
if (exc.InnerException != null)
{
errLog += "Inner Exception Type: ";
errLog += exc.InnerException.GetType() + "\n";
errLog += "Inner Exception: ";
errLog += exc.InnerException.Message + "\n";
errLog += "Inner Source: ";
errLog += exc.InnerException.Source + "\n";
if (exc.InnerException.StackTrace != null)
{
errLog += "\nInner Stack Trace: " + "\n";
errLog += exc.InnerException.StackTrace + "\n";
}
}
errLog += "Exception Type: ";
errLog += exc.GetType().ToString() + "\n";
errLog += "Exception: " + exc.Message + "\n";
errLog += "\nStack Trace: " + "\n";
if (exc.StackTrace != null)
{
errLog += exc.StackTrace + "\n";
}
_error = errLog;
_isError = true;
}
}
}
in ~\Views
Create Folder Error
and in ~\Views\Error
Create Error.cshtml
@using MVC_WebApp.Models
@{
ViewBag.Title = "Error";
if (FTools.ThereIsError == false)
{
if (Server.GetLastError() != null)
{
FTools.LogException();
}
}
if (FTools.ThereIsError == false)
{
<br />
<h1>No Problem!</h1>
}
else
{
string log = FTools.GetLastError;
<div>@Html.Raw(log.Replace("\n", "<br />"))</div>
}
}
If you enter this address localhost/Error
Source: Microsoft ASP.Net
And if you want to vary the speed and include callbacks simply add them like this :
jQuery.fn.extend({
slideRightShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, speed, callback);
});
},
slideRightHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, speed, callback);
});
}
});
A little bit late, but all the answers were specific to linux.
If you need also unix, then you need this:
char * getExecPath (char * path,size_t dest_len, char * argv0)
{
char * baseName = NULL;
char * systemPath = NULL;
char * candidateDir = NULL;
/* the easiest case: we are in linux */
size_t buff_len;
if (buff_len = readlink ("/proc/self/exe", path, dest_len - 1) != -1)
{
path [buff_len] = '\0';
dirname (path);
strcat (path, "/");
return path;
}
/* Ups... not in linux, no guarantee */
/* check if we have something like execve("foobar", NULL, NULL) */
if (argv0 == NULL)
{
/* we surrender and give current path instead */
if (getcwd (path, dest_len) == NULL) return NULL;
strcat (path, "/");
return path;
}
/* argv[0] */
/* if dest_len < PATH_MAX may cause buffer overflow */
if ((realpath (argv0, path)) && (!access (path, F_OK)))
{
dirname (path);
strcat (path, "/");
return path;
}
/* Current path */
baseName = basename (argv0);
if (getcwd (path, dest_len - strlen (baseName) - 1) == NULL)
return NULL;
strcat (path, "/");
strcat (path, baseName);
if (access (path, F_OK) == 0)
{
dirname (path);
strcat (path, "/");
return path;
}
/* Try the PATH. */
systemPath = getenv ("PATH");
if (systemPath != NULL)
{
dest_len--;
systemPath = strdup (systemPath);
for (candidateDir = strtok (systemPath, ":"); candidateDir != NULL; candidateDir = strtok (NULL, ":"))
{
strncpy (path, candidateDir, dest_len);
strncat (path, "/", dest_len);
strncat (path, baseName, dest_len);
if (access(path, F_OK) == 0)
{
free (systemPath);
dirname (path);
strcat (path, "/");
return path;
}
}
free(systemPath);
dest_len++;
}
/* again someone has use execve: we dont knowe the executable name; we surrender and give instead current path */
if (getcwd (path, dest_len - 1) == NULL) return NULL;
strcat (path, "/");
return path;
}
EDITED: Fixed the bug reported by Mark lakata.
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
@Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml
code to this:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"> <!-- Just add this line -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
Now is possible to type tag:nameofthetag or app:nameoftheapp to filter without adding new filters to the saved filters bar
If you're only looking for a webkit version this is nifty: http://s3.amazonaws.com/37assets/svn/463-single_spinner.html from http://37signals.com/svn/posts/2577-loading-spinner-animation-using-css-and-webkit
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
One way to do this is to have your main version of php set up with mod_php and run all of the others through fast cgi on different ports (i.e. 81, 82, 83 etc). This won't guarantee totally consistent behavior though.
Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.
In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).
My evil workaround (don't do this in production!):
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
According to docs calling SSLContext constructor directly should work, too. I haven't tried that.
Loop through the Items and Add to the Collection. You can use the Add
method
List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
string qry="SELECT Column1 FROM Table1";
var cmd= new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
con.Open();
using (SqlDataReader objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
//I would also check for DB.Null here before reading the value.
string item= objReader.GetString(objReader.GetOrdinal("Column1"));
items.Add(item);
}
}
}
}
you may want it to be ==, but 123.4444444444443 != 123.4444444444442
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
All links to the Azure Active Directory Connection page now seem to be invalid.
I had an older version of Azure AD installed too, this is what worked for me. Install this.
Run these in an elevated PS session:
uninstall-module AzureAD # this may or may not be needed
install-module AzureAD
install-module AzureADPreview
install-module MSOnline
I was then able to log in and run what I needed.
Use git revert
for reverting your push.
git-revert - Revert some existing commits
git revert [--edit | --no-edit] [-n] [-m parent-number] [-s] <commit>... git revert --continue git revert --quit git revert --abort
Revert the changes that the related patches introduce, and record some new commits that record them. This requires your working tree to be clean (no modifications from the HEAD commit).
<script type="text/javascript">
function GetContent(idUser){
$.ajaxSetup({
url: 'ping.php'
});
$.ajax({
type: "POST",
url: "blablabla.php",
dataType: "text",
data: ({ParamUserID:idUser}),// here we def wich variabe is assiciated
contentType: "application/x-www-form-urlencoded; charset=iso-8859-1",
success: function(html) {
$('#user_specified_content').html(html);
}
});
}
</script>
This is the script from which I get my content from the blabla.php page.
When I receive my data on success my accents don't appear.
I have found a super good working solution by my own for fetching data with accents on the fetched data from .success
function
On my blabla page. I did this to bring a solution to my problem:
I use utf8_encode(place your data here)
in my php file. See it in action below:
while( $row = sqlsrv_fetch_array($recordset) )
{
<option value="<?php echo $row["xyz"]; ?>"><?php echo utf8_encode($row["gName"]) . ' | ' . utf8_encode($row["gManagerName"]); ?></option>
}
Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.
In the UK, there are a few government standards which deal successfully with the bulk of the UK population -- the Passport Office, the Driver & Vehicle Licensing Agency, the Deed Poll office, and the NHS. They use different standards, obviously.
Changing your name by Deed Poll allows 300 characters;
There is no legal limit on the length of your name, but we impose a limit of 300 characters (including spaces) for your full name.
The NHS uses 70 characters for patient names
PATIENT NAME
Format/length: max an70
The Passport Office allows 30+30 first/last and Driving Licenses (DVLA) is 30 total.
Note that other organisations will have their own restrictions about what they will show on the documents they produce — for HM Passport Office the limit is 30 characters each for your forename and your surname, and for the DVLA the limit is 30 characters in total for your full name.
In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:
public class ClientHandler implements SOAPHandler<SOAPMessageContext>{
public boolean handleMessage(final SOAPMessageContext soapMessageContext)
{
final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outInd.booleanValue())
{
try
{
soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
return true;
}
}
Just a suggestion SharePoint 2013 online & on-prem file encoding is UTF-8 BOM. Make sure your file is UTF-8 BOM, otherwise your uploaded html and scripts may not rendered correctly in browser.
Complete Binary Tree: All levels are completely filled except the lowest level and one main thing all the leaf elements must have left child. Strict Binary Tree: In this tree every non-leaf node has no child i.e. neither left nor right. Full Binary Tree: Every Node has either zero child or Two children (never having single child).
This script worked for me in CentOS to list all crons in the environment:
sudo cat /etc/passwd | sed 's/^\([^:]*\):.*$/sudo crontab -u \1 -l 2>\&1/' | grep -v "no crontab for" | sh
This answer worked for me:
pipeline {
agent any
stages {
stage("Run unit tests"){
steps {
script {
try {
sh '''
# Run unit tests without capturing stdout or logs, generates cobetura reports
cd ./python
nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
cd ..
'''
} finally {
junit 'nosetests.xml'
}
}
}
}
stage ('Speak') {
steps{
echo "Hello, CONDITIONAL"
}
}
}
}
The reason for the exception is that and
implicitly calls bool
. First on the left operand and (if the left operand is True
) then on the right operand. So x and y
is equivalent to bool(x) and bool(y)
.
However the bool
on a numpy.ndarray
(if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool()
call is implicit in and
, but also in if
, while
, or
, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool
calls, for example 2 < x < 10
is just another way of writing 2 < x and x < 10
. And the and
will call bool
: bool(2 < x) and bool(x < 10)
.
The element-wise equivalent for and
would be the np.logical_and
function, similarly you could use np.logical_or
as equivalent for or
.
For boolean arrays - and comparisons like <
, <=
, ==
, !=
, >=
and >
on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and
(&
operator)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or
(|
operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:
1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
3) System variable create: C:\program files (x86)\java\jre6\bin\
4) Anywhere you type java -version
it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.
Changing this line:
var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
To fix the dimensions.
Try this one -
"SELECT
ID, Salt, password, BannedEndDate
, (
SELECT COUNT(1)
FROM dbo.LoginFails l
WHERE l.UserName = u.UserName
AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"
If you use svn+ssh, you can copy your public ssh key to the remote machine:
ssh-copy-id user@remotehost
I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.
As per Apple's documentation:
(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;
Description:
Tells a child controller its appearance is about to change.
If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:
, viewWillDisappear:
, viewDidAppear:
, or viewDidDisappear:
directly.
(void)endAppearanceTransition;
Description:
Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.
Sample code:
(void)applicationDidEnterBackground:(UIApplication *)application
{
[self.window.rootViewController beginAppearanceTransition: NO animated: NO]; // I commented this line
[self.window.rootViewController endAppearanceTransition]; // I commented this line
}
Question: How I fixed?
Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement