// Regex - Check Singapore valid mobile numbers
public static boolean isSingaporeMobileNo(String str) {
Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
Matcher matcher = mobNO.matcher(str);
if (matcher.find()) {
return true;
} else {
return false;
}
}
An easy way to overcome this problem is to use 64 bit type
list = numpy.array(list, dtype=numpy.float64)
In Python,
any variable that is assigned a value is local to the block in which the assignment appears.
If a variable can't be found in the current scope, please refer to the LEGB order.
FreeBSD and Solaris have this handy pwait(1)
utility, which does exactly, what you want.
I believe, other modern OSes also have the necessary system calls too (MacOS, for example, implements BSD's kqueue
), but not all make it available from command-line.
I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.
If destroy() and clear() is not working (just like what i had experience) you can use jquery to remove the canvas and append it again.
$('#chartAmazon').remove();
$('#chartBar').append('<canvas id="chartAmazon"></canvas>');
var ctxAmazon = $("#chartAmazon").get(0).getContext("2d");
var AmazonChart = new Chart(ctxAmazon, {
type: 'doughnut',
data: dataAmazon,
options: optionsA
});
angular 5 :
getImage(id: string): Observable<Blob> {
return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}
Use a for
loop to iterate through your array. For each string, create a new option
element, assign the string as its innerHTML
and value
, and then append it to the select
element.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
UPDATE: Using createDocumentFragment
and forEach
If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment
acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild
operation so that the DOM only updates once, instead of n
times.
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();
cuisines.forEach(function(cuisine, index) {
var opt = document.createElement('option');
opt.innerHTML = cuisine;
opt.value = cuisine;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
As the official docs use https://
instead of market://
, this combines Eric's and M3-n50's answer with code reuse (don't repeat yourself):
Intent intent = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
try {
startActivity(new Intent(intent)
.setPackage("com.android.vending"));
} catch (android.content.ActivityNotFoundException exception) {
startActivity(intent);
}
It tries to open with the GPlay app if it exists and falls back to default.
@echo off
set "language=de"
IF "%language%" == "de" (
goto languageDE
) ELSE (
IF "%language%" == "en" (
goto languageEN
) ELSE (
echo Not found.
)
)
:languageEN
:languageDE
echo %language%
This works , but not sure how your language variable is defined.Does it have spaces in its definition.
#include<stdio.h>
int main()
{
char str[100];
scanf("%[^\n]s",str);
printf("%s",str);
return 0;
}
input: read the string
ouput: print the string
This code prints the string with gaps as shown above.
As of IE11, you need to use addEventListener
. attachEvent
is deprecated and throws an error.
Although this question is only related to finding directory path ($WORKSPACE) however I had a requirement to read the file from workspace and parse it into JSON object to read sonar issues ( ignore minor/notes issues )
Might help someone, this is how I did it- from readFile
jsonParse(readFile('xyz.json'))
and jsonParse method-
@NonCPS
def jsonParse(text) {
return new groovy.json.JsonSlurperClassic().parseText(text);
}
This will also require script approval in ManageJenkins-> In-process script approval
I wrote this method:
private string GetUrlParameter(HttpRequestBase request, string parName)
{
string result = string.Empty;
var urlParameters = HttpUtility.ParseQueryString(request.Url.Query);
if (urlParameters.AllKeys.Contains(parName))
{
result = urlParameters.Get(parName);
}
return result;
}
And I call it like this:
string fooBar = GetUrlParameter(Request, "FooBar");
if (!string.IsNullOrEmpty(fooBar))
{
}
I got a MD5 hash with different results for both key and certificate.
This says it all. You have a mismatch between your key and certificate.
The modulus should match. Make sure you have correct key.
You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.
[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.
If you use http://localhost:80/
as a prefix, you can listen to http requests with no need for Administrative privileges.
You have to use the jquery attribute selector. You can read more here:
http://api.jquery.com/attribute-equals-selector/
In your case it should be:
$('input[name="btnName"]')
If you're using Visual Studio 2013 (may require Pro edition or higher), I was able to add a virtual directory to an IIS Express (file-based) website by right-clicking on the website in the Solution Explorer and clicking Add > New Virtual Directory. This added an entry to the applicationhost.config file as with the manual methods described here.
I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).
Try changing your curl request to:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
and see if that helps any.
Starting with API15, you can use also callOnClick()
that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
<context:annotation-config>
:
This tells Spring that I am going to use Annotated beans as spring bean and those would be wired through @Autowired
annotation, instead of declaring in spring config xml file.
<context:component-scan base-package="com.test...">
:
This tells Spring container, where to start searching those annotated beans. Here spring will search all sub packages of the base package.
After a lot of time spent trying all these technique in a Dialog, I finally had this idea : attach the theme to the Dialog itself and not to the TextInputLayout.
<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorWhite</item>
<item name="colorAccent">@color/colorPrimary</item>
</style>
inside onCreate :
public class myDialog extends Dialog {
private Activity activity;
private someVars;
public PopupFeedBack(Activity activity){
super(activity, R.style.AppTheme_Dialog);
setContentView(R.layout.myView);
....}}
cheers :)
function exportToExcel() {_x000D_
var tab_text = "<tr bgcolor='#87AFC6'>";_x000D_
var textRange; var j = 0, rows = '';_x000D_
tab = document.getElementById('student-detail');_x000D_
tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";_x000D_
var tableData = $('#student-detail').DataTable().rows().data();_x000D_
for (var i = 0; i < tableData.length; i++) {_x000D_
rows += '<tr>'_x000D_
+ '<td>' + tableData[i].value1 + '</td>'_x000D_
+ '<td>' + tableData[i].value2 + '</td>'_x000D_
+ '<td>' + tableData[i].value3 + '</td>'_x000D_
+ '<td>' + tableData[i].value4 + '</td>'_x000D_
+ '<td>' + tableData[i].value5 + '</td>'_x000D_
+ '<td>' + tableData[i].value6 + '</td>'_x000D_
+ '<td>' + tableData[i].value7 + '</td>'_x000D_
+ '<td>' + tableData[i].value8 + '</td>'_x000D_
+ '<td>' + tableData[i].value9 + '</td>'_x000D_
+ '<td>' + tableData[i].value10 + '</td>'_x000D_
+ '</tr>';_x000D_
}_x000D_
tab_text += rows;_x000D_
var data_type = 'data:application/vnd.ms-excel;base64,',_x000D_
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',_x000D_
base64 = function (s) {_x000D_
return window.btoa(unescape(encodeURIComponent(s)))_x000D_
},_x000D_
format = function (s, c) {_x000D_
return s.replace(/{(\w+)}/g, function (m, p) {_x000D_
return c[p];_x000D_
})_x000D_
}_x000D_
_x000D_
var ctx = {_x000D_
worksheet: "Sheet 1" || 'Worksheet',_x000D_
table: tab_text_x000D_
}_x000D_
document.getElementById("dlink").href = data_type + base64(format(template, ctx));_x000D_
document.getElementById("dlink").download = "StudentDetails.xls";_x000D_
document.getElementById("dlink").traget = "_blank";_x000D_
document.getElementById("dlink").click();_x000D_
}
_x000D_
Here Value 1 to 10 are column names that you are getting
We have used YUI, Chosen, and are currently using the jQuery Select2 plugin: https://select2.github.io/
It's pretty robust, the arrow is just the tip of the iceberg.
As soon as stylized selects becomes a requirement, I agree with the others, go with a plugin. Don't kill yourself reinventing the wheel.
It's implementation-specific, but in practice the rule (in the absence of #pragma pack
or the like) is:
sizeof(T)
bytes.So, given the following struct:
struct ST
{
char ch1;
short s;
char ch2;
long long ll;
int i;
};
ch1
is at offset 0s
at offset 2ch2
is at offset 4, immediately after sll
at offset 8i
is at offset 16, right after llSo sizeof(ST)
is 24.
It can be reduced to 16 bytes by rearranging the members to avoid padding:
struct ST
{
long long ll; // @ 0
int i; // @ 8
short s; // @ 12
char ch1; // @ 14
char ch2; // @ 15
} ST;
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
Another option is to use numpy.full
, an option available in NumPy 1.8+
a = np.full([height, width, 9], np.nan)
This is pretty flexible and you can fill it with any other number that you want.
Using jQuery
$('#note textarea');
or just
$('#textid');
In the eclipse environment where you execute your java programs, take the following steps:
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
Since you are explicitly also asking to handle columns that haven't yet been filled out, and I assume also don't want to mess with them if they have a word instead of a number, you might consider this:
=If(IsNumber(K23), If(K23 > 0, ........., 0), 0)
This just says... If K23 is a number; And if that number is greater than zero; Then do something ......... Otherwise, return zero.
In ........., you might put your division equation there, such as A1/K23
, and you can rest assured that K23 is a number which is greater than zero.
You can either use adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
which is introduced in recyclerview:1.2.0-alpha02
https://medium.com/androiddevelopers/restore-recyclerview-scroll-position-a8fbdc9a9334
but it has some issues such as not working with inner RecyclerView, and some other issues you can check out in medium post's comment section.
Or you can use ViewModel
with SavedStateHandle
which works for inner RecyclerViews, screen rotation and process death.
Create a ViewModel
with saveStateHandle
val scrollState=
savedStateHandle.getLiveData<Parcelable?>(KEY_LAYOUT_MANAGER_STATE)
use Parcelable scrollState
to save and restore state as answered in other posts or by adding a scroll listener to RecyclerView and
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
scrollState.value = mLayoutManager.onSaveInstanceState()
}
}
Here you go.
SELECT
column1,
column2
FROM
viewWhatever
WHERE
CASE
WHEN @locationType = 'location' AND account_location = @locationID THEN 1
WHEN @locationType = 'area' AND xxx_location_area = @locationID THEN 1
WHEN @locationType = 'division' AND xxx_location_division = @locationID THEN 1
ELSE 0
END = 1
For free private SVN hosting try the following:
Or use BitBucket for free private git/mercurial repositories
DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:
DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;
Maybe this one can help:
function focus(el){_x000D_
el.focus();_x000D_
return el==document.activeElement;_x000D_
}
_x000D_
return value: true = success, false = failed
Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
I just had this issue as well and my normal branches start with pb-3.1-12345/namebranch
but I accidental capitalized the first 2 letters PB-3.1/12345/namebranch
. After renaming the branch to use lower case letters I could create the branch.
Gagravarr's answer is quite good!
But if you assume that a cell is also empty if it contains an empty String (""
), you need some additional code. This can happen, if a cell was edited and then not cleared properly (for how to clear a cell properly, see further below).
I wrote myself a helper to check if an XSSFCell
is empty (including an empty String).
/**
* Checks if the value of a given {@link XSSFCell} is empty.
*
* @param cell
* The {@link XSSFCell}.
* @return {@code true} if the {@link XSSFCell} is empty. {@code false}
* otherwise.
*/
public static boolean isCellEmpty(final XSSFCell cell) {
if (cell == null) { // use row.getCell(x, Row.CREATE_NULL_AS_BLANK) to avoid null cells
return true;
}
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return true;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()) {
return true;
}
return false;
}
Pay attention for newer POI Version
They first changed getCellType()
to getCellTypeEnum()
as of Version 3.15 Beta 3
and then moved back to getCellType()
as of Version 4.0
.
Version >= 3.15 Beta 3
:
CellType.BLANK
and CellType.STRING
instead of Cell.CELL_TYPE_BLANK
and Cell.CELL_TYPE_STRING
Version >= 3.15 Beta 3
&& Version < 4.0
Cell.getCellTypeEnum()
instead of Cell.getCellType()
But better double check yourself, because they planned to change it back in future releases.
This JUnit test shows the case in which the additional empty check is needed.
Scenario: the content of a cell is changed within a Java program. Later on, in the same Java program, the cell is checked for emptiness. The test will fail if the isCellEmpty(XSSFCell cell)
function doesn't check for empty Strings.
@Test
public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() {
// Arrange
XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0);
boolean expectedValue = true;
boolean actualValue;
// Act
cell.setCellValue("foo");
cell.setCellValue("bar");
cell.setCellValue(" ");
actualValue = isCellEmpty(cell);
// Assert
Assert.assertEquals(expectedValue, actualValue);
}
Just in case if someone wants to know, how to clear the content of a cell properly. There are two ways to archive that (I would recommend way 1).
// way 1
public static void clearCell(final XSSFCell cell) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
// way 2
public static void clearCell(final XSSFCell cell) {
String nullString = null;
cell.setCellValue(nullString);
}
Why way 1? Explicit is better than implicit (thanks, Python)
Way 1: sets the cell type explicitly back to blank
.
Way 2: sets the cell type implicitly back to blank
due to a side effect when setting a cell value to a null
String.
Regards winklerrr
The one that worked for me is:
grep -e '->'
The -e means that the next argument is the pattern, and won't be interpreted as an argument.
From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/
Use
$(document).on("click", "#btn_a", function(){
alert ('button clicked');
});
to add the listener for the dynamically created button.
alert($("#btn_a").val());
will give you the value of the button
my quick answer with basic java arithmetic calculation is this:
First consider the following values:
1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
the code snippet is as follows:
int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60 ;
I hope to be helpful to you.
Walk through on how to run an SQL on the command line for PostgreSQL in Linux:
Open a terminal and make sure you can run the psql
command:
psql --version
which psql
Mine is version 9.1.6 located in /bin/psql
.
Create a plain textfile called mysqlfile.sql
Edit that file, put a single line in there:
select * from mytable;
Run this command on commandline (substituting your username and the name of your database for pgadmin and kurz_prod):
psql -U pgadmin -d kurz_prod -a -f mysqlfile.sql
The following is the result I get on the terminal (I am not prompted for a password):
select * from mytable;
test1
--------
hi
me too
(2 rows)
Notice the data-type and size
>describe all_tab_columns
VIEW all_tab_columns
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
The Spring container is able to resolve Setter-based circular dependencies but gives a runtime exception BeanCurrentlyInCreationException in case of Constructor-based circular dependencies. In case of Setter-based circular dependency, the IOC container handles it differently from a typical scenario wherein it would fully configure the collaborating bean before injecting it. For eg., if Bean A has a dependency on Bean B and Bean B on Bean C, the container fully initializes C before injecting it to B and once B is fully initialized it is injected to A. But in case of circular dependency, one of the beans is injected to the other before it is fully initialized.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
Walk is a good built-in for what you are doing
$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
_x000D_
It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.
MyClass myClass = new MyClass();
once you've added that line you can then call your method
myClass.myMethod();
Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
Try this
SELECT Count(*) AS N
FROM
(SELECT DISTINCT Name FROM table1) AS T;
Read this for more info.
Remember, you are NOT allowed to do this.
class foo():
def print_hello(self):
print("Hello") # This next line will produce an ERROR!
self.print_hello() # <---- it calls a class function, inside a class,
# but outside a class function. Not allowed.
You must call a class function from either outside the class, or from within a function in that class.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Using the solution from inversus, I expanded the snippet with a function, that will be called when the desired application is not installed at the moment. So it works like: Run application by package name. If not found, open Android market - Google play for this package.
public void startApplication(String packageName)
{
try
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info : resolveInfoList)
if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
{
launchComponent(info.activityInfo.packageName, info.activityInfo.name);
return;
}
// No match, so application is not installed
showInMarket(packageName);
}
catch (Exception e)
{
showInMarket(packageName);
}
}
private void launchComponent(String packageName, String name)
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(packageName, name));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showInMarket(String packageName)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
And it is used like this:
startApplication("org.teepee.bazant");
Work out the time complexity of the algorithm you are using now and it should be obvious that it can not be improved.
This works great for finding the top viewController 1 from any root view controlle
+ (UIViewController *)topViewControllerFor:(UIViewController *)viewController
{
if(!viewController.presentedViewController)
return viewController;
return [MF5AppDelegate topViewControllerFor:viewController.presentedViewController];
}
/* View Controller for Visible View */
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIViewController *visibleViewController = [AppDelegate topViewControllerFor:app.window.rootViewController];
Here's a simple function:
function setParent(el, newParent)
{
newParent.appendChild(el);
}
el
's childNodes
are the elements to be moved, newParent
is the element el
will be moved to, so you would execute the function like:
var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
setParent(a.childNodes[0], b);
}
If you've already installed Android Studio --
Add the following lines to the end of ~/.bashrc
or ~/.zshrc
(if using Oh My ZSH):
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Restart Terminal and you're good to go.
convert the NULL
values with empty string by wrapping it in COALESCE
"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"
OR
Use CONCAT_WS instead:
"UPDATE table SET data = CONCAT_WS(',',data, 'a')"
From C#3.5 I assume you're using WPF.
Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.
For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.
Look up Binding on MSDN.
Try this :
<style type="text/css">
.myTableStyle
{
position:absolute;
top:50%;
left:50%;
/*Alternatively you could use: */
/*
position: fixed;
bottom: 50%;
right: 50%;
*/
}
</style>
Installig Eclispe ADT from market place solved this problem for me.
The man page explains that you can enter command line mode in a running session by typing Ctrl+A, :, then issuing the scrollback <num>
command.
try with this after add ANDROID_HOME on your Environment Variable, work well on my mac
flutter config --android-sdk ANDROID_HOME
For normal MySQL, just connect as the 'root' administrative super user, and issue the command:
FLUSH HOSTS
Even in the case of too many connections, MySQL should be keeping a connection in reserve so that a super user can connect.
The mysqladmin
client generally connects as root anyway and issues the above SQL.
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
var app = angular.module( "myApp", [] );_x000D_
_x000D_
app.controller( "myCtrl", ["$scope", function($scope) {_x000D_
_x000D_
$scope.submit_form = function(formData) {_x000D_
_x000D_
$scope.formData = formData;_x000D_
_x000D_
console.log(formData); // object_x000D_
console.log(JSON.stringify(formData)); // string_x000D_
_x000D_
$scope.form = {}; // clear ng-model form_x000D_
_x000D_
}_x000D_
_x000D_
}] );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
<form ng-submit="submit_form(form)" >_x000D_
_x000D_
Firstname: <input type="text" ng-model="form.firstname" /><br />_x000D_
Lastname: <input type="text" ng-model="form.lastname" /><br />_x000D_
_x000D_
<hr />_x000D_
_x000D_
<input type="submit" value="Submit" />_x000D_
_x000D_
</form>_x000D_
_x000D_
<hr /> _x000D_
_x000D_
<p>Firstname: {{ form.firstname }}</p>_x000D_
<p>Lastname: {{ form.lastname }}</p>_x000D_
_x000D_
<pre>Submit Form: {{ formData }} </pre>_x000D_
_x000D_
</div>
_x000D_
Look at http://ss64.com/nt/if.html for an answer; the command is IF [%1]==[] GOTO NO_ARGUMENT
or similar.
Voila!
div {_x000D_
background-color: red;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
width: 48px;_x000D_
height: 48px; _x000D_
transform: rotate(360deg);_x000D_
transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
transform: rotate(0deg);_x000D_
transition: 0s;_x000D_
}
_x000D_
<div></div>
_x000D_
In addition to perfect Riceball LEE's example of adding a new element-directive
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
Let's say you wish to add on-the-fly my-directive
to the span
element.
template: '<div>Hello <span>World</span></div>'
link: ($scope, $element, $attrs) ->
span = $element.find('span').clone()
span.attr('my-directive', 'my-directive')
span = $compile(span)($scope)
$element.find('span').replaceWith span
Hope that helps.
try Integer.toString(integer value);
method as
ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));
#include <iostream>
std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
For .Net 4 use:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.
CREATE TABLE [dbo].[ImagenesUsuario] (
[idImagen] [int] IDENTITY (1, 1) NOT NULL
)
ALTER TABLE [dbo].[ImagenesUsuario] ADD
CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY CLUSTERED
(
[idImagen]
) ON [PRIMARY]
I had to set
C:\ProgramData\MySQL\MySQL Server 8.0/my.ini secure-file-priv=""
When I commented line with secure-file-priv
, secure-file-priv was null and I couldn't download data.
To be efficient, and random, it might be best to have two different queries.
Something like...
SELECT table_id FROM table
Then, in your chosen language, pick a random id, then pull that row's data.
SELECT * FROM table WHERE table_id = $rand_id
But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.
Try using a wildcard like this
=VLOOKUP(LEFT(A1,3)&"*",B$2:B$22,1,FALSE)
so if A1 is "barry" that formula will return the first value in B2:B22
that starts with "bar"
In Kotlin, you can concatenate using String interpolation/templates:
val a = "Hello"
val b = "World"
val c = "$a $b"
The output will be: Hello World
StringBuilder
for String templates which is the most efficient approach in terms of memory because +
/plus()
creates new String objects.Or you can concatenate using the StringBuilder
explicitly.
val a = "Hello"
val b = "World"
val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()
print(c)
The output will be: HelloWorld
Or you can concatenate using the +
/ plus()
operator:
val a = "Hello"
val b = "World"
val c = a + b // same as calling operator function a.plus(b)
print(c)
The output will be: HelloWorld
Following solution worked for me.
.algncenterdiv {
display: block;
margin-left: auto;
margin-right: auto;
}
If you're not on java 1.8 yet and you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
Here's an example update trigger:
create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime,
OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName)
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log
This will print:
id EmployeeId LogDate OldName
1 1 2010-07-05 20:11:54.127 Zaphoid
Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:
If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:
var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();
var firstNames = list.Select(p => p.FirstName).ToList();
var lastNames = list.Select(p => p.LastName).ToList();
Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>()
Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)
For VS 2013, community edition, you have to delete the registry keys found under: hkey_current_user\software\Microsoft\VSCommon\12.0\clientservices\tokenstorge\visualstudio\ideuser
Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.
However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.
Though it is an old question, it is still a valid one.
Expected behavior:
Cancel
.Code with a demonstration:
<!DOCTYPE html>
<html>
<head>
<title>File upload event</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userFile" id="userFile"><br>
<input type="submit" name="upload_btn" value="upload">
</form>
<script type="text/javascript">
document.getElementById("userFile").onchange = function(e) {
alert(this.value);
this.value = null;
}
</script>
</body>
</html>
_x000D_
Explanation:
onchange
event handler is used to handle any change in file selection event.onchange
event is triggered only when the value of an element is changed. So, when we select the same file using the input
field the event will not be triggered. To overcome this, I set this.value = null;
at the end of the onchange
event function. It sets the file path of the selected file to null
. Thus, the onchange
event is triggered even at the time of the same file selection.According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
df.T.iloc[-1]
df.T.tail(1)
pd.Series(df.values[:, -1], name=df.columns[-1])
If you want “real” comparison according to Unicode and locale rules, use ICU’s Collator
class.
If you run VMware Player or Workstation (or maybe VirtualBox, I'm not sure if it supports Mac OS X, but may), and then Mac OS X Server (Client can't legally be virtualized). Of course, in this case you are running XCode on OS X, but your host machine could be linux.
Load testing your API by using just ab is not enough. However, I think it's a great tool to give you a basic idea how your site is performant.
If you want to use the ab command in to test multiple API endpoints, with different data, all at the same time in background, you need to use "nohup" command. It runs any command even when you close the terminal.
I wrote a simple script that automates the whole process, feel free to use it: http://blog.ikvasnica.com/entry/load-test-multiple-api-endpoints-concurrently-use-this-simple-shell-script
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
for Email use this code
$email=$this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getEmail());
echo $email;
In this way one can delete a particular item which is present multiple times in a list : Try deleting all 5
list1=[1,2,3,4,5,6,5,3,5,7,11,5,9,8,121,98,67,34,5,21]
print list1
n=input("item to be deleted : " )
for i in list1:
if n in list1:
list1.remove(n)
print list1
I had a similar problem, and the solution that worked best for me was to include the source in the same jar as the compiled code (so a given directory in the jar would include both Foo.java
and Foo.class
). Eclipse automatically associates the source with the compiled code, and automatically provides the JavaDoc from the source. Obviously, that's only helpful if you control the artifact.
The question has already been answered by aaronasterling
However, someone might be interested in how the variables are stored under the hood.
Before coming to the snippet:
Closures are functions that inherit variables from their enclosing environment. When you pass a function callback as an argument to another function that will do I/O, this callback function will be invoked later, and this function will — almost magically — remember the context in which it was declared, along with all the variables available in that context.
If a function does not use free variables it doesn't form a closure.
If there is another inner level which uses free variables -- all previous levels save the lexical environment ( example at the end )
function attributes func_closure
in python < 3.X or __closure__
in python > 3.X save the free variables.
Every function in python has this closure attributes, but it doesn't save any content if there is no free variables.
example: of closure attributes but no content inside as there is no free variable.
>>> def foo():
... def fii():
... pass
... return fii
...
>>> f = foo()
>>> f.func_closure
>>> 'func_closure' in dir(f)
True
>>>
NB: FREE VARIABLE IS MUST TO CREATE A CLOSURE.
I will explain using the same snippet as above:
>>> def make_printer(msg):
... def printer():
... print msg
... return printer
...
>>> printer = make_printer('Foo!')
>>> printer() #Output: Foo!
And all Python functions have a closure attribute so let's examine the enclosing variables associated with a closure function.
Here is the attribute func_closure
for the function printer
>>> 'func_closure' in dir(printer)
True
>>> printer.func_closure
(<cell at 0x108154c90: str object at 0x108151de0>,)
>>>
The closure
attribute returns a tuple of cell objects which contain details of the variables defined in the enclosing scope.
The first element in the func_closure which could be None or a tuple of cells that contain bindings for the function’s free variables and it is read-only.
>>> dir(printer.func_closure[0])
['__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'cell_contents']
>>>
Here in the above output you can see cell_contents
, let's see what it stores:
>>> printer.func_closure[0].cell_contents
'Foo!'
>>> type(printer.func_closure[0].cell_contents)
<type 'str'>
>>>
So, when we called the function printer()
, it accesses the value stored inside the cell_contents
. This is how we got the output as 'Foo!'
Again I will explain using the above snippet with some changes:
>>> def make_printer(msg):
... def printer():
... pass
... return printer
...
>>> printer = make_printer('Foo!')
>>> printer.func_closure
>>>
In the above snippet, I din't print msg inside the printer function, so it doesn't create any free variable. As there is no free variable, there will be no content inside the closure. Thats exactly what we see above.
Now I will explain another different snippet to clear out everything Free Variable
with Closure
:
>>> def outer(x):
... def intermediate(y):
... free = 'free'
... def inner(z):
... return '%s %s %s %s' % (x, y, free, z)
... return inner
... return intermediate
...
>>> outer('I')('am')('variable')
'I am free variable'
>>>
>>> inter = outer('I')
>>> inter.func_closure
(<cell at 0x10c989130: str object at 0x10c831b98>,)
>>> inter.func_closure[0].cell_contents
'I'
>>> inn = inter('am')
So, we see that a func_closure
property is a tuple of closure cells, we can refer them and their contents explicitly -- a cell has property "cell_contents"
>>> inn.func_closure
(<cell at 0x10c9807c0: str object at 0x10c9b0990>,
<cell at 0x10c980f68: str object at 0x10c9eaf30>,
<cell at 0x10c989130: str object at 0x10c831b98>)
>>> for i in inn.func_closure:
... print i.cell_contents
...
free
am
I
>>>
Here when we called inn
, it will refer all the save free variables so we get I am free variable
>>> inn('variable')
'I am free variable'
>>>
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
When searching folders where you might get an error based on security (e.g. C:\Users
), use the following command:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.
This opens up a simpler solution if you can change the method signatures - alter Foo()
so that it returns type Task
and then DoFoo()
can await Foo()
, as in this code:
public async Task Foo() {
var x = await DoSomethingThatThrows();
}
public async void DoFoo() {
try {
await Foo();
} catch (ProtocolException ex) {
// This will catch exceptions from DoSomethingThatThrows
}
}
Our app also has this problem. After testing, it is found that when the application memory is insufficient and the activity is recycled, the system calls the onSaveInstanceState method to save a large amount of bundle data, and the data becomes large every time, and finally a TransactionTooLargeException error will be reported, so I think of this method should be able to solve this problem.
public final int MAX_BUNDLE_SIZE = 300;
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
long bundleSize = getBundleSize(outState);
if (bundleSize > MAX_BUNDLE_SIZE * 1024) {
outState.clear();
}
}
private long getBundleSize(Bundle bundle) {
long dataSize;
Parcel obtain = Parcel.obtain();
try {
obtain.writeBundle(bundle);
dataSize = obtain.dataSize();
} finally {
obtain.recycle();
}
return dataSize;
}
sed
can be put into multi-line search & replace mode to match newline characters \n
.
To do so sed
first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".
To replace a single newline portably (with respect to GNU and FreeBSD sed
) you can use an escaped "real" newline.
# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' |
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'
# output
# California
#
# Massachusetts
#
# Arizona
#
There is, however, a much more convenient was to achieve the same result:
echo 'California
Massachusetts
Arizona' |
sed G
There's actually a pretty straightforward way to do this in CSS exploiting the fact that IE extends this with non-standards and FF supports :after
You can also do this in JS if you wish by inspecting the scrollWidth of the target and comparing it to it's parents width, but imho this is less robust.
Edit: this is apparently more developed than I thought. CSS3 support may soon exist, and some imperfect extensions are available for you to try.
That last one is good reading.
.navigationLevel2 li { color: #aa0000 }
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.
If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.
Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.
FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.
You could capture the (2001)
part and replace the rest with nothing.
public static string extractYearString(string input) {
return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}
var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"
.*\(([0-9]{4})\).*
means
.*
match anything\(
match a (
character(
begin capture[0-9]{4}
any single digit four times)
end capture\)
match a )
character.*
anything (rest of string)Use a BOM to solve version issues.
you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.
To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>3.2.12.RELEASE</version>
<type>pom</type>
</dependency>
If your sed
allows in place editing via the -i
parameter:
sed -e 's/$/string after each line/' -i filename
If not, you have to make a temporary file:
typeset TMP_FILE=$( mktemp )
touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
});
Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>
, provided you keep the class attribute with it.
By the way, I think you could do it in one selector:
$('#mytable .customerIDCell').each(function() {
alert($(this).html());
});
If that makes things easier.
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe
(the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe
you'll get output in your console window.
Example code:
a = pd.Series([1,2,3,4], index=[7,2,8,9])
b = pd.Series([5,6,7,8], index=[7,2,8,9])
data = pd.DataFrame({'a': a,'b':b, 'idx_col':a.index})
Pandas allows you to create a DataFrame
from a dict
with Series
as the values and the column names as the keys. When it finds a Series
as a value, it uses the Series
index as part of the DataFrame
index. This data alignment is one of the main perks of Pandas. Consequently, unless you have other needs, the freshly created DataFrame
has duplicated value. In the above example, data['idx_col']
has the same data as data.index
.
express.static()
expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html
and use that.
Serving static files in Express documentation, or more detailed serve-static
documentation, including the default behavior of serving index.html
:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
This post was helpful, but just wanted to share a slight alternative that may help others:
Setting max-height
instead of height
also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;}
when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height
accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.
My iPhone has updated to iOS8.1. My Xcode version is 6.0.1, and my mac os version is 10.10. When I want to run app in my iPhone, there is a section named Ineligible Devices(OS Version)
. Then I update Xcode to 6.1 version, solved problem.
Part of Xcode 6.1 release note: Includes SDKS for OS X 10.10 Yosemite, OS X 10.9 Mavericks, and iOS 8.1
.
That is, Xcode 6.0.x don't support iOS 8.1.
You can definitely run a high-traffic site in Django. Check out this pre-Django 1.0 but still relevant post here: http://menendez.com/blog/launching-high-performance-django-site/
With Java 9, we get access to jshell
, so one can write something like this:
import jdk.jshell.JShell;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Eval {
public static void main(String[] args) throws IOException {
try(JShell js = JShell.create(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
js.onSnippetEvent(snip -> {
if (snip.status() == jdk.jshell.Snippet.Status.VALID) {
System.out.println("? " + snip.value());
}
});
System.out.print("> ");
for (String line = br.readLine(); line != null; line = br.readLine()) {
js.eval(js.sourceCodeAnalysis().analyzeCompletion(line).source());
System.out.print("> ");
}
}
}
}
Sample run:
> 1 + 2 / 4 * 3
? 1
> 32 * 121
? 3872
> 4 * 5
? 20
> 121 * 51
? 6171
>
Slightly op, but that's what Java currently has to offer
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
In addition to changing the permissions as the other answers have indicated, I had to restart apache for it to take effect:
sudo service apache2 restart
If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.
To add to the other answers above, the finally
clause executes no matter what whereas the else
clause executes only if an exception was not raised.
For example, writing to a file with no exceptions will output the following:
file = open('test.txt', 'w')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
OUTPUT:
Writing to file.
Write successful.
File closed.
If there is an exception, the code will output the following, (note that a deliberate error is caused by keeping the file read-only.
file = open('test.txt', 'r')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
OUTPUT:
Could not write to file.
File closed.
We can see that the finally
clause executes regardless of an exception. Hope this helps.
since iOS7 use
self.automaticallyAdjustsScrollViewInsets = NO;
//and create you page scroller with 3 pages
self.pageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.pageView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height)];
[self.pageView setShowsVerticalScrollIndicator:NO];
[self.pageView setPagingEnabled:YES];
[self.view addSubview:self.pageView];
Was able to set the auth using the HttpsURLConnection
URL myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//httpsurlconnection
conn.setRequestProperty("Authorization", basicAuth);
few of the changes fetched from this post. and Base64 is from java.util package.
Yes, ensure
ensures that the code is always evaluated. That's why it's called ensure
. So, it is equivalent to Java's and C#'s finally
.
The general flow of begin
/rescue
/else
/ensure
/end
looks like this:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
rescue SomeOtherException => some_other_variable
# code that deals with some other exception
else
# code that runs only if *no* exception was raised
ensure
# ensure that this code always runs, no matter what
# does not change the final value of the block
end
You can leave out rescue
, ensure
or else
. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from StandardError
will be caught. (Please note that this does not mean that all exceptions are caught, because there are exceptions which are instances of Exception
but not StandardError
. Mostly very severe exceptions that compromise the integrity of the program such as SystemStackError
, NoMemoryError
, SecurityError
, NotImplementedError
, LoadError
, SyntaxError
, ScriptError
, Interrupt
, SignalException
or SystemExit
.)
Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing
def foo
begin
# ...
rescue
# ...
end
end
you write just
def foo
# ...
rescue
# ...
end
or
def foo
# ...
ensure
# ...
end
The same applies to class
definitions and module
definitions.
However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a using
block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:
# This is what you want to do:
File.open('myFile.txt', 'w') do |file|
file.puts content
end
# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
yield filehandle = new(filename, mode, perm, opt)
ensure
filehandle&.close
end
And what do you know: this is already available in the core library as File.open
. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la using
in C#) or transactions or whatever else you might think of.
The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.
BTW: in modern C#, using
is actually superfluous, because you can implement Ruby-style resource blocks yourself:
class File
{
static T open<T>(string filename, string mode, Func<File, T> block)
{
var handle = new File(filename, mode);
try
{
return block(handle);
}
finally
{
handle.Dispose();
}
}
}
// Usage:
File.open("myFile.txt", "w", (file) =>
{
file.WriteLine(contents);
});
In addition to richq answer of using git log -g --grep=<regexp>
or git grep -e <regexp> $(git log -g --pretty=format:%h)
: take a look at the following blog posts by Junio C Hamano, current git maintainer
Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.
You can use git log --grep=<foo> --grep=<bar>
(or git log --author=<foo> --grep=<bar>
that internally translates to two --grep
) to find commits that match either of patterns (implicit OR semantic).
Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar>
to find commit that has both line matching first and line matching second somewhere.
With git grep
you can combine multiple patterns (all which must use the -e <regexp>
form) with --or
(which is the default), --and
, --not
, (
and )
. For grep --all-match
means that file must have lines that match each of alternatives.
explorer "http://www.google.com/search?client=opera&rls=...."
Another option is to set the spring.config.location
through @TestPropertySource
:
@TestPropertySource(properties = { "spring.config.location = classpath:<path-to-your-yml-file>" }
I know this is late, but this command searches the /usr/ directory to find java for you
sudo find /usr/ -name *jdk
Results to
/usr/lib/jvm/java-6-openjdk
/usr/lib/jvm/java-1.6.0-openjdk
FYI, if you are on a Mac, currently JAVA_HOME is located at
/System/Library/Frameworks/JavaVM.framework/Home
IE11 no longer reports as MSIE
, according to this list of changes it's intentional to avoid mis-detection.
What you can do if you really want to know it's IE is to detect the Trident/
string in the user agent if navigator.appName
returns Netscape
, something like (the untested);
function getInternetExplorerVersion()_x000D_
{_x000D_
var rv = -1;_x000D_
if (navigator.appName == 'Microsoft Internet Explorer')_x000D_
{_x000D_
var ua = navigator.userAgent;_x000D_
var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");_x000D_
if (re.exec(ua) != null)_x000D_
rv = parseFloat( RegExp.$1 );_x000D_
}_x000D_
else if (navigator.appName == 'Netscape')_x000D_
{_x000D_
var ua = navigator.userAgent;_x000D_
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");_x000D_
if (re.exec(ua) != null)_x000D_
rv = parseFloat( RegExp.$1 );_x000D_
}_x000D_
return rv;_x000D_
}_x000D_
_x000D_
console.log('IE version:', getInternetExplorerVersion());
_x000D_
Note that IE11 (afaik) still is in preview, and the user agent may change before release.
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
For anyone coming across this thread, here's a script called thatsNotYoChild.js that I just wrote that solves this problem automatically:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically, it separates children from the parent element, but keeps the element in the same physical location on the page.
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
In my case I didnt need to disable it , rather I had to put this code on top of my class : (and this solved my issue)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)//this is what was added
@Value //this was there already
@Builder//this was there already
public class NameOfClass {
//some code in here.
}
This is one of the command which you can run to install apt-get:
wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb
Finally found a solution from : Detect different device platforms using CSS
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
To reduce HTTP call, this can also be used inside you existing common CSS file:
@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait) {
.ipad-portrait { color: red; } /* your css rules for ipad portrait */
}
@media all and (device-width: 1024px) and (device-height: 768px) and (orientation:landscape) {
.ipad-landscape { color: blue; } /* your css rules for ipad landscape */
}
Hope this helps.
Other references:
new_list = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
for i in range(len(new_list)):
new_list[i]=new_list[i].replace('\n','')
print(new_list)
Output Will be like this
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']
To get each sum in a separate column:
Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash')
and CDate<=SYSDATETIME()
and CStatus='Active';
These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread
in this case) goes through a sort-of del myThread
.
The call self.sample()
is roughly equivalent to myThread.__dict__["sample"](self)
.
But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread
deleted, and now it's basically a NoneType
- and has no 'sample' attribute.
Like @Sunkas wrote, performSelector:withObject:afterDelay:
is the pendant to the dispatch_after
just that it is shorter and you have the normal objective-c
syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject
and you will receive it in the selector
you call:
[self performSelector:@selector(testStringMethod:)
withObject:@"Test Test"
afterDelay:0.5];
- (void)testStringMethod:(NSString *)string{
NSLog(@"string >>> %@", string);
}
If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:
If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.
If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar
, which is available in SQLLIB/java/
folder of your db2 installation.
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
From here:
Windows
For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
Find the “datadir”
, this is the where does MySQL stored the data in Windows.
Linux
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
my.cnf
file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/english
skip-external-locking
“datadir”
, this is where does MySQL stored the data in Linux system.C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char
that is terminated by the first null character. There is no string concatenation operator in C.
Use strcat
to concatenate two strings. You could use the following function to do it:
#include <stdlib.h>
#include <string.h>
char* concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free
the memory when it is no longer needed.
Call the function like this:
char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string
If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.
char* concat(const char *s1, const char *s2)
{
const size_t len1 = strlen(s1);
const size_t len2 = strlen(s2);
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
return result;
}
If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.
A simplified version of SLaks' answer also works:
if ('abcdefghij'.indexOf(str) >= 0) {
// Do something
}
....since strings are sort of arrays themselves. :)
If needed, implement the indexof function for Internet Explorer as described before me.
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
os.path.commonprefix() and os.path.relpath() are your friends:
>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var']) # No common prefix: the root is the common prefix
'/'
You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:
paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
…
You can then find the relative paths:
relative_paths = [os.path.relpath(path, common_prefix) for path in paths]
You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.
PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().
PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:
>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'
even though /usr/var
is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix()
solves this (specific) problem.
PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?
PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()
), taking the intersection of all these parent sets, and selecting the longest common prefix.
PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath()
, which returns a valid path.
Autoplay works only with /v/
instead of /embed/
, so change the src to:
src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"
Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. But if you override a method inherited from a library it is recommended to use it. If you dont, you will often get no error on a later library change, but a well hidden bug.
If you using >5 version of laravel then you will use.
composer require laravel/ui --dev **or** composer require laravel/ui
And then
php artisan ui:auth
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}
For background pushes in iOS13, you must set below parameters:
apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms
The video link: https://developer.apple.com/videos/play/wwdc2019/707/
(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa
me:
(returnTypeOfSecontArgument) secondArgumentName ;
as in other languages we use following syntax
void add(int one, int second)
but way of assigning arguments in OBJ_c
is different as described above
This is the most famous case and It has many names
kebab-case
: It's the name most adopted by official softwarecaterpillar-case
dash-case
hyphen-case
or hyphenated-case
lisp-case
spinal-case
css-case
slug-case
friendly-url-case
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
This can be archived by adding code on the onchange event of the select control.
For Example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value=""></option>
<option value="http://google.com">Google</option>
<option value="http://gmail.com">Gmail</option>
<option value="http://youtube.com">Youtube</option>
</select>
Using PNG is not such a good idea. Actually it's costly as far as performance is concerned. You can use drawable XML files, for example, Facebook's background.
This will help you to smooth and speed up your performance, and for the logo use .9 patch images.
This error message also occurs when you created the SCHEMA with a different COLLATION than the one which is used in the dump. So, if the dump contains
CREATE TABLE `mytab` (
..
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
you should also reflect this in the SCHEMA collation:
CREATE SCHEMA myschema COLLATE utf8_unicode_ci;
I had been using utf8mb4_general_ci in the schema, cause my script came from a fresh V8 installation, now loading a DB on old 5.7 crashed and drove me nearly crazy.
So, maybe this helps you saving some frustating hours... :-)
(MacOS 10.3, mysql 5.7)
You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.
In case anybody is looking at this old question, a handy command to see the changes since your last update:
svn log -r $(svn info | grep Revision | cut -f 2 -d ' '):HEAD -v
LE (thanks Gary for the comment)
same thing, but much shorter and more logical:
svn log -r BASE:HEAD -v
The generic template that can be used for checking if some "feature" is supported by the type:
#include <type_traits>
template <template <typename> class TypeChecker, typename Type>
struct is_supported
{
// these structs are used to recognize which version
// of the two functions was chosen during overload resolution
struct supported {};
struct not_supported {};
// this overload of chk will be ignored by SFINAE principle
// if TypeChecker<Type_> is invalid type
template <typename Type_>
static supported chk(typename std::decay<TypeChecker<Type_>>::type *);
// ellipsis has the lowest conversion rank, so this overload will be
// chosen during overload resolution only if the template overload above is ignored
template <typename Type_>
static not_supported chk(...);
// if the template overload of chk is chosen during
// overload resolution then the feature is supported
// if the ellipses overload is chosen the the feature is not supported
static constexpr bool value = std::is_same<decltype(chk<Type>(nullptr)),supported>::value;
};
The template that checks whether there is a method foo
that is compatible with signature double(const char*)
// if T doesn't have foo method with the signature that allows to compile the bellow
// expression then instantiating this template is Substitution Failure (SF)
// which Is Not An Error (INAE) if this happens during overload resolution
template <typename T>
using has_foo = decltype(double(std::declval<T>().foo(std::declval<const char*>())));
Examples
// types that support has_foo
struct struct1 { double foo(const char*); }; // exact signature match
struct struct2 { int foo(const std::string &str); }; // compatible signature
struct struct3 { float foo(...); }; // compatible ellipsis signature
struct struct4 { template <typename T>
int foo(T t); }; // compatible template signature
// types that do not support has_foo
struct struct5 { void foo(const char*); }; // returns void
struct struct6 { std::string foo(const char*); }; // std::string can't be converted to double
struct struct7 { double foo( int *); }; // const char* can't be converted to int*
struct struct8 { double bar(const char*); }; // there is no foo method
int main()
{
std::cout << std::boolalpha;
std::cout << is_supported<has_foo, int >::value << std::endl; // false
std::cout << is_supported<has_foo, double >::value << std::endl; // false
std::cout << is_supported<has_foo, struct1>::value << std::endl; // true
std::cout << is_supported<has_foo, struct2>::value << std::endl; // true
std::cout << is_supported<has_foo, struct3>::value << std::endl; // true
std::cout << is_supported<has_foo, struct4>::value << std::endl; // true
std::cout << is_supported<has_foo, struct5>::value << std::endl; // false
std::cout << is_supported<has_foo, struct6>::value << std::endl; // false
std::cout << is_supported<has_foo, struct7>::value << std::endl; // false
std::cout << is_supported<has_foo, struct8>::value << std::endl; // false
return 0;
}
According to this answer, the easiest way in both languages is:
Kotlin:
Glide.with(context).load(uri).apply(RequestOptions().circleCrop()).into(imageView)
Java:
Glide.with(context).load(uri).apply(new RequestOptions().circleCrop()).into(imageView)
This works on Glide 4.X.X
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:
window.open('/pageaddress.html','winname',"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350");
Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)
Here how you can do it:
jQuery:
$(function() {
$("#labelfile").click(function() {
$("#imageupl").trigger('click');
});
})
css
.file {
position: absolute;
clip: rect(0px, 0px, 0px, 0px);
display: block;
}
.labelfile {
color: #333;
background-color: #fff;
display: inline-block;
margin-bottom: 0;
font-weight: 400;
text-align: center;
vertical-align: middle;
cursor: pointer;
background-image: none;
white-space: nowrap;
padding: 6px 8px;
font-size: 14px;
line-height: 1.42857143;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="margin-top:4px;">
<input name="imageupl" type="file" id="imageupl" class="file" />
<label class="labelfile" id="labelfile"><i class="icon-download-alt"></i> Browse File</label>
</div>
Optionally you can remove all folders from "packages" folder and select "Manage NuGet Packages for Solution...". In this case "Restore" button appears on NuGet Packages Windows.
EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.
"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"
The most obvious approach is to loop through twice. On the first pass, order the values:
if(current_value > examined_value)
{
current_value = examined_value
(and then swap them, however you like)
}
Then on the second pass, alphabetize the words, but only if their values match.
if(current_value == examined_value)
{
(alphabetize the two)
}
Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.
There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.
html
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown Example <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>
jquery
$(document).ready( function() {
/* $(selector).hover( inFunction, outFunction ) */
$('.dropdown').hover(
function() {
$(this).find('ul').css({
"display": "block",
"margin-top": 0
});
},
function() {
$(this).find('ul').css({
"display": "none",
"margin-top": 0
});
}
);
});
This can be done. For example with Firefox
CSS
#hlinks {
-moz-binding: url(stackexchange.xml#hlinks);
}
stackexchange.xml
<bindings xmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="hlinks">
<content>
<children/>
<html:a href="/privileges">privileges</html:a>
<html:span class="lsep"> | </html:span>
<html:a href="/users/logout">log out</html:a>
</content>
</binding>
</bindings>
If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. You can directly use the map or bimap methods to transform your Map. A MapX can be constructed from an existing Map eg.
MapX<String, Column> y = MapX.fromMap(orgColumnMap)
.map(c->new Column(c.getValue());
If you also wish to change the key you can write
MapX<String, Column> y = MapX.fromMap(orgColumnMap)
.bimap(this::newKey,c->new Column(c.getValue());
bimap can be used to transform the keys and values at the same time.
As MapX extends Map the generated map can also be defined as
Map<String, Column> y
This is what I used for my countdown clock:
</SCRIPT>
<center class="auto-style19" style="height: 31px">
<Font face="blacksmith" size="large"><strong>
<SCRIPT LANGUAGE="JavaScript">
var header = "You have <I><font color=red>"
+ getDaysUntilICD10() + "</font></I> "
header += "days until ICD-10 starts!"
document.write(header)
</SCRIPT>
The HTML inside of my script worked, though I could not explain why.
Add this code in a separate file/script included after the validation plugin to override the messages, edit at will :)
jQuery.extend(jQuery.validator.messages, {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
minlength: jQuery.validator.format("Please enter at least {0} characters."),
rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
range: jQuery.validator.format("Please enter a value between {0} and {1}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});
TableA LEFT OUTER JOIN TableB
is equivalent to TableB RIGHT OUTER JOIN Table A
.
In Oracle, (+)
denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S
. In your second query, it's S RIGHT OUTER JOIN P
. They're functionally equivalent.
In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S
, P
will always have a record because it's on the LEFT
, but S
could be null.
See this example from java2s.com for additional explanation.
To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.
I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+)
determines RIGHT or LEFT. (Specifically, if the (+)
is on the right, it's a LEFT JOIN. If (+)
is on the left, it's a RIGHT JOIN.)
The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.
See this SO question.
Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.
Implicit JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.
Explicit JOIN
SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column
These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.
Oneliner:
thefirst = [i for i in range(10) if i > 3][0]
If youre not sure that any element will be valid according to the criteria, you should enclose this with try/except
since that [0]
can raise an IndexError
.
Random random = new Random ();
int randomNumber = random.Next (lowerBound,upperBound);
The quoting rules are painful. I think you want:
SELECT nextval('foo."SQ_ID"');
to prevent case-folding of SQ_ID
.
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
I found the default JS date formatting didn't work.
So I used toLocaleString
with options
const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);
to get: DD/MM/YYYY format
See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp
You can use istringstream
.
string s = "10";
// create an input stream with your string.
istringstream is(str);
int i;
// use is like an input stream
is >> i;
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
There's no built-in way, you'll have to loop over all of them:
function setAll(a, v) {
var i, n = a.length;
for (i = 0; i < n; ++i) {
a[i] = v;
}
}
http://jsfiddle.net/alnitak/xG88A/
If you really want, do this:
Array.prototype.setAll = function(v) {
var i, n = this.length;
for (i = 0; i < n; ++i) {
this[i] = v;
}
};
and then you could actually do cool.setAll(42)
(see http://jsfiddle.net/alnitak/ee3hb/).
Some people frown upon extending the prototype of built-in types, though.
EDIT ES5 introduced a way to safely extend both Object.prototype
and Array.prototype
without breaking for ... in ...
enumeration:
Object.defineProperty(Array.prototype, 'setAll', {
value: function(v) {
...
}
});
EDIT 2 In ES6 draft there's also now Array.prototype.fill
, usage cool.fill(42)
vector<string> getseq(char * db_file)
And if you want to print it on main() you should do it in a loop.
int main() {
vector<string> str_vec = getseq(argv[1]);
for(vector<string>::iterator it = str_vec.begin(); it != str_vec.end(); it++) {
cout << *it << endl;
}
}
kubectl delete daemonsets,replicasets,services,deployments,pods,rc --all
to get rid of them pesky replication controllers too.
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
Just in keeping the parent value in child attribute
var Foo = function(){
this.val= 4;
this.test={};
this.test.val=6;
this.test.par=this;
}
var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);
In the thread dump you can find the Line Number as below.
for the main thread which is currently running...
"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
java.lang.Thread.State: **RUNNABLE**
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:313)
at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**
Once you have the indexPath of your cell, you can do something like:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
In Xcode 4.6 and higher:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
You can set whatever your like as animation effect, of course.
Just passing the file object to the putobject method worked for me. If you are getting a stream, try writing it to a temp file before passing it on to S3.
amazonS3.putObject(bucketName, id,fileObject);
I am using Aws SDK v1.11.414
The answer at https://stackoverflow.com/a/35904801/2373449 helped me
vcxproj file may contain 'MACHINE:i386' Edit vcxproj file with editor. remove it !
Use this line of code when scanning the second value:
scanf(" %lf", &b);
also replace all %ld with %lf.
It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.
COLLATE UTF8_GENERAL_CI
will work as ignore-case.
USE:
SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';
or
SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';
With File::Slurp:
use File::Slurp;
my $text = read_file('index.html');
This is a solution suggested by the MySQl manual:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.
You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
So I found this post and the answers did not help me but i was able to figure out why it gave me the error. I had a
cat > temp.txt < EOF
some content
EOF
The issue was that i copied the above code to be in a function and inadvertently tabbed the code. Need to make sure the last EOF is not tabbed.