You got a ninja ')'.
Try :
<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
session_status() === PHP_SESSION_ACTIVE ?: session_start();
Closed Game
Not removing but creating a new List
without that element with LINQ:
// remove
users = users.Where(u => u.userId != 123).ToList();
// new list
var modified = users.Where(u => u.userId == 123).ToList();
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
If the only thing you want to do is drop in an image onto a widget withouth the complexity of the graphics API, you can also just create a new QWidget and set the background with StyleSheets. Something like this:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ... QWidget *pic = new QWidget(this); pic->setStyleSheet("background-image: url(test.png)"); pic->setGeometry(QRect(50,50,128,128)); ... }
If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.
set JAVA_HOME=C:\Program Files\Java\jdk1.6.x
If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.
JAVA_HOME=/usr/java/jdk1.6.x
select columns
from table
where (
column like 'a%'
or column like 'b%' )
order by column asc
I use SweetAlert, It's Awesome, You will get lots of customization option as well as all callbacks
swal("Here's a message!", "It's pretty, isn't it?");
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.
-AD.
because the second query is looking for rows with the id's 1 OR 2 OR 3, the first query is looking for a one of the comma delimited values to exist in companyID,
and another problem here is you aren't joining the tables on a common key in your where so you are going to get a mutation of rows that = count(table1) * count(table2);
Your problem really exists with part 2 of my answer. (with your second query)
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
Outdated answer
You are subtracting the wrong number:
Use Calendar
instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
I have a similar problem specifucally : ERR! enoent ENOENT: no such file or directory, chmod 'node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/bin/sshpk-conv I tried all above solutions but no luck. I was using vagrant box, and the project was in a shared folder. The problems seems to be only there, when I move the project to another not shared folder (woth host), voila! problem solved. Just in case another person was using also vagrant
Sounds a bit familiar with my problem: aapt not found under the right path
I needed to clean all open projects to get it working again...
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Sure:
try {
throw new Exception('Something bad');
} catch (Exception $e) {
// Do nothing
}
You might want to go have a read of the PHP documentation on Exceptions.
Another way of doing the same but with dplyr
library(dplyr)
subdf <- df %>% filter(numbers <= 3) %>% droplevels()
str(subdf)
Edit:
Also Works ! Thanks to agenis
subdf <- df %>% filter(numbers <= 3) %>% droplevels
levels(subdf$letters)
That's what have worked for me, I wanted to commit only one Cordova plugin to the repo:
...
plugins/*
!plugins/cordova-plugin-app-customization
By default X-Frame-Options
is set to denied, to prevent clickjacking attacks. To override this, you can add the following into your spring security config
<http>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
</http>
Here are available options for policy
For more information take a look here.
And here to check how you can configure the headers using either XML or Java configs.
Note, that you might need also to specify appropriate strategy
, based on needs.
Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>
bool computeHash(const std::string& unhashed, std::string& hashed)
{
bool success = false;
EVP_MD_CTX* context = EVP_MD_CTX_new();
if(context != NULL)
{
if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
{
if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
{
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
{
std::stringstream ss;
for(unsigned int i = 0; i < lengthOfHash; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
hashed = ss.str();
success = true;
}
}
}
EVP_MD_CTX_free(context);
}
return success;
}
int main(int, char**)
{
std::string pw1 = "password1", pw1hashed;
std::string pw2 = "password2", pw2hashed;
std::string pw3 = "password3", pw3hashed;
std::string pw4 = "password4", pw4hashed;
hashPassword(pw1, pw1hashed);
hashPassword(pw2, pw2hashed);
hashPassword(pw3, pw3hashed);
hashPassword(pw4, pw4hashed);
std::cout << pw1hashed << std::endl;
std::cout << pw2hashed << std::endl;
std::cout << pw3hashed << std::endl;
std::cout << pw4hashed << std::endl;
return 0;
}
The advantage of this higher level interface is that you simply need to swap out the EVP_sha256()
call with another digest's function, e.g. EVP_sha512()
, to use a different digest. So it adds some flexibility.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
I've always wondered how costly it is to always assume that invoke is required...
private void OnCoolEvent(CoolObjectEventArgs e)
{
BeginInvoke((o,e) => /*do work here*/,this, e);
}
I found a pretty simple way to handle "one copy of script per system". It doesn't allow me to run multiple copies of the script from many accounts though (on standard Linux that is).
Solution:
At the beginning of script, I gave:
pidof -s -o '%PPID' -x $( basename $0 ) > /dev/null 2>&1 && exit
Apparently pidof works great in a way that:
ps -C ...
grep -v grep
( or anything similar )And it doesn't rely on lockfiles, which for me is a big win, because relaying on them means you have to add handling of stale lockfiles - which is not really complicated, but if it can be avoided - why not?
As for checking with "one copy of script per running user", i wrote this, but I'm not overly happy with it:
(
pidof -s -o '%PPID' -x $( basename $0 ) | tr ' ' '\n'
ps xo pid= | tr -cd '[0-9\n]'
) | sort | uniq -d
and then I check its output - if it's empty - there are no copies of the script from same user.
I have been using this one....
/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/
It allows that +
before @
([email protected])
you can use LayoutInflater to inflate your dynamic data as a layout file.
UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it.
after that create a layout file that you want to inflate. at last in your onBindViewHolder
method in your "RAdaper" class. write these codes :
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);
after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.
I just wanted to provide a bit of an update/special case since it looks like people still come here. If you're using a multi-index or otherwise using an index-slicer the inplace=True option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of pandas 0.15):
idx = pd.IndexSlice
df.loc[idx[:,mask_1],idx[mask_2,:]].fillna(value=0,inplace=True)
The "problem" is that the chaining breaks the fillna ability to update the original dataframe. I put "problem" in quotes because there are good reasons for the design decisions that led to not interpreting through these chains in certain situations. Also, this is a complex example (though I really ran into it), but the same may apply to fewer levels of indexes depending on how you slice.
The solution is DataFrame.update:
df.update(df.loc[idx[:,mask_1],idx[[mask_2],:]].fillna(value=0))
It's one line, reads reasonably well (sort of) and eliminates any unnecessary messing with intermediate variables or loops while allowing you to apply fillna to any multi-level slice you like!
If anybody can find places this doesn't work please post in the comments, I've been messing with it and looking at the source and it seems to solve at least my multi-index slice problems.
Try to change your label frame size height and width so your text not cut.
[label setframe:CGRect(x,y,widht,height)];
This code will match a US or Canadian phone number, and will also make sure that it is a valid area code and exchange:
^((\+1)?[\s-]?)?\(?[2-9]\d\d\)?[\s-]?[2-9]\d\d[\s-]?\d\d\d\d
Create rectangle.xml
using Shape Drawable Like this put in to your Drawable Folder...
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="12px"/>
<stroke android:width="2dip" android:color="#000000"/>
</shape>
put it in to an ImageView
<ImageView
android:id="@+id/rectimage"
android:layout_height="150dp"
android:layout_width="150dp"
android:src="@drawable/rectangle">
</ImageView>
Hope this will help you.
Basically, you can't run it from a UNC path without seeing that message.
What I usually do is just put a CLS
at the top of the script so I don't have to see that message. Then, specify the full path to files in the network share that you need to use.
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.
The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.
Thanks, that helped me. I made some improvements and wrapped that in a helper script "finalurl":
#!/bin/bash
curl $1 -s -L -I -o /dev/null -w '%{url_effective}'
-o
output to /dev/null
-I
don't actually download, just discover the final URL-s
silent mode, no progressbarsThis made it possible to call the command from other scripts like this:
echo `finalurl http://someurl/`
That's how I just did it on OsX 10.10.3
for f in *.txt; do (cat $f; echo '') >> fullData.txt; done
since the simple 'echo' command with no params ended up in no new lines inserted.
It is kind of a workaround but works like a charm. Just add <option value="" style="display: none"></option>
as a filler. Like in:
<select size="4" ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
<option value="" style="display: none"></option>
</select>
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
You can specify the constraints and defaults in a CREATE TABLE AS SELECT, but the syntax is as follows
create table t1 (id number default 1 not null);
insert into t1 (id) values (2);
create table t2 (id default 1 not null)
as select * from t1;
That is, it won't inherit the constraints from the source table/select. Only the data type (length/precision/scale) is determined by the select.
Use the osascript
command in your code as icktoofay mentioned: osascript -e 'tell application "Terminal" to quit'
Then, open Terminal preferences, go to Settings > Shell, and set "Prompt before closing:" to "Never." Terminal should now quit completely (not remain open in your dock) and ignore the prompt before quitting. If you have only one Terminal window open and the osascript
command is your last line of code, it should wait for whatever command you ran before to finish.
This would not be ideal if you are running scripts in the same window or other windows in the background (for instance, you may run a command in the background and continue using the current window for other commands if the first command is followed by an ampersand); be careful!
If you wrap the osascript
code in a shell script file, you can probably call it with whatever pithy file-name you give it---as long as it is in Terminal's search path (run echo $PATH
to see where Terminal looks for scripts).
Yes, you can do almost that:
SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...
Two comments:
and
and or
for logical operations in Python.The whole thing should look like:
<form enctype='multipart/form-data' method='POST' action='submitFormTo.php'>
<input type='file' name='files[]' multiple />
<button type='submit'>Submit</button>
</form>
Make sure you have the enctype='multipart/form-data'
attribute in your <form>
tag, or you can't read the files on the server side after submission!
I took aberke's solution and modified it to suit my taste.
My Code Pen
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('exampleController',_x000D_
function exampleController($scope) {_x000D_
$scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}};_x000D_
$scope.homePhonePrompt = "Home Phone";_x000D_
});_x000D_
_x000D_
myApp_x000D_
/*_x000D_
Intended use:_x000D_
<phone-number placeholder='prompt' model='someModel.phonenumber' />_x000D_
Where: _x000D_
someModel.phonenumber: {String} value which to bind formatted or unformatted phone number_x000D_
_x000D_
prompt: {String} text to keep in placeholder when no numeric input entered_x000D_
*/_x000D_
.directive('phoneNumber',_x000D_
['$filter',_x000D_
function ($filter) {_x000D_
function link(scope, element, attributes) {_x000D_
_x000D_
// scope.inputValue is the value of input element used in template_x000D_
scope.inputValue = scope.phoneNumberModel;_x000D_
_x000D_
scope.$watch('inputValue', function (value, oldValue) {_x000D_
_x000D_
value = String(value);_x000D_
var number = value.replace(/[^0-9]+/g, '');_x000D_
scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension);_x000D_
scope.phoneNumberModel = scope.inputValue;_x000D_
});_x000D_
}_x000D_
_x000D_
return {_x000D_
link: link,_x000D_
restrict: 'E',_x000D_
replace: true,_x000D_
scope: {_x000D_
phoneNumberPlaceholder: '@placeholder',_x000D_
phoneNumberModel: '=model',_x000D_
allowExtension: '=extension'_x000D_
},_x000D_
template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />'_x000D_
};_x000D_
}_x000D_
]_x000D_
)_x000D_
/* _x000D_
Format phonenumber as: (aaa) ppp-nnnnxeeeee_x000D_
or as close as possible if phonenumber length is not 10_x000D_
does not allow country code or extensions > 5 characters long_x000D_
*/_x000D_
.filter('phoneNumber', _x000D_
function() {_x000D_
return function(number, allowExtension) {_x000D_
/* _x000D_
@param {Number | String} number - Number that will be formatted as telephone number_x000D_
Returns formatted number: (###) ###-#### x #####_x000D_
if number.length < 4: ###_x000D_
else if number.length < 7: (###) ###_x000D_
removes country codes_x000D_
*/_x000D_
if (!number) {_x000D_
return '';_x000D_
}_x000D_
_x000D_
number = String(number);_x000D_
number = number.replace(/[^0-9]+/g, '');_x000D_
_x000D_
// Will return formattedNumber. _x000D_
// If phonenumber isn't longer than an area code, just show number_x000D_
var formattedNumber = number;_x000D_
_x000D_
// if the first character is '1', strip it out _x000D_
var c = (number[0] == '1') ? '1 ' : '';_x000D_
number = number[0] == '1' ? number.slice(1) : number;_x000D_
_x000D_
// (###) ###-#### as (areaCode) prefix-endxextension_x000D_
var areaCode = number.substring(0, 3);_x000D_
var prefix = number.substring(3, 6);_x000D_
var end = number.substring(6, 10);_x000D_
var extension = number.substring(10, 15);_x000D_
_x000D_
if (prefix) {_x000D_
//formattedNumber = (c + "(" + area + ") " + front);_x000D_
formattedNumber = ("(" + areaCode + ") " + prefix);_x000D_
}_x000D_
if (end) {_x000D_
formattedNumber += ("-" + end);_x000D_
}_x000D_
if (allowExtension && extension) {_x000D_
formattedNumber += ("x" + extension);_x000D_
}_x000D_
return formattedNumber;_x000D_
};_x000D_
}_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="exampleController">_x000D_
<p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p>_x000D_
<p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p>_x000D_
<phone-number id="homePhone"_x000D_
class="form-control" _x000D_
placeholder="Home Phone" _x000D_
model="user.profile.HomePhone"_x000D_
ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" />_x000D_
</div>
_x000D_
Just to go a little bit further in the matter, you can also set a bitmap directly, like this:
ImageView imageView = new ImageView(this);
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);
Of course, this technique is only useful if you need to change the image.
The problem is that you thought your jsonString is a dictionary. It's not.
It's an array of dictionaries.
In raw json strings, arrays begin with [
and dictionaries begin with {
.
I used your json string with below code :
let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
and I am getting the output :
[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
Password Requirement :
Passwords must include characters from at least two (2) of these groupings: alpha, numeric, and special characters.
^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])|(?=.{8,})(?=.*\d)(?=.*[!@#$%^&])|(?=.{8,})(?=.*[a-zA-Z])(?=.*[!@#$%^&]).*$
I tested it and it works
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde
functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
// it works in bootstrap 4, there was some changes in documentation.We dont need prefix col-, just offset-lg-3 e.g.
<div class="row">
<div class="offset-lg-3 col-lg-6"> Some content...
</div>
</div>
// here doc: http://v4-alpha.getbootstrap.com/layout/grid/#example-offsetting-columns
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
DataTable dt = new DataTable();
DataSet Gds = new DataSet();
// DataColumn colm1 = new DataColumn();
//DataColumn colm2 = new DataColumn();
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ExpId", typeof(int));
dt.Columns.Add("FirstName", typeof(string));
}
protected void BtnLoad_Click(object sender, EventArgs e)
{
// gvLoad is Grid View Id
if (gvLoad.Rows.Count == 0)
{
Gds.Tables.Add(tblLoad());
}
else
{
dt = tblGridRow();
dt.Rows.Add(tblRow());
Gds.Tables.Add(dt);
}
gvLoad.DataSource = Gds;
gvLoad.DataBind();
}
protected DataTable tblLoad()
{
dt.Rows.Add(tblRow());
return dt;
}
protected DataRow tblRow()
{
DataRow dr;
dr = dt.NewRow();
dr["Exp Id"] = Convert.ToInt16(txtId.Text);
dr["First Name"] = Convert.ToString(txtName.Text);
return dr;
}
protected DataTable tblGridRow()
{
DataRow dr;
for (int i = 0; i < gvLoad.Rows.Count; i++)
{
if (gvLoad.Rows[i].Cells[0].Text != null)
{
dr = dt.NewRow();
dr["Exp Id"] = gvLoad.Rows[i].Cells[1].Text.ToString();
dr["First Name"] = gvLoad.Rows[i].Cells[2].Text.ToString();
dt.Rows.Add(dr);
}
}
return dt;
}
protected void btn_Click(object sender, EventArgs e)
{
dt = tblGridRow();
dt.Rows.Add(tblRow());
Session["tab"] = dt;
// Response.Redirect("Default.aspx");
}
protected void gvLoad_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt = tblGridRow();
dt.Rows.RemoveAt(e.RowIndex);
gvLoad.DataSource = dt;
gvLoad.DataBind();
}
}
To understand the use of "SET SERVEROUTPUT ON" I will take an example
DECLARE
a number(10) :=10;
BEGIN
dbms_output.put_line(a) ;
dbms_output.put_line('Hello World ! ') ;
END ;
With an output : PL/SQl procedure successfully completed i.e without the expected output
And the main reason behind is that ,whatever we pass inside dbms_output.put_line(' ARGUMENT '/VALUES) i.e. ARGUMENT/VALUES , is internally stored inside a buffer in SGA(Shared Global Area ) memory area upto 2000 bytes .
*NOTE :***However one should note that this buffer is only created when we use **dbms_output package. And we need to set the environment variable only once for a session !!
And in order to fetch it from that buffer we need to set the environment variable for the session . It makes a lot of confusion to the beginners that we are setting the server output on ( because of its nomenclature ) , but unfortunately its nothing like that . Using SET SERVER OUTPUT ON are just telling the PL/SQL engine that
*Hey please print the ARGUMENT/VALUES that I will be passing inside dbms_output.put_line
and in turn PL/SQl run time engine prints the argument on the main console .
I think I am clear to you all . Wish you all the best . To know more about it with the architectural structure of Oracle Server Engine you can see my answer on Quora http://qr.ae/RojAn8
And to answer your question "One should use SET SERVER OUTPUT in the beginning of the session. "
If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).
If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").
Once the edition is done, hit ESC again, then type :wq
to save your work or :q!
to quit without saving.
For quick reference, here you have a text-based cheat sheet.
You can create the path if it doesn't exist yet with a method like the following:
using System.IO;
private void CreateIfMissing(string path)
{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}
I got this error when I did a Response.Redirect
after a successful login of the user.
I fixed it by doing a FormsAuthentication.RedirectFromLoginPage
instead.
I formerly voted to close this question as off-topic but actually I changed my mind as this is quite nice visual effect which, unfortunately, is not yet part of support library. It will most likely show up in future update, but there's no time frame announced.
Luckily there are few custom implementations already available:
including Materlial themed widget sets compatible with older versions of Android:
so you can try one of these or google for other "material widgets" or so...
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Yes Java allows vargs
in method parameter .
public class Varargs
{
public int add(int... numbers)
{
int result = 1;
for(int number: numbers)
{
result= result+number;
} return result;
}
}
I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.
<ComboBox Name="CategoryList"
DisplayMemberPath="CategoryName"
SelectedItem="{Binding Path=CategoryParent}"
SelectedValue="{Binding Path=CategoryParent.ID}"
SelectedValuePath="ID">
See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.
Set the following user environment variables (== environment variables of type user variables)
JAVA_HOME :
C:\Program Files\Java\jdk1.8.0_112
JDK_HOME :
%JAVA_HOME%
JRE_HOME :
%JAVA_HOME%\jre
CLASSPATH :
.;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
PATH :
your-unique-entries;%JAVA_HOME%\bin
(make sure that the longish your-unique-entries
does not contain any other references to another Java installation folder.Note for Windows users on 64-bit systems:
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
Notice that these environment variables are derived from the "root" environment variable JAVA_HOME
. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME
to the fresh installation.
There is a blogpost explaining the rationale behind all these environment variables.
JAVA_TOOL_OPTIONS
with value -Dfile.encoding="UTF-8"
. This ensures that Java (and tools such as Maven) will run with a Charset.defaultCharset()
of UTF-8
(instead of the default Windows-1252
). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8.Path
an entry C:\ProgramData\Oracle\Java\javapath;
. I anecdotally noticed that the links in that directory didn't get updated during an JDK installation update. So it's best to remove C:\ProgramData\Oracle\Java\javapath;
from the Path
system environment variable in order to have a consistent environment.The compiler should make them all the same in the long run. Pick a standard so that your code will be easy to read, and stick with it.
There is no concept of folders or directories in S3. You can create file names like "abc/xys/uvw/123.jpg"
, which many S3 access tools like S3Fox
show like a directory structure, but it's actually just a single file in a bucket.
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
You can animate it after the fadeIn completes using the callback as shown below:
$("#Friends").fadeIn('slow',function(){
$(this).animate({'top': '-=30px'},'slow');
});
I had the same issue and resolved it by adding the /bin
directory location to the PATH Environment Variable.
Search for the file location where Git was installed, mine is C:\Users\(My UserName)\AppData\Local\GitHub
. It may also be C:\Program Files (x86)\Git
Once you have the location of Git you should see a /bin
sub-folder. It may be in a PortableGit folder (mine is
PortableGit_015aa71ef18c047ce8509ffb2f9e4bb0e3e73f13
). Copy this path.
Go to Control Panel > System > System Protection > Advanced > Environment Variables
Choose PATH, click edit and paste the bin path there. If there are already any values in your PATH paste your Git path at the end separated with a semi-colon.
Now you can access Git command from CMD.
The simplest technique:
If your form action attribute is omitted, you can send a form to the same HTML file without actually using a GET HTTP access, just by using onClick on the button used for submitting the form. Then the form fields are in the elements array document.FormName.elements . Each element in that array has a value attribute containing the string the user provided (For INPUT elements). It also has id and name attributes, containing the id and/or name provided in the form child elements.
Open terminal and type:
$ sudo gem update cocoapods
Remove all the pods from your project (tricky part):
Manually
Automatically using CocoaPods De-Integrate
Install
$ [sudo] gem install cocoapods-deintegrate
Run
$ pod deintegrate
Here we are going through at installing the Pods again
Change your location your directory
$ cd yourprojectdirectory
Edit podfile by adding lines you need to it
$ open -a Xcode podfile
or
$ nano podfile
FINALLY install the pod again
$ pod install
Hope this helps
The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll()
.
var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove();
The querySelectorAll()
function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var
, then you can pass it as an argument to jquery remove()
.
just use \xb0 (in a string);
python will convert it automatically
As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell()
to see where in the file the pointer is and file.seek
to set the pointer. For example:
>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'
Also, you should know that file.readlines()
reads the whole file and stores it as a list. That's useful to know because you can replace:
for line in file.readlines():
#do stuff
file.seek(0)
for line in file.readlines():
#do more stuff
with:
lines = file.readlines()
for each_line in lines:
#do stuff
for each_line in lines:
#do more stuff
You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:
for line in file:
#do stuff
You need no new functions nor new modules. You simply need to execute the module you're calling if you don't want to use namespace.
module.exports = function() {
this.sum = function(a,b) { return a+b };
this.multiply = function(a,b) { return a*b };
//etc
}
or in any other .js like myController.js :
instead of
var tools = require('tools.js')
which force us to use a namespace and call tools like tools.sum(1,2);
we can simply call
require('tools.js')();
and then
sum(1,2);
in my case I have a file with controllers ctrls.js
module.exports = function() {
this.Categories = require('categories.js');
}
and I can use Categories
in every context as public class after require('ctrls.js')()
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
I'll just throw in a JS (ES6) answer, in case someone is looking for it:
Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
doSomething(el);
}
Update (this may have been possible when I posted the original answer, but adding this now anyway):
document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
doSomething(el);
});
This gets rid of the Array.from
usage.
document.querySelectorAll
returns a NodeList
.
Read here to know more about how to iterate on it (and other things): https://developer.mozilla.org/en-US/docs/Web/API/NodeList
You can reload using /etc/init.d/nginx reload
and sudo service nginx reload
If nginx -t
throws some error then it won't reload
so use && to run both at a same time
like
nginx -t && /etc/init.d/nginx reload
I had the same problem. My JDK package pointed by JAVA_HOME didn't have any tools.jar Be sure that your JDK instal.lation has tools.jar
(clearly the message error is confusing)
Here goes:
DECLARE @var nvarchar(max) = 'Man''s best friend';
You will note that the '
is escaped by doubling it to ''
.
Since the string delimiter is '
and not "
, there is no need to escape "
:
DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';
The second example in the MSDN page on DECLARE
shows the correct syntax.
Wrap them around a div with the following CSS
.div_wrapper{
white-space: nowrap;
}
try:
ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'
The NuGet package Pdf2Png is available for free and is only protected by the MIT License, which is very open.
I've tested around a bit and this is the code to get it to convert a PDF file to an image (tt does save the image in the debug folder).
using cs_pdf_to_image;
using PdfToImage;
private void BtnConvert_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string PdfFile = openFileDialog1.FileName;
string PngFile = "Convert.png";
List<string> Conversion = cs_pdf_to_image.Pdf2Image.Convert(PdfFile, PngFile);
Bitmap Output = new Bitmap(PngFile);
PbConversion.Image = Output;
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
}
}
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0 1
1 2
2 3
3 4
5 5
update or even better approach as @DSM suggested in comments, using pandas.Series.dropna()
:
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!
The better approach would be to extract this logic into reusable function on your $rootScope
:
.run(function ($rootScope) {
$rootScope.inArray = function (item, array) {
return (-1 !== array.indexOf(item));
};
})
Then, use it in your template:
<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>
I think everyone will agree that this example is much more readable and maintainable.
After following the guide (or using Spring Initializr), I had a WAR that worked on my local computer, but didn't work remote (running on Tomcat).
There was no error message, it just said "Spring servlet initializer was found", but didn't do anything at all.
17-Aug-2016 16:58:13.552 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.4
17-Aug-2016 16:58:13.593 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /opt/tomcat/webapps/ROOT.war
17-Aug-2016 16:58:16.243 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
and
17-Aug-2016 16:58:16.301 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
17-Aug-2016 16:58:21.471 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
Nothing else happened. Spring Boot just didn't run.
Apparently I compiled the server with Java 1.8, and the remote computer had Java 1.7.
After compiling with Java 1.7, it started working.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version> <!-- added this line -->
<start-class>myapp.SpringApplication</start-class>
</properties>
Two ways I can think of are
var TestApp = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
<li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
<li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
This is my personal favorite.
var ListItem = React.createClass({
getInitialState: function() {
return {
isSelected: false
};
},
handleClick: function() {
this.setState({
isSelected: true
})
},
render: function() {
var isSelected = this.state.isSelected;
var style = {
'background-color': ''
};
if (isSelected) {
style = {
'background-color': '#ccc'
};
}
return (
<li onClick={this.handleClick} style={style}>{this.props.content}</li>
);
}
});
var TestApp2 = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<ListItem content="Component 1" />
<ListItem content="Component 2" />
<ListItem content="Component 3" />
</ul>
</div>
);
}
});
React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
Here is a DEMO
I hope this helps.
Run a test.
string coerce: 7.42296099663
string cast: 8.05654597282
string fail coerce: 7.14159703255
string fail cast: 7.87444186211
This was a test that ran each scenario 10,000,000 times. :-)
Co-ercion is 0 + "123"
Casting is (integer)"123"
I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123')
is a fatal error in PHP. You might want your code to check the type of the supplied value.
My test code is below.
function test_string_coerce($s) {
return 0 + $s;
}
function test_string_cast($s) {
return (integer)$s;
}
$iter = 10000000;
print "-- running each text $iter times.\n";
// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();
print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_coerce('123');
}
$string_coerce->Stop();
// string cast
$string_cast = new Timer;
$string_cast->Start();
print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_cast('123');
}
$string_cast->Stop();
// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();
print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_coerce('hello');
}
$string_coerce_fail->Stop();
// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();
print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_cast('hello');
}
$string_cast_fail->Stop();
// -----------------
print "\n";
print "string coerce: ".$string_coerce->Elapsed()."\n";
print "string cast: ".$string_cast->Elapsed()."\n";
print "string fail coerce: ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast: ".$string_cast_fail->Elapsed()."\n";
class Timer {
var $ticking = null;
var $started_at = false;
var $elapsed = 0;
function Timer() {
$this->ticking = null;
}
function Start() {
$this->ticking = true;
$this->started_at = microtime(TRUE);
}
function Stop() {
if( $this->ticking )
$this->elapsed = microtime(TRUE) - $this->started_at;
$this->ticking = false;
}
function Elapsed() {
switch( $this->ticking ) {
case true: return "Still Running";
case false: return $this->elapsed;
case null: return "Not Started";
}
}
}
For Windows:
Save the following as MSFT.vbs:
set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")
Then from a command prompt, run:
C:\>MSFT.vbs
Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx
If you have set the environment variables (JAVA_HOME
and PATH
) under user variables, command prompt (run as administrator) will not identify java. For that you need to set environment variables under system variables.
I prefer the solution suggested here, as exemplified by this jsfiddle:
CSS:
sup, sub {
vertical-align: baseline;
position: relative;
top: -0.2em;
}
sub {
top: 0.2em;
}
HTML:
<span>The following equation is perhaps the most well known of all: </span><span id="box">E<sub>a</sub> = mc<sup>2</sup></span><span>. And it gives an opportunity to try out a superscript and even throw in a superfluous subscript! I'm sure that Einstein would be pleased.</span>.
The beauty of this solution is that you can tailor the vertical positioning of the superscript and subscript, to avoid any clashes with the line above or below... in the above, just increase or decrease the 0.2em
to suit your requirements.
I wrote this quick example. It works for me. I only tested it with one dataset with one table inside, but I guess that may be enough for you.
Take into consideration that I treated all cells as String (not even SharedStrings). If you want to use SharedStrings you might need to tweak my sample a bit.
Edit: To make this work it is necessary to add WindowsBase and DocumentFormat.OpenXml references to project.
Enjoy,
private void ExportDataSet(DataSet ds, string destination)
{
using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
foreach (System.Data.DataTable table in ds.Tables) {
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
uint sheetId = 1;
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in table.Columns) {
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (System.Data.DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
}
The question is what is worse:
For financial databases, deadlocks are far worse than wrong values. I know that sounds backwards, but hear me out. The traditional example of DB transactions is you update two rows, subtracting from one and adding to another. That is wrong.
In a financial database you use business transactions. That means adding one row to each account. It is of utmost importance that these transactions complete and the rows are successfully written.
Getting the account balance temporarily wrong isn't a big deal, that is what the end of day reconciliation is for. And an overdraft from an account is far more likely to occur because two ATMs are being used at once than because of a uncommitted read from a database.
That said, SQL Server 2005 fixed most of the bugs that made NOLOCK
necessary. So unless you are using SQL Server 2000 or earlier, you shouldn't need it.
Further Reading
Row-Level Versioning
Try:
return $this->sendRequest($uri);
Since PHP is not a pure Object-Orieneted language, it interprets sendRequest()
as an attempt to invoke a globally defined function (just like nl2br()
for example), but since your function is part of a class ('InstagramController'), you need to use $this
to point the interpreter in the right direction.
You can use C function gettimeofday : http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html
Here C library 'ul_time', function sec_usec resides in 'time' global table and returns seconds, useconds. Copy DLL to Lua folder, open it with require 'ul_time'.
This gives you the first few digits of the hash and they are unique enough to use as say a version number.
git rev-parse --short HEAD
Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!
In the child pom, use something like this:
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.felipe</groupId>
<artifactId>tutorial_maven</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>tutorial_maven_jar</artifactId>
Using properties like ${project.groupId}
won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.
str(c)
returns a new string representation of c
, and does not mutate c
itself.
c = str(c)
is probably what you are looking for
The 2nd parameter of http.post is the body of the message, ie the payload and not the url search parameters. Pass data
in that parameter.
From the documentation
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
public post(cmd: string, data: object): Observable<any> {
const params = new URLSearchParams();
params.set('cmd', cmd);
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
params: params,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post(this.BASE_URL, data, options)
.map(this.handleData)
.catch(this.handleError);
}
You should also check out the 1st parameter (BASE_URL
). It must contain the complete url (minus query string) that you want to reach. I mention in due to the name you gave it and I can only guess what the value currently is (maybe just the domain?).
Also there is no need to call JSON.stringify
on the data/payload that is sent in the http body.
If you still can't reach your end point look in the browser's network activity in the development console to see what is being sent. You can then further determine if the correct end point is being called wit the correct header and body. If it appears that is correct then use POSTMAN or Fiddler or something similar to see if you can hit your endpoint that way (outside of Angular).
Also you can use agg function,
df.groupby(['Name', 'Fruit'])['Number'].agg('sum')
In addition to what mentioned before, you can use [attr.selected]
directive to select a specific option, as follows:
<select>
<option *ngFor="let program of programs" [attr.selected]="(member.programID == program.id)">
{{ program.name }}
</option>
</select>
The best place to start looking is http://api.jquery.com/category/selectors/
This will give you a good set of examples.
Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])
Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]
Just because you asked for the dropdown as aposed to a listbox try the following:
$('select, [size]).each(function(){
var selectedItem = $('select, [select]', this).first();
});
The code was from memory so please accound for small errors
If you compiling your angular JS code in both CMD and IDE then this issue occur. In CMD, your angular JS code compile automatically whenever you change your angular JS code in IDE and then your IDE want to occupy the same port i.e 4200 which is occupied by CMD already So, there is a simple solution for this issue, just close your cmd while compiling your code in IDE.
You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.
You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.
In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.
<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
<asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>
switch(message)
{
case "test":
Console.WriteLine("yes");
break;
default:
if (Contains("test2")) {
Console.WriteLine("yes for test2");
}
break;
}
Look @JRuns answer in here. The idea is to create html with your custom scheme and upload it somewhere. Then if you click on your custom link on your html-file, you will be redirected to your app. I used this article for android. But dont forget to set full name Name = "MyApp.Mobile.Droid.MainActivity"
attribute to your target activity.
If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:
select a, (select b from B b where b.joinProperty = a.joinProperty) from A a
This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.
I had the same issue in 14.04, but I fixed it by these steps:
It worked like charm :)
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
Try this (I'm using SASS):
.carousel {
max-height: 700px;
overflow: hidden;
.item img {
width: 100%;
height: auto;
}
}
You can wrap the .carousel
into a .container
if you wish.
You can use python3 -m pip
as a synonym for pip3
. That has saved me a couple of times.
you can set it in .bashrc
PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;
As an alternative way to floating:
<style>
.wrapper{position:relative;}
.right,.left{width:50%; position:absolute;}
.right{right:0;}
.left{left:0;}
</style>
...
<div class="wrapper">
<div class="left"></div>
<div class="right"></div>
</div>
Considering that there's no necessity to position the .left div as absolute (depending on your direction, this could be the .right one) due to that would be in the desired position in natural flow of html code.
I use this to get all indices:
$ curl --silent 'http://127.0.0.1:9200/_cat/indices' | cut -d\ -f3
With this list you can work on...
$ curl -s 'http://localhost:9200/_cat/indices' | head -5
green open qa-abcdefq_1458925279526 1 6 0 0 1008b 144b
green open qa-test_learnq_1460483735129 1 6 0 0 1008b 144b
green open qa-testimportd_1458925361399 1 6 0 0 1008b 144b
green open qa-test123p_reports 1 6 3868280 25605 5.9gb 870.5mb
green open qa-dan050216p_1462220967543 1 6 0 0 1008b 144b
To get the 3rd column above (names of the indices):
$ curl -s 'http://localhost:9200/_cat/indices' | head -5 | cut -d\ -f3
qa-abcdefq_1458925279526
qa-test_learnq_1460483735129
qa-testimportd_1458925361399
qa-test123p_reports
qa-dan050216p_1462220967543
NOTE: You can also use awk '{print $3}'
instead of cut -d\ -f3
.
You can also suffix the query with a ?v
to add a column header. Doing so will break the cut...
method so I'd recommend using the awk..
selection at this point.
$ curl -s 'http://localhost:9200/_cat/indices?v' | head -5
health status index pri rep docs.count docs.deleted store.size pri.store.size
green open qa-abcdefq_1458925279526 1 6 0 0 1008b 144b
green open qa-test_learnq_1460483735129 1 6 0 0 1008b 144b
green open qa-testimportd_1458925361399 1 6 0 0 1008b 144b
green open qa-test123p_reports 1 6 3868280 25605 5.9gb 870.5mb
I found this MSDN forum post which suggests two solutions to your problem.
First solution (not recommended):
Find the .Net Framework 3.5 and 2.0 folder
Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder
Add the reference to these two assemblies
Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work
Second solution (Use a different class / library):
The user who had posted the question claimed that Uri.EscapeUriString
and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer
.
You could also try to use Json.Net. It's a third party library and pretty powerful.
Ignoring the check results in a corrupted install. This is the only solution that worked for me:
Create a C# console app with the following code:
Console.WriteLine(string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0"));
Run the app and get the 3 digit code.
Run > Regedit, open the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib
Now, if you don't have a folder underneath that path with the 3 digit code from step 2, create it. If you do have the folder, check that it has the "Counter" and "Help" values set under that path. It probably doesn't -- which is why the check fails.
Create the missing Counter and Help keys (REG_MULTI_SZ). For the values, copy them from the existing path above (probably 009).
The check should now pass.
Implement custom adapter for your class:
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
.bash_profile
is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.
.bashrc
is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.
I personally put everything in .bashrc
so that I don't have to restart the application for changes to take effect.
Wireshark does not do port redirection, but sniffs and interprets a lot of protocols.
If you want to just go with the default large size you can add 'modal-lg':
var modal = $modal.open({
templateUrl: "/partials/welcome",
controller: "welcomeCtrl",
backdrop: "static",
scope: $scope,
windowClass: 'modal-lg'
});
To generate jar file in eclipse right click on the project for which you want to generate, Select Export>Java>Runnable Jar File,
Its create jar which includes all the dependencies from Pom.xml, But please make sure license issue if you are using third-party dependency for your application.
If you are looking for range like function which works for float type, then here is a very good article.
def frange(start, stop, step=1.0):
''' "range()" like function which accept float type'''
i = start
while i < stop:
yield i
i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time.
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
print i # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))
Output:
1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]
Windows: I prefer Alt+F3 to search a string and change all instances of search string at once.
Better to save the code first, windows -> Perspective -> close all Perspective. Then from windows -> Perspective -> open your desired perspective. Now you can all the tab which required for the perspective
This worked for me on my Oracle database:
SELECT 'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM user_tables
where table_name like 'myTblPrefix%'
Then, copy the results, paste them into your editor, then run them like a script.
You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.
I success use this code to change uppercase
$(document).ready(function(){
$('#kode').keyup(function()
{
$(this).val($(this).val().toUpperCase());
});
});
</script>
in your html tag bootstraps
<div class="form-group">
<label class="control-label col-md-3">Kode</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<input name="kode" placeholder="Kode matakul" id="kode" class="form-control col-md-7 col-xs-12" type="text" required="required" maxlength="15">
<span class="fa fa-user form-control-feedback right" aria-hidden="true"></span>
</div>
</div>
If you don't want to do it all by yourself, you can use the random.randrange function.
For example import random; print random.randrange(10, 25, 5)
prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
Try this code:
CONVERT(varchar(15), date_started, 103)
Another approach is using the lunchy gem (a wrapper for launchctl):
brew install postgresql
initdb /usr/local/var/postgres -E utf8
gem install lunchy
To start PostgreSQL:
lunchy start postgres
To stop PostgreSQL:
lunchy stop postgres
For further information, refer to: "How to Install PostgreSQL on a Mac With Homebrew and Lunchy"
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).
for me, the problem was from require('jquery-validation')
i added in the begging of that js file which Validate method used which is necessary as an npm module
unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes
so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before
the data object is a buffer of bytes. Simply call .toString()
to get human-readable code:
console.log( data.toString() );
reference: Node.js buffers
I had a similar issue today in React. Eventually realised that the problem was being caused by the state not being set yet. I was calling user.user.name
and although it was showing up in the console, I couldn't seem to access it in my component till I included a check to check if user.user
was set and then calling user.user.name
.
Here is what I generally use in Jupyter Notebook:
# Jupyter Notebook settings
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
#size=25
size=15
params = {'legend.fontsize': 'large',
'figure.figsize': (20,8),
'axes.labelsize': size,
'axes.titlesize': size,
'xtick.labelsize': size*0.75,
'ytick.labelsize': size*0.75,
'axes.titlepad': 25}
plt.rcParams.update(params)
The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor
(hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.
To do this you will need to generate a stack in an extended HttpClient
, so its not advisable to do this in a production environment.
/**
* Extended HttpClient that generates a stack trace on error when not in a production build.
*/
@Injectable()
export class TraceHttpClient extends HttpClient {
constructor(handler: HttpHandler) {
super(handler);
}
request(...args: [any]): Observable<any> {
const stack = environment.production ? null : Error().stack;
return super.request(...args).pipe(
catchError((err) => {
// tslint:disable-next-line:no-console
if (stack) console.error('HTTP Client error stack\n', stack);
return throwError(err);
})
);
}
}
In case anyone else comes across this in a search for an answer...
The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.
Go here and get a number generated. Use any expiry date and CVV
https://ppmts.custhelp.com/app/answers/detail/a_id/750/
It's worked every time for me so far...
Simplification of @Daira Hopwood method good for picking one single commit. Need no temporary branches.
In the case of the author:
then do:
git checkout Z # move HEAD to wanted commit
git reset Y # have Z as changes in working tree
git stash # save Z in stash
git checkout X # return to working branch
git stash pop # apply Z to current branch
git commit -a # do commit
For me, this was related to the scenario described by Smi, with the difference being that vcvarsall.bat
itself was failing due to an invalid path.
This was cause by line-breaks within the path, which meant vcvarsall.bat
couldn't find the common tools directory for some reason.
In order to make a pull request you need to do the following steps:
It took me a while to figure this, hope this will help someone.
the question is should the url be case sensitive?
I see no use, or good practice behind case sensitive URL's. It stupid, it sucks and should be avoided at all times.
Just to back up my opinion, when someone asks what URL, how could you explain what characters of the URL are Upper or Lower case? That's nonsense and should no one ever tell you otherwise.
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
Another manner to do the job is using MAX()
analytic function in OVER PARTITION clause
SELECT t.*
FROM
(
SELECT id
,rev
,contents
,MAX(rev) OVER (PARTITION BY id) as max_rev
FROM YourTable
) t
WHERE t.rev = t.max_rev
The other ROW_NUMBER()
OVER PARTITION solution already documented in this post is
SELECT t.*
FROM
(
SELECT id
,rev
,contents
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY rev DESC) rank
FROM YourTable
) t
WHERE t.rank = 1
This 2 SELECT work well on Oracle 10g.
MAX() solution runs certainly FASTER that ROW_NUMBER()
solution because MAX()
complexity is O(n)
while ROW_NUMBER()
complexity is at minimum O(n.log(n))
where n
represent the number of records in table !
Sort hash by key, return hash in Ruby
With destructuring and Hash#sort
hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h
Enumerable#sort_by
hash.sort_by { |k, v| k }.to_h
Hash#sort with default behaviour
h = { "b" => 2, "c" => 1, "a" => 3 }
h.sort # e.g. ["a", 20] <=> ["b", 30]
hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }
Note: < Ruby 2.1
array = [["key", "value"]]
hash = Hash[array]
hash #=> {"key"=>"value"}
Note: > Ruby 2.1
[["key", "value"]].to_h #=> {"key"=>"value"}
I tried all the option but was not able to get it working on Redhat platform. I did the following to make it work:-
yum install MySQL-python -y
Once the package was installed was able to import module as follows in the interpreter:-
>>> import MySQLdb
>>>
You can access documents directory using this code it is basically used for storing file in plist format:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
The bug is probably somewhere else in your code, because it should work fine:
>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True
Or with tuples:
>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True
I eventually settled for:
>>> import time
>>> time.mktime(time.gmtime())
1509467455.0
For a working solution (tested on Ubuntu 12.04 (Precise Pangolin))...
find ! -path "dir1" -iname "*.mp3"
will search for MP3 files in the current folder and subfolders except in dir1 subfolder.
Use:
find ! -path "dir1" ! -path "dir2" -iname "*.mp3"
...to exclude dir1 AND dir2
this.close_Button = (Button)this.findViewById(R.id.close);
this.close_Button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
finish()
- Call this when your activity is done and should be closed. The ActivityResult
is propagated back to whoever launched you via onActivityResult()
.
Below code will help you to find out iframe data.
let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
To add another answer, the flag -p
(short for --optimize-minimize
) will enable the UglifyJS with default arguments.
You won't get a minified and raw bundle out of a single run or generate differently named bundles so the -p
flag may not meet your use case.
Conversely the -d
option is short for --debug
--devtool sourcemap
--output-pathinfo
My webpack.config.js omits devtool
, debug
, pathinfo
, and the minmize plugin in favor of these two flags.
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
If you wrote the console application you can make it hidden by default.
Create a new console app then then change the "Output Type" type to "Windows Application" (done in the project properties)
This problem can happen when you deploy your web application to a server, so you must check if you already installed MVC3.
Check if the folder C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3
exists.
If it doesn't exist, you need to install it from http://www.microsoft.com/en-us/download/details.aspx?id=1491
If you wont to install you can add all DLLs locally in bin folder and add references to them this work fine if you host on server don't deploy ASP.NET Web Pages or MVC3.
tl;dr takeaway:
If you're looking for a very high standard for yourself or team, JSLint. But its not necessarily THE standard, just A standard, some of which comes to us dogmatically from a javascript god named Doug Crockford. If you want to be a bit more flexible, or have some old pros on your team that don't buy into JSLint's opinions, or are going back and forth between JS and other C-family languages on a regular basis, try JSHint.
long version:
The reasoning behind the fork explains pretty well why JSHint exists:
http://badassjs.com/post/3364925033/jshint-an-community-driven-fork-of-jslint http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/
So I guess the idea is that it's "community-driven" rather than Crockford-driven. In practicality, JSHint is generally a bit more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical "opinions" that JSLint is a stickler on.
As an example, if you think both the A and B below are fine, or if you want to write code with one or more of the aspects of A that aren't available in B, JSHint is for you. If you think B is the only correct option... JSLint. I'm sure there are other differences, but this highlights a few.
A) Passes JSHint out of the box - fails JSLint
(function() {
"use strict";
var x=0, y=2;
function add(val1, val2){
return val1 + val2;
}
var z;
for (var i=0; i<2; i++){
z = add(y, x+i);
}
})();
B) Passes Both JSHint and JSLint
(function () {
"use strict";
var x = 0, y = 2, i, z;
function add(val1, val2) {
return val1 + val2;
}
for (i = 0; i < 2; i += 1) {
z = add(y, x + i);
}
}());
Personally I find JSLint code very nice to look at, and the only hard features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0
declarations, and some of the whitespace enforcements for function declarations.
A few of the whitespace things that JSLint enforces, I find to be not necessarily bad, but out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc...), which are often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day, and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches stuff that's a legitimate bug or really bad form, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.
A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is simply just about pushing 1 version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.
The classical answer that works in almost every environment is
SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL
sometimes NOT EXISTS may be not implemented (not working).
You can port-forward with another ssh
command that need not be tied to how you are connecting to the server (as an alternative to the other answer). Thus, the ordering of the below steps is arbitrary.
from your local machine, run
ssh -N -f -L localhost:16006:localhost:6006 <user@remote>
on the remote machine, run:
tensorboard --logdir <path> --port 6006
Then, navigate to (in this example) http://localhost:16006 on your local machine.
(explanation of ssh command:
-N
: no remote commands
-f
: put ssh in the background
-L <machine1>:<portA>:<machine2>:<portB>
:
forward <machine1>:<portA>
(local scope) to <machine2>:<portB>
(remote scope)
Either use a simple for
-loop:
var result = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name === "string 1") {
result = array[i];
break;
}
}
Or if you can, that is, if your browser supports it, use Array.filter
, which is much more terse:
var result = array.filter(function (obj) {
return obj.name === "string 1";
})[0];
You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.
The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.
Building on Tom's answer, here's an example using XMLUnit v2.
It uses these maven dependencies
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
..and here's the test code
import static org.junit.Assert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
import org.xmlunit.builder.Input;
import org.xmlunit.input.WhitespaceStrippedSource;
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String result = "<root></root>";
String expected = "<root> </root>";
// ignore whitespace differences
// https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource
assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));
assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences
}
}
The documentation that outlines this is https://github.com/xmlunit/xmlunit#comparing-two-documents
Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.
CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE
AS
IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
BEGIN
UPDATE a
SET Date_Column = GETDATE()
FROM Table_A a
JOIN inserted i ON a.ID = i.ID
END
When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.
You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.
IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
FYI, even if an exception is re-raised in the rescue
section, the ensure
block will be executed before the code execution continues to the next exception handler. For instance:
begin
raise "Error!!"
rescue
puts "test1"
raise # Reraise exception
ensure
puts "Ensure block"
end
Like Guffa said, you cannot reliably get that much control over native controls. The best way is probably to make a box of elements with radio buttons beside each item, then use labels and JavaScript to make the 'rows' interactive, so clicking on a radio button or label will color the selected row.
It works in samsung touchwiz launcher
public static void setBadge(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
public static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
try using -U
(aka --update-snapshots
) when you run maven
And make sure the dependency definition is correct
Also, you can create an alias.cmd in your path (for example C:\Windows) with the command
@echo %2 %3 %4 %5 %6 > %windir%\%1.cmd
Once you do that, you can do something like this:
alias nameOfYourAlias commands to run
And after that you can type in comman line
nameOfYourAlias
this will execute
commands to run
BUT the best way for me is just adding the path of a programm.
setx PATH "%PATH%;%ProgramFiles%\Sublime Text 3" /M
And now I run sublime as
subl index.html
A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.
Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");
// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
System.out.println(entry.getValue());
} // outputs Zero One Three
It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.
I came across a similar issue but instead of changing the regedit I decided to change the Chrome settings
Try the following steps
chrome://plugins/
+ Details
(top right corner) to expand all the plugin details.Java
and click on Disable
for the path(s) that you don't want to be used.You might have to restart the browser to see the changes. This also assumes that the Java that you have enabled is the latest Java.
Hope this helps
If you are already restricted/hardcoded your algorithm to using a std::vector::iterator
and std::vector::iterator
only, it doesn't really matter which method you will end up using. Your algorithm is already concretized beyond the point where choosing one of the other can make any difference. They both do exactly the same thing. It is just a matter of personal preference. I would personally use explicit subtraction.
If, on the other hand, you want to retain a higher degree of generality in your algorithm, namely, to allow the possibility that some day in the future it might be applied to some other iterator type, then the best method depends on your intent. It depends on how restrictive you want to be with regard to the iterator type that can be used here.
If you use the explicit subtraction, your algorithm will be restricted to a rather narrow class of iterators: random-access iterators. (This is what you get now from std::vector
)
If you use distance
, your algorithm will support a much wider class of iterators: input iterators.
Of course, calculating distance
for non-random-access iterators is in general case an inefficient operation (while, again, for random-access ones it is as efficient as subtraction). It is up to you to decide whether your algorithm makes sense for non-random-access iterators, efficiency-wise. It the resultant loss in efficiency is devastating to the point of making your algorithm completely useless, then you should better stick to subtraction, thus prohibiting the inefficient uses and forcing the user to seek alternative solutions for other iterator types. If the efficiency with non-random-access iterators is still in usable range, then you should use distance
and document the fact that the algorithm works better with random-access iterators.
The function takes a pointer to an arbitrary type and returns one such.
In additon to directly accessing the array, there is also
array_push
— Push one or more elements onto the end of array
In python3, has_key(key)
is replaced by __contains__(key)
Tested in python3.7:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
I often need to run more code per condition, by using: ( , , )
multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:
//=-=|Source|=-=//
/**
* JavaScript Timer Object
*
* var now=timer['elapsed']();
* timer['stop']();
* timer['start']();
* timer['reset']();
*
* @expose
* @method timer
* @return {number}
*/
timer=function(){
var a=Date.now();
b=0;
return{
/** @expose */
elapsed:function(){return b=Date.now()-a},
start:function(){return a=Date.now()},
stop:function(){return Date.now()},
reset:function(){return a=0}
}
}();
//=-=|Google Advanced Optimized|=-=//
timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();
It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming,
mean_1 = x_1, variance_1 = 0; //initial conditions; edge case;
//for k >= 2,
mean_k = mean_k-1 + (x_k - mean_k-1) / k;
variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k);
then for a list of n>=2
values, the estimate of the standard deviation is:
stddev = std::sqrt(variance_n / (n-1)).
Hope this helps!
From the documentation for sys.exit
:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
One example where exit codes are used are in shell scripts. In Bash you can check the special variable $?
for the last exit status:
me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43
Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h
(on a Linux system), but I don't know if this is the right thing to do.
app.get('*',function(req,res){
res.redirect('/login');
});
To replace only single quotes, use this simple statement:
$string = str_replace("'", "\\'", $string);
If you can't just use filter join but need to perform some operations on the array's entry:
{% for entry in array %}
User {{ entry.attribute1 }} has id {{ entry.attribute2 }}
{% if not loop.last %}, {% endif %}
{% endfor %}
For slow queries on version < 5.1, the following configuration worked for me:
log_slow_queries=/var/log/mysql/slow-query.log
long_query_time=20
log_queries_not_using_indexes=YES
Also note to place it under [mysqld]
part of the config file and restart mysqld
.
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:
s = """
line 1 has 4 leading spaces
line 2 has 4 leading spaces
line 3 has 4 leading spaces
"""
if we print(s)
we would get output like:
>>> print(s)
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
and if we used textwrap.dedent
:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable, without stopping further propagation of the event.
After trying without success to use _compiled_select()
or get_compiled_select()
I just printed the db
object, and you can see the query there in the queries
property.
Try it yourself:
var_dump( $this->db );
If you know you have only one query, you can print it directly:
echo $this->db->queries[0];
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
I want to share an available option that doesn't seem to be mentioned here yet:
rumpy.random.permutation(x)
Will generate a random permutation of array x. Not exactly what you asked for, but it is a potential solution to similar questions.
You can just use the one-liner
echo colorscheme koehler >> ~/.vimrc
and replace koehler
with any other available colorscheme. Imho, all of them are better than default.
The dot itself is not an operator, .^
is.
The .^
is a pointwise¹ (i.e. element-wise) power, as .*
is the pointwise product.
.^
Array power.A.^B
is the matrix with elementsA(i,j)
to theB(i,j)
power. The sizes ofA
andB
must be the same or be compatible.
C.f.
¹) Hence the dot.
String Integer
without space as String
arr = "12345"
arr.split('')
output: ["1","2","3","4","5"]
String Integer
with space as String
arr = "1 2 3 4 5"
arr.split(' ')
output: ["1","2","3","4","5"]
String Integer
without space as Integer
arr = "12345"
arr.split('').map(&:to_i)
output: [1,2,3,4,5]
arr = "abc"
arr.split('')
output: ["a","b","c"]
Explanation:
arr
-> string which you're going to perform any action.split()
-> is an method, which split the input and store it as array.''
or ' '
or ','
-> is an value, which is needed to be removed from given string.By checking out to one of the commits in the history you are moving your git into so called 'detached state', which looks like is not what you want. Use this single command to create a new branch on one of the commits from the history:
git checkout -b <new_branch_name> <SHA1>
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
The idea of os.path.join()
is to make your program cross-platform (linux/windows/etc).
Even one slash ruins it.
So it only makes sense when being used with some kind of a reference point like
os.environ['HOME']
or os.path.dirname(__file__)
.
Set a breakpoint on the last line of code.
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
You want to use "multiline".
$string =~ /(START)(.+?)(END)/m;