you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
The correct way to set the column width is by using the line as posted by Jahmic, however it is important to note that additionally, you have to apply styling after adding the data, and not before, otherwise on some configurations, the column width is not applied
If you're trying to launch a specific activity instead of running the launcher one.
When you select that activity. the android studio might through this error,
Either you need to make it launcher activity, just like answered by few others.
or you need to add android:exported="true"
inside your activity tag inside manifest. It allows any external tool to run your specific activity directly without making it a launcher activity
Had this issue. My main app and extension belonged to the same app group id correctly, but there was also one more app ID not in my project that shared said app group id. I had to remove this last app ID's association with the app group.
Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())
Expanding a bit on @Eruant's answer,
$(window).on('load', function() {
// your code here
});
Works very well with both async
and defer
while loading on scripts.
So you can import all scripts like this:
<script src="/js/script1.js" async defer></script>
<script src="/js/script2.js" async defer></script>
<script src="/js/script3.js" async defer></script>
Just make sure script1
doesn't call functions from script3
before $(window).on('load' ...
, make sure to call them inside window load
event.
More about async/defer here.
The following code implements a default context menu known from Windows
with copy, cut, paste, select all, undo and redo functions. It also works on Linux
and Mac OS X
:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DefaultContextMenu extends JPopupMenu
{
private Clipboard clipboard;
private UndoManager undoManager;
private JMenuItem undo;
private JMenuItem redo;
private JMenuItem cut;
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem delete;
private JMenuItem selectAll;
private JTextComponent textComponent;
public DefaultContextMenu()
{
undoManager = new UndoManager();
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
addPopupMenuItems();
}
private void addPopupMenuItems()
{
undo = new JMenuItem("Undo");
undo.setEnabled(false);
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
undo.addActionListener(event -> undoManager.undo());
add(undo);
redo = new JMenuItem("Redo");
redo.setEnabled(false);
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
redo.addActionListener(event -> undoManager.redo());
add(redo);
add(new JSeparator());
cut = new JMenuItem("Cut");
cut.setEnabled(false);
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
cut.addActionListener(event -> textComponent.cut());
add(cut);
copy = new JMenuItem("Copy");
copy.setEnabled(false);
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
copy.addActionListener(event -> textComponent.copy());
add(copy);
paste = new JMenuItem("Paste");
paste.setEnabled(false);
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
paste.addActionListener(event -> textComponent.paste());
add(paste);
delete = new JMenuItem("Delete");
delete.setEnabled(false);
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
delete.addActionListener(event -> textComponent.replaceSelection(""));
add(delete);
add(new JSeparator());
selectAll = new JMenuItem("Select All");
selectAll.setEnabled(false);
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
selectAll.addActionListener(event -> textComponent.selectAll());
add(selectAll);
}
private void addTo(JTextComponent textComponent)
{
textComponent.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent pressedEvent)
{
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canUndo())
{
undoManager.undo();
}
}
if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
&& ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
{
if (undoManager.canRedo())
{
undoManager.redo();
}
}
}
});
textComponent.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
@Override
public void mouseReleased(MouseEvent releasedEvent)
{
handleContextMenu(releasedEvent);
}
});
textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
}
private void handleContextMenu(MouseEvent releasedEvent)
{
if (releasedEvent.getButton() == MouseEvent.BUTTON3)
{
processClick(releasedEvent);
}
}
private void processClick(MouseEvent event)
{
textComponent = (JTextComponent) event.getSource();
textComponent.requestFocus();
boolean enableUndo = undoManager.canUndo();
boolean enableRedo = undoManager.canRedo();
boolean enableCut = false;
boolean enableCopy = false;
boolean enablePaste = false;
boolean enableDelete = false;
boolean enableSelectAll = false;
String selectedText = textComponent.getSelectedText();
String text = textComponent.getText();
if (text != null)
{
if (text.length() > 0)
{
enableSelectAll = true;
}
}
if (selectedText != null)
{
if (selectedText.length() > 0)
{
enableCut = true;
enableCopy = true;
enableDelete = true;
}
}
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
{
enablePaste = true;
}
undo.setEnabled(enableUndo);
redo.setEnabled(enableRedo);
cut.setEnabled(enableCut);
copy.setEnabled(enableCopy);
paste.setEnabled(enablePaste);
delete.setEnabled(enableDelete);
selectAll.setEnabled(enableSelectAll);
// Shows the popup menu
show(textComponent, event.getX(), event.getY());
}
public static void addDefaultContextMenu(JTextComponent component)
{
DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
defaultContextMenu.addTo(component);
}
}
Usage:
JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);
Now the textArea
will have a context menu when it is right-clicked on.
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
Like this:
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
// do something with the 2 result sets...
if ($result1)
mysql_free_result($result1);
if ($result2)
mysql_free_result($result2);
The zabbix-server
daemon doesn't seem to like passwords with special characters in them. Unsure whether quotes would work in the configuration I just removed special characters from the database password, updated the configuration files and restarted the daemon.
Configuration parsing errors don't show up in logs for some reason.
You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"
Form native JavaScript checkValidity
function is more then enough to trigger the HTML5
validation
$(document).ready(function() {
$('#urlSubmit').click(function() {
if($('#urlForm')[0].checkValidity()) {
alert("form submitting");
}
});
});
This is very complicated in java, which is why I would suggest using Spring's RestTemplate
abstraction:
String result =
restTemplate.getForObject(
"http://example.com/hotels/{hotel}/bookings/{booking}",
String.class,"42", "21"
);
Reference:
RestTemplate
Denis's answer made me think to another solution using JsonObjects,
a header property checker:
Predicate<object> hasHeader = jsonObject =>
((JObject)jsonObject).OfType<JProperty>()
.Any(prop => prop.Name == "header");
or maybe better:
Predicate<object> hasHeader = jsonObject =>
((JObject)jsonObject).Property("header") != null;
for example:
dynamic json = JsonConvert.DeserializeObject(data);
string header = hasHeader(json) ? json.header : null;
in python sorted
works like you want with integers:
>>> sorted([10,3,2])
[2, 3, 10]
it looks like you have a problem because you are using strings:
>>> sorted(['10','3','2'])
['10', '2', '3']
(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int
>>> sorted(['10','3','2'], key=int)
['2', '3', '10']
which converts the values to integers during the sort (it is called as a function - int('10')
returns the integer 10
)
and as suggested in the comments, you can also sort the list itself, rather than generating a new one:
>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']
but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).
and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ...
to the sql command:
select temperature from temperatures order by temperature;
You will find newest version of the chromedriver here: http://chromedriver.storage.googleapis.com/index.html - there is a 64bit version for linux.
It works for me!
input[type="file"]{
font-size: 0px;
}
Then, you can use different kind of styles such as width
, height
or other properties in order to create your own input file.
This is my answer,
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>
Using Date object guarantees that. For eg if you try to create April 31st
:
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is
0
, Feb. is1
etc.
Do you really want to style the <div>
? Or do you want to style the <input type="button">
? You should use the correct selector if you want the latter:
input[type=button] {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
/* ... other rules ... */
cursor:pointer;
}
input[type=button]:hover {
background-color:rgba(255,204,0,0.8);
}
See also:
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
When you are defining styles for division which is positioned absolute
ly, they specifying margins are useless. Because they are no longer inside the regular DOM tree.
You can use float to do the trick.
.divtagABS {
float: left;
margin-left: auto;
margin-right:auto;
}
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
When looking for files to potentially add. The output from git show
does that but it also includes a lot of other stuff. The following command is useful to get the same list of files but without all of the other stuff.
git status --porcelain | grep "^?? " | sed -e 's/^[?]* //'
This is useful when combined in a pipeline to find files matching a specific pattern and then piping that to git add
.
git status --porcelain | grep "^?? " | sed -e 's/^[?]* //' | \
egrep "\.project$|\.settings$\.classfile$" | xargs -n1 git add
If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add
method.
List<String> list = List.of("first", "second", "third");
Here is my solution for those who use hook
; If you are listing items in your grid and want to remove the selected item, you can use this solution.
var list = data.filter(form => form.id !== selectedRowDataId);
setData(list);
firstly shouldn't
data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
be
data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
and secondly you can use
url: this.action + '?NonFormValue=' + NonFormValue,
or if the action already contains any parameters
url: this.action + '&NonFormValue=' + NonFormValue,
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
This saves you having to duplicate the link in the tr - just fish it out of the first a.
$(".link-first-found").click(function() {
var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});
Here's an updated version (Swift 3.0.1) from Ben Packard's answer.
import UIKit
@IBDesignable class BorderedButton: UIButton {
@IBInspectable var borderColor: UIColor? {
didSet {
if let bColor = borderColor {
self.layer.borderColor = bColor.cgColor
}
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
override var isHighlighted: Bool {
didSet {
guard let currentBorderColor = borderColor else {
return
}
let fadedColor = currentBorderColor.withAlphaComponent(0.2).cgColor
if isHighlighted {
layer.borderColor = fadedColor
} else {
self.layer.borderColor = currentBorderColor.cgColor
let animation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = fadedColor
animation.toValue = currentBorderColor.cgColor
animation.duration = 0.4
self.layer.add(animation, forKey: "")
}
}
}
}
The resulting button can be used inside your StoryBoard thanks to the @IBDesignable
and @IBInspectable
tags.
Also the two properties defined, allow you to set the border width and color directly on interface builder and preview the result.
Other properties could be added in a similar fashion, for border radius and highlight fading time.
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
I had a case in where I was needing to use a data frame within a for loop function. In this case, it was the "efficient", however, keep in mind that the database was small and the iterations in the loop were very simple. But maybe the code could be useful for some one with similar conditions.
The for loop purpose was to use the raster extract function along five locations (i.e. 5 Tokio, New York, Sau Paulo, Seul & Mexico city) and each location had their respective raster grids. I had a spatial point database with more than 1000 observations allocated within the 5 different locations and I was needing to extract information from 10 different raster grids (two grids per location). Also, for the subsequent analysis, I was not only needing the raster values but also the unique ID for each observations.
After preparing the spatial data, which included the following tasks:
Here the for loop code with the use of a data frame:
1. Add stacked rasters per location into a list
raslist <- list(LOC1,LOC2,LOC3,LOC4,LOC5)
2. Create an empty dataframe, this will be the output file
TB <- data.frame(VAR1=double(),VAR2=double(),ID=character())
3. Set up for loop function
L1 <- seq(1,5,1) # the location ID is a numeric variable with values from 1 to 5
for (i in 1:length(L1)) {
dat=subset(points,LOCATION==i) # select corresponding points for location [i]
t=data.frame(extract(raslist[[i]],dat),dat$ID) # run extract function with points & raster stack for location [i]
names(t)=c("VAR1","VAR2","ID")
TB=rbind(TB,t)
}
this works for me,
$(function() { $('.datepicker').datepicker({ startDate: '-0m', autoclose: true }); });
You can use this function, if you want to remove the element (without index)
removeItem(item) {
this.setState(prevState => {
data: prevState.data.filter(i => i !== item)
});
}
I used this and it worked. https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width
html {
scrollbar-width: none;
}
Note: User Agents must apply any scrollbar-width value set on the root element to the viewport.
Flexbox can easily fix this old problem:
.image-wrapper {
display: flex;
}
More information about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
you can access file config nginx,you can see root /path. in this
default of nginx apache at /var/www/html
I've spend some hours solving this problem. My solution is based on the following wishes/requirements:
I create a HandleErrorAttribute (see code comments for explanation of the details). A few details including "usings" has been left out, so the code might not compile. I add the filter to the global filters during application initialization in Global.asax.cs like this:
GlobalFilters.Filters.Add(new UnikHandleErrorAttribute());
Attribute:
namespace Foo
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
/// <summary>
/// Generel error handler attribute for Foo MVC solutions.
/// It handles uncaught exceptions from controller actions.
/// It outputs trace information.
/// If custom errors are enabled then the following is performed:
/// <ul>
/// <li>If the controller action return type is <see cref="JsonResult"/> then a <see cref="JsonResult"/> object with a <c>message</c> property is returned.
/// If the exception is of type <see cref="MySpecialExceptionWithUserMessage"/> it's message will be used as the <see cref="JsonResult"/> <c>message</c> property value.
/// Otherwise a localized resource text will be used.</li>
/// </ul>
/// Otherwise the exception will pass through unhandled.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class FooHandleErrorAttribute : HandleErrorAttribute
{
private readonly TraceSource _TraceSource;
/// <summary>
/// <paramref name="traceSource"/> must not be null.
/// </summary>
/// <param name="traceSource"></param>
public FooHandleErrorAttribute(TraceSource traceSource)
{
if (traceSource == null)
throw new ArgumentNullException(@"traceSource");
_TraceSource = traceSource;
}
public TraceSource TraceSource
{
get
{
return _TraceSource;
}
}
/// <summary>
/// Ctor.
/// </summary>
public FooHandleErrorAttribute()
{
var className = typeof(FooHandleErrorAttribute).FullName ?? typeof(FooHandleErrorAttribute).Name;
_TraceSource = new TraceSource(className);
}
public override void OnException(ExceptionContext filterContext)
{
var actionMethodInfo = GetControllerAction(filterContext.Exception);
// It's probably an error if we cannot find a controller action. But, hey, what should we do about it here?
if(actionMethodInfo == null) return;
var controllerName = filterContext.Controller.GetType().FullName; // filterContext.RouteData.Values[@"controller"];
var actionName = actionMethodInfo.Name; // filterContext.RouteData.Values[@"action"];
// Log the exception to the trace source
var traceMessage = string.Format(@"Unhandled exception from {0}.{1} handled in {2}. Exception: {3}", controllerName, actionName, typeof(FooHandleErrorAttribute).FullName, filterContext.Exception);
_TraceSource.TraceEvent(TraceEventType.Error, TraceEventId.UnhandledException, traceMessage);
// Don't modify result if custom errors not enabled
//if (!filterContext.HttpContext.IsCustomErrorEnabled)
// return;
// We only handle actions with return type of JsonResult - I don't use AjaxRequestExtensions.IsAjaxRequest() because ajax requests does NOT imply JSON result.
// (The downside is that you cannot just specify the return type as ActionResult - however I don't consider this a bad thing)
if (actionMethodInfo.ReturnType != typeof(JsonResult)) return;
// Handle JsonResult action exception by creating a useful JSON object which can be used client side
// Only provide error message if we have an MySpecialExceptionWithUserMessage.
var jsonMessage = FooHandleErrorAttributeResources.Error_Occured;
if (filterContext.Exception is MySpecialExceptionWithUserMessage) jsonMessage = filterContext.Exception.Message;
filterContext.Result = new JsonResult
{
Data = new
{
message = jsonMessage,
// Only include stacktrace information in development environment
stacktrace = MyEnvironmentHelper.IsDebugging ? filterContext.Exception.StackTrace : null
},
// Allow JSON get requests because we are already using this approach. However, we should consider avoiding this habit.
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
// Exception is now (being) handled - set the HTTP error status code and prevent caching! Otherwise you'll get an HTTP 200 status code and running the risc of the browser caching the result.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; // Consider using more error status codes depending on the type of exception
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Call the overrided method
base.OnException(filterContext);
}
/// <summary>
/// Does anybody know a better way to obtain the controller action method info?
/// See http://stackoverflow.com/questions/2770303/how-to-find-in-which-controller-action-an-error-occurred.
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
private static MethodInfo GetControllerAction(Exception exception)
{
var stackTrace = new StackTrace(exception);
var frames = stackTrace.GetFrames();
if(frames == null) return null;
var frame = frames.FirstOrDefault(f => typeof(IController).IsAssignableFrom(f.GetMethod().DeclaringType));
if (frame == null) return null;
var actionMethod = frame.GetMethod();
return actionMethod as MethodInfo;
}
}
}
I've developed the following jQuery plugin for client side ease of use:
(function ($, undefined) {
"using strict";
$.FooGetJSON = function (url, data, success, error) {
/// <summary>
/// **********************************************************
/// * UNIK GET JSON JQUERY PLUGIN. *
/// **********************************************************
/// This plugin is a wrapper for jQuery.getJSON.
/// The reason is that jQuery.getJSON success handler doesn't provides access to the JSON object returned from the url
/// when a HTTP status code different from 200 is encountered. However, please note that whether there is JSON
/// data or not depends on the requested service. if there is no JSON data (i.e. response.responseText cannot be
/// parsed as JSON) then the data parameter will be undefined.
///
/// This plugin solves this problem by providing a new error handler signature which includes a data parameter.
/// Usage of the plugin is much equal to using the jQuery.getJSON method. Handlers can be added etc. However,
/// the only way to obtain an error handler with the signature specified below with a JSON data parameter is
/// to call the plugin with the error handler parameter directly specified in the call to the plugin.
///
/// success: function(data, textStatus, jqXHR)
/// error: function(data, jqXHR, textStatus, errorThrown)
///
/// Example usage:
///
/// $.FooGetJSON('/foo', { id: 42 }, function(data) { alert('Name :' + data.name); }, function(data) { alert('Error: ' + data.message); });
/// </summary>
// Call the ordinary jQuery method
var jqxhr = $.getJSON(url, data, success);
// Do the error handler wrapping stuff to provide an error handler with a JSON object - if the response contains JSON object data
if (typeof error !== "undefined") {
jqxhr.error(function(response, textStatus, errorThrown) {
try {
var json = $.parseJSON(response.responseText);
error(json, response, textStatus, errorThrown);
} catch(e) {
error(undefined, response, textStatus, errorThrown);
}
});
}
// Return the jQueryXmlHttpResponse object
return jqxhr;
};
})(jQuery);
What do I get from all this? The final result is that
Client side example:
var success = function(data) {
alert(data.myjsonobject.foo);
};
var onError = function(data) {
var message = "Error";
if(typeof data !== "undefined")
message += ": " + data.message;
alert(message);
};
$.FooGetJSON(url, params, onSuccess, onError);
Comments are most welcome! I'll probably blog about this solution some day...
I think (from experimenting - MSDN is unhelpful here) that there is no direct way of doing this. Setting Criteria1
to an Array
is equivalent to using the tick boxes in the dropdown - as you say it will only filter a list based on items that match one of those in the array.
Interestingly, if you have the literal values "<>A"
and "<>B"
in the list and filter on these the macro recorder comes up with
Range.AutoFilter Field:=1, Criteria1:="=<>A", Operator:=xlOr, Criteria2:="=<>B"
which works. But if you then have the literal value "<>C"
as well and you filter for all three (using tick boxes) while recording a macro, the macro recorder replicates precisely your code which then fails with an error. I guess I'd call that a bug - there are filters you can do using the UI which you can't do with VBA.
Anyway, back to your problem. It is possible to filter values not equal to some criteria, but only up to two values which doesn't work for you:
Range("$A$1:$A$9").AutoFilter Field:=1, Criteria1:="<>A", Criteria2:="<>B", Operator:=xlAnd
There are a couple of workarounds possible depending on the exact problem:
=ISNUMBER(A2)
or =NOT(A2="A", A2="B", A2="C")
then filter on TRUE
Criteria1:=">-65535"
(or a suitable number lower than any you expect) which will filter out non-numeric values - assuming this is what you wantFor example:
Public Sub hideABCRows(rangeToFilter As Range)
Dim oCurrentCell As Range
On Error GoTo errHandler
Application.ScreenUpdating = False
For Each oCurrentCell In rangeToFilter.Cells
If oCurrentCell.Value = "A" Or oCurrentCell.Value = "B" Or oCurrentCell.Value = "C" Then
oCurrentCell.EntireRow.Hidden = True
End If
Next oCurrentCell
Application.ScreenUpdating = True
Exit Sub
errHandler:
Application.ScreenUpdating = True
End Sub
Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:
TypeError: 'numpy.float64' object cannot be interpreted as an integer
or
TypeError: 'numpy.float64' object is not iterable
The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:
def MinMax(x, mini=0, maxi=1)
return max(min(x,mini), maxi)
The solution was avoid numpy
or math
:
def MinMax(x, mini=0, maxi=1)
x = [x_aux if x_aux > mini else mini for x_aux in x]
x = [x_aux if x_aux < maxi else maxi for x_aux in x]
return max(min(x,mini), maxi)
Then, everything calm again. It was like one library possessed max
and min
!
Using other posters code with some tweaks:
<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
<tbody>
<tr>
<td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$(function() {
var oTable = $('#tbAD').DataTable({
"oLanguage": {
"sSearch": "Filter Data"
},
"iDisplayLength": -1,
"sPaginationType": "full_numbers",
"pageLength": 50,
});
$("#datepicker_from").datepicker();
$("#datepicker_to").datepicker();
$('#datepicker_from').change(function (e) {
oTable.draw();
});
$('#datepicker_to').change(function (e) {
oTable.draw();
});
$('#datepicker_clear_lnk').click(function (e) {
oTable.draw();
});
});
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
var startDate = new Date(data[9]).setHours(0,0,0,0);
if (min == null && max == null) { return true; }
if (min == null && startDate <= max) { return true; }
if (max == null && startDate >= min) { return true; }
if (startDate <= max && startDate >= min) { return true; }
return false;
}
);
});
</script>
A function to add or subtract business days from a given date, this doesn't account for holidays.
function dateFromBusinessDays($days, $dateTime=null) {
$dateTime = is_null($dateTime) ? time() : $dateTime;
$_day = 0;
$_direction = $days == 0 ? 0 : intval($days/abs($days));
$_day_value = (60 * 60 * 24);
while($_day !== $days) {
$dateTime += $_direction * $_day_value;
$_day_w = date("w", $dateTime);
if ($_day_w > 0 && $_day_w < 6) {
$_day += $_direction * 1;
}
}
return $dateTime;
}
use like so...
echo date("m/d/Y", dateFromBusinessDays(-7));
echo date("m/d/Y", dateFromBusinessDays(3, time() + 3*60*60*24));
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
This is something like the regular expression you need:
([^-]*)-
Quick tests in JavaScript:
/([^-]*)-/.exec('text-1')[1] // 'text'
/([^-]*)-/.exec('foo-bar-1')[1] // 'foo'
/([^-]*)-/.exec('-1')[1] // ''
/([^-]*)-/.exec('quux')[1] // explodes
or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.
So I run a functionally equivalent form of your code in an IPython notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()
I get what I believe to be very reasonable output.
It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?
The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.
import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline
# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)
I know this question is older but I was looking thru the answers and thought that I might be able to expand on the "dynamic" portion of the problem and possibly help someone out.
First and foremost I built this solution to solve a problem a couple of coworkers were having with inconstant and large data sets needing to be pivoted quickly.
This solution requires the creation of a stored procedure so if that is out of the question for your needs please stop reading now.
This procedure is going to take in the key variables of a pivot statement to dynamically create pivot statements for varying tables, column names and aggregates. The Static column is used as the group by / identity column for the pivot(this can be stripped out of the code if not necessary but is pretty common in pivot statements and was necessary to solve the original issue), the pivot column is where the end resultant column names will be generated from, and the value column is what the aggregate will be applied to. The Table parameter is the name of the table including the schema (schema.tablename) this portion of the code could use some love because it is not as clean as I would like it to be. It worked for me because my usage was not publicly facing and sql injection was not a concern. The Aggregate parameter will accept any standard sql aggregate 'AVG', 'SUM', 'MAX' etc. The code also defaults to MAX as an aggregate this is not necessary but the audience this was originally built for did not understand pivots and were typically using max as an aggregate.
Lets start with the code to create the stored procedure. This code should work in all versions of SSMS 2005 and above but I have not tested it in 2005 or 2016 but I can not see why it would not work.
create PROCEDURE [dbo].[USP_DYNAMIC_PIVOT]
(
@STATIC_COLUMN VARCHAR(255),
@PIVOT_COLUMN VARCHAR(255),
@VALUE_COLUMN VARCHAR(255),
@TABLE VARCHAR(255),
@AGGREGATE VARCHAR(20) = null
)
AS
BEGIN
SET NOCOUNT ON;
declare @AVAIABLE_TO_PIVOT NVARCHAR(MAX),
@SQLSTRING NVARCHAR(MAX),
@PIVOT_SQL_STRING NVARCHAR(MAX),
@TEMPVARCOLUMNS NVARCHAR(MAX),
@TABLESQL NVARCHAR(MAX)
if isnull(@AGGREGATE,'') = ''
begin
SET @AGGREGATE = 'MAX'
end
SET @PIVOT_SQL_STRING = 'SELECT top 1 STUFF((SELECT distinct '', '' + CAST(''[''+CONVERT(VARCHAR,'+ @PIVOT_COLUMN+')+'']'' AS VARCHAR(50)) [text()]
FROM '+@TABLE+'
WHERE ISNULL('+@PIVOT_COLUMN+','''') <> ''''
FOR XML PATH(''''), TYPE)
.value(''.'',''NVARCHAR(MAX)''),1,2,'' '') as PIVOT_VALUES
from '+@TABLE+' ma
ORDER BY ' + @PIVOT_COLUMN + ''
declare @TAB AS TABLE(COL NVARCHAR(MAX) )
INSERT INTO @TAB EXEC SP_EXECUTESQL @PIVOT_SQL_STRING, @AVAIABLE_TO_PIVOT
SET @AVAIABLE_TO_PIVOT = (SELECT * FROM @TAB)
SET @TEMPVARCOLUMNS = (SELECT replace(@AVAIABLE_TO_PIVOT,',',' nvarchar(255) null,') + ' nvarchar(255) null')
SET @SQLSTRING = 'DECLARE @RETURN_TABLE TABLE ('+@STATIC_COLUMN+' NVARCHAR(255) NULL,'+@TEMPVARCOLUMNS+')
INSERT INTO @RETURN_TABLE('+@STATIC_COLUMN+','+@AVAIABLE_TO_PIVOT+')
select * from (
SELECT ' + @STATIC_COLUMN + ' , ' + @PIVOT_COLUMN + ', ' + @VALUE_COLUMN + ' FROM '+@TABLE+' ) a
PIVOT
(
'+@AGGREGATE+'('+@VALUE_COLUMN+')
FOR '+@PIVOT_COLUMN+' IN ('+@AVAIABLE_TO_PIVOT+')
) piv
SELECT * FROM @RETURN_TABLE'
EXEC SP_EXECUTESQL @SQLSTRING
END
Next we will get our data ready for the example. I have taken the data example from the accepted answer with the addition of a couple of data elements to use in this proof of concept to show the varied outputs of the aggregate change.
create table temp
(
date datetime,
category varchar(3),
amount money
)
insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('1/1/2012', 'ABC', 2000.00) -- added
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'DEF', 1500.00) -- added
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('2/10/2012', 'DEF', 800.00) -- addded
insert into temp values ('3/1/2012', 'ABC', 1100.00)
The following examples show the varied execution statements showing the varied aggregates as a simple example. I did not opt to change the static, pivot, and value columns to keep the example simple. You should be able to just copy and paste the code to start messing with it yourself
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','max'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','avg'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','min'
This execution returns the following data sets respectively.
No need to trim the array, simply address it as a circular buffer (index % maxlen). This will ensure it never goes over the limit (implementing a circular buffer means that once you get to the end you wrap around to the beginning again - not possible to overrun the end of the array).
For example:
var container = new Array ();
var maxlen = 100;
var index = 0;
// 'store' 1538 items (only the last 'maxlen' items are kept)
for (var i=0; i<1538; i++) {
container [index++ % maxlen] = "storing" + i;
}
// get element at index 11 (you want the 11th item in the array)
eleventh = container [(index + 11) % maxlen];
// get element at index 11 (you want the 11th item in the array)
thirtyfifth = container [(index + 35) % maxlen];
// print out all 100 elements that we have left in the array, note
// that it doesn't matter if we address past 100 - circular buffer
// so we'll simply get back to the beginning if we do that.
for (i=0; i<200; i++) {
document.write (container[(index + i) % maxlen] + "<br>\n");
}
Such difference between the output of du -sh
and df -h
may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted
to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
For instance:
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
As you see, simply adding the HttpServletRequest
and HttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession
object too.
EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.
I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.
You can change height and width with css:
#search {
height: 100px;
width: 400px;
}
It's worth pointing out that safari on OSX ignores most input button styles, however.
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
This is what I ended up doing:
<div style="height: 600px">
<img src="assets/zzzzz.png" alt="Error" style="max-width: 100%;
max-height: 100%; display:block; margin:auto;" />
</div>
Which will limit the image height to 600px and will horizontally-center (or resize down if the parent width is smaller) to the parent container, maintaining proportions.
Use FileMode.Truncate
everytime you create the file. Also place the File.Create
inside a try
catch
.
Try below code:
@Override
public void onBackPressed() {
Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (myFragment != null && myFragment instanceof StepOneFragment) {
finish();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Say you have a DIV
you want centred horizontally:
<div id="foo">Lorem ipsum</div>
In the CSS you'd style it with this:
#foo
{
margin:0 auto;
width:30%;
}
Which states that you have a top and bottom margin of zero pixels, and on either left or right, automatically work out how much is needed to be even.
Doesn't really matter what you put in for the width, as long as it's there and isn't 100%. Otherwise you wouldn't be setting the centre on anything.
But if you float it, left or right, then the bets are off since that pulls it out of the normal flow of elements on the page and the auto margin setting won't work.
One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files
Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:
To check OleDbConnection State use this:
if (oconn.State == ConnectionState.Open)
{
oconn.Close();
}
State
return the ConnectionState
public override ConnectionState State { get; }
Here are the other ConnectionState
enum
public enum ConnectionState
{
//
// Summary:
// The connection is closed.
Closed = 0,
//
// Summary:
// The connection is open.
Open = 1,
//
// Summary:
// The connection object is connecting to the data source. (This value is reserved
// for future versions of the product.)
Connecting = 2,
//
// Summary:
// The connection object is executing a command. (This value is reserved for future
// versions of the product.)
Executing = 4,
//
// Summary:
// The connection object is retrieving data. (This value is reserved for future
// versions of the product.)
Fetching = 8,
//
// Summary:
// The connection to the data source is broken. This can occur only after the connection
// has been opened. A connection in this state may be closed and then re-opened.
// (This value is reserved for future versions of the product.)
Broken = 16
}
Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:
Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.
I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts
127.0.0.1 svn.openwrt.org
Afterwards, you can use socat to create a tcp tunnel to a local port:
while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done
You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.
Just replace the port and server addresses on your own needs.
Actually this will give you repeated indices np.random.random_integers(0, len(df), N)
where N
is a large number.
I have not tried this option, but the following information is given in the vim help system (i.e. help eol):
'endofline' 'eol' boolean (default on)
local to buffer
{not in Vi}
When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file. This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.
Normally you don't have to set or reset this option. When 'binary' is off the value is not used when writing the file. When 'binary' is on it is used to remember the presence of a for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to.
You may be interested in the answer to a previous question as well: "Why should files end with a newline".
None has worked for me. But his one did.
Since the Bootstrap 4 .row class is now display:flex you can simply use the new align-self-center flexbox utility on any column to vertically center it:
<div class="row">
<div class="col-6 align-self-center">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
I learned about it from https://medium.com/wdstack/bootstrap-4-vertical-center-1211448a2eff
I really needed this in C# and found Center MessageBox C#
Here's a nicely formatted version
using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
public class MessageBoxEx
{
private static IWin32Window _owner;
private static HookProc _hookProc;
private static IntPtr _hHook;
public static DialogResult Show(string text)
{
Initialize();
return MessageBox.Show(text);
}
public static DialogResult Show(string text, string caption)
{
Initialize();
return MessageBox.Show(text, caption);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
{
Initialize();
return MessageBox.Show(text, caption, buttons);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton, options);
}
public static DialogResult Show(IWin32Window owner, string text)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text);
}
public static DialogResult Show(IWin32Window owner, string text, string caption)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton, options);
}
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
public const int WH_CALLWNDPROCRET = 12;
public enum CbtHookAction : int
{
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
} ;
static MessageBoxEx()
{
_hookProc = new HookProc(MessageBoxHookProc);
_hHook = IntPtr.Zero;
}
private static void Initialize()
{
if (_hHook != IntPtr.Zero)
{
throw new NotSupportedException("multiple calls are not supported");
}
if (_owner != null)
{
_hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(_hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = _hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(_hHook);
_hHook = IntPtr.Zero;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(_owner.Handle, ref recParent);
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.
You can use the perl debugger on a trivial program, like so:
perl -de1
Alternatively there's Alexis Sukrieh's Perl Console application, but I haven't used it.
If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.
Following is a work-around:
Running the shortcut will execute your batch script as administrator.
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
Nobody actualy brought it so, the way it was made to work is animation-play-state set to paused.
The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.
SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';
The following solution seems like a good option,
<label ng-repeat="fruit in fruits">
<input
type="checkbox"
ng-model="fruit.checked"
ng-value="true"
> {{fruit.fruitName}}
</label>
And in controller model value fruits
will be like this
$scope.fruits = [
{
"name": "apple",
"checked": true
},
{
"name": "orange"
},
{
"name": "grapes",
"checked": true
}
];
Join the same table back to itself. Use an inner join so that rows that don't match are discarded. In the joined set, there will be rows that have a matching ARIDNR in another row in the table with a different LIEFNR. Allow those ARIDNR to appear in the final set.
SELECT * FROM YourTable WHERE ARIDNR IN (
SELECT a.ARIDNR FROM YourTable a
JOIN YourTable b on b.ARIDNR = a.ARIDNR AND b.LIEFNR <> a.LIEFNR
)
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
I had a hell of a time finding this option in SQL Management Studio 2012, but I finally found it. The option is hiding in the Advanced button in the screen below.
I always assumed this contained just assumed advanced options for File generation, since that's what it's next to, but it turns out someone at MS is just really bad at UI design in this case. HTH somebody who comes to this thread like I did.
Why not using: { position: fixed; bottom: 0 }
?
Follow this link for solution: Android Lint contentDescription warning
Resolved this warning by setting attribute android:contentDescription for my ImageView
android:contentDescription="@string/desc"
Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription
This defines text that briefly describes the content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.
Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.
This link for explanation: Accessibility, It's Impact and Development Resources
Many Android users have disabilities that require them to interact with their Android devices in different ways. These include users who have visual, physical or age-related disabilities that prevent them from fully seeing or using a touchscreen.
Android provides accessibility features and services for helping these users navigate their devices more easily, including text-to-speech, haptic feedback, trackball and D-pad navigation that augments their experience. Android application developers can take advantage of these services to make their applications more accessible and also build their own accessibility services.
This guide is for making your app accessible: Making Apps More Accessible
Making sure your application is accessible to all users is relatively easy, particularly when you use framework-provided user interface components. If you only use these standard components for your application, there are just a few steps required to ensure your application is accessible:
Label your ImageButton, ImageView, EditText, CheckBox and other user interface controls using the android:contentDescription attribute.
Make all of your user interface elements accessible with a directional controller, such as a trackball or D-pad.
Test your application by turning on accessibility services like TalkBack and Explore by Touch, and try using your application using only directional controls.
This should work.
$(".formData").val("valuesgoeshere")
For empty
$(".formData").val("")
If this does not work, you should post a jsFiddle.
Demo:
$(function() {_x000D_
$(".resetInput").on("click", function() {_x000D_
$(".formData").val("");_x000D_
});_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print()
function also offers the sep
parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Appsamuck iPhone tutorials is aiming for 31 days of tutorials ending in 31 small apps developed for the iPhone all the source code for which is available to download. They also provide a commercial service to build apps!
If you want to know if you can do the coding, well at least you can download the code and see if anything there is helpful for your needs. On the flip side you can also get a quote from them for developing the app for you, so you can try both sides of the coin, outsource and in-house. Of course it all depends on how much time you have too! It's certainly worth a look!
(OK, after my last disastrous attempt to try and post a useful piece of help, I went off hunting around!)
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
To Get the Value when the radio button is checked
if (rdbtnSN06.IsChecked == true)
{
string RadiobuttonContent =Convert.ToString(rdbtnSN06.Content.ToString());
}
else
{
string RadiobuttonContent =Convert.ToString(rdbtnSN07.Content.ToString());
}
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
I think the simplest way might be:
values.reduce(function(a, b){return a+b;})
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
Your solution requires some ajax method to pass the html to a back-end server that has a html to pdf facility and then returning the pdf output generated back to the browser.
First setting up the client side code, we will setup the jquery code as
var options = {
"url": "/pdf/generate/convert_to_pdf.php",
"data": "data=" + $("#content").html(),
"type": "post",
}
$.ajax(options)
Then intercept the data from the html2pdf generation script (somewhere from the internet).
convert_to_pdf.php
(given as url in JQUERY code) looks like this -
<?php
$html = $_POST['data'];
$pdf = html2pdf($html);
header("Content-Type: application/pdf"); //check this is the proper header for pdf
header("Content-Disposition: attachment; filename='some.pdf';");
echo $pdf;
?>
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
In your ASP.NET page:
<asp:Label ID="UserNameLabel" runat="server" />
In your code behind (assuming you're using C#):
function Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
UserNameLabel.Text = "User Name";
}
}
They should have made 0 an integer even when there's an enum function overload.
I knew C# core team rationale for mapping 0 to enum, but still, it is not as orthogonal as it should be. Example from Npgsql.
Test example:
namespace Craft
{
enum Symbol { Alpha = 1, Beta = 2, Gamma = 3, Delta = 4 };
class Mate
{
static void Main(string[] args)
{
JustTest(Symbol.Alpha); // enum
JustTest(0); // why enum
JustTest((int)0); // why still enum
int i = 0;
JustTest(Convert.ToInt32(0)); // have to use Convert.ToInt32 to convince the compiler to make the call site use the object version
JustTest(i); // it's ok from down here and below
JustTest(1);
JustTest("string");
JustTest(Guid.NewGuid());
JustTest(new DataTable());
Console.ReadLine();
}
static void JustTest(Symbol a)
{
Console.WriteLine("Enum");
}
static void JustTest(object o)
{
Console.WriteLine("Object");
}
}
}
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...
String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);
or disregarding the prefix syntax:
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);
Here is example:
You have a.bat:
@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END
and b.bat called conditionally from a.bat:
@echo off
echo "This is b.bat"
You can use Linq in case you are using .NET 3.5 or later:
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
If you can't use Linq then you can do it like this:
var temp = new List<string>();
foreach (var s in test)
{
if (!string.IsNullOrEmpty(s))
temp.Add(s);
}
test = temp.ToArray();
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
Yet another option would be:
SELECT * FROM mytable
WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');
select regexp_replace(field, E'[\\n\\r]+', ' ', 'g' )
read the manual http://www.postgresql.org/docs/current/static/functions-matching.html
Try this, works fine on web-kit
.border { _x000D_
width: 400px;_x000D_
padding: 20px;_x000D_
border-top: 10px solid #FFFF00;_x000D_
border-bottom:10px solid #FF0000;_x000D_
background-image: _x000D_
linear-gradient(#FFFF00, #FF0000),_x000D_
linear-gradient(#FFFF00, #FF0000)_x000D_
;_x000D_
background-size:10px 100%;_x000D_
background-position:0 0, 100% 0;_x000D_
background-repeat:no-repeat;_x000D_
}
_x000D_
<div class="border">Hello!</div>
_x000D_
If you really just want to subset each data frame by an index that exists in both data frames, you can do this with the 'match' function, like so:
data_A[match(data_B$index, data_A$index, nomatch=0),]
data_B[match(data_A$index, data_B$index, nomatch=0),]
This is, though, the same as:
data_A[data_A$index %in% data_B$index,]
data_B[data_B$index %in% data_A$index,]
Here is a demo:
# Set seed for reproducibility.
set.seed(1)
# Create two sample data sets.
data_A <- data.frame(index=sample(1:200, 90, rep=FALSE), value=runif(90))
data_B <- data.frame(index=sample(1:200, 120, rep=FALSE), value=runif(120))
# Subset data of each data frame by the index in the other.
t_A <- data_A[match(data_B$index, data_A$index, nomatch=0),]
t_B <- data_B[match(data_A$index, data_B$index, nomatch=0),]
# Make sure they match.
data.frame(t_A[order(t_A$index),], t_B[order(t_B$index),])[1:20,]
# index value index.1 value.1
# 27 3 0.7155661 3 0.65887761
# 10 12 0.6049333 12 0.14362694
# 88 14 0.7410786 14 0.42021589
# 56 15 0.4525708 15 0.78101754
# 38 18 0.2075451 18 0.70277874
# 24 23 0.4314737 23 0.78218212
# 34 32 0.1734423 32 0.85508236
# 22 38 0.7317925 38 0.56426384
# 84 39 0.3913593 39 0.09485786
# 5 40 0.7789147 40 0.31248966
# 74 43 0.7799849 43 0.10910096
# 71 45 0.2847905 45 0.26787813
# 57 46 0.1751268 46 0.17719454
# 25 48 0.1482116 48 0.99607737
# 81 53 0.6304141 53 0.26721208
# 60 58 0.8645449 58 0.96920881
# 30 59 0.6401010 59 0.67371223
# 75 61 0.8806190 61 0.69882454
# 63 64 0.3287773 64 0.36918946
# 19 70 0.9240745 70 0.11350771
A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.
See here: code of ringbuffer
I checked both Guava's EvictingQueue and ArrayDeque.
ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.
EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.
Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).
A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RingBuffer<T> implements Iterable<T> {
private T[] buffer; // queue elements
private int count = 0; // number of elements on queue
private int indexOut = 0; // index of first element of queue
private int indexIn = 0; // index of next available slot
// cast needed since no generic array creation in Java
public RingBuffer(int capacity) {
buffer = (T[]) new Object[capacity];
}
public boolean isEmpty() {
return count == 0;
}
public int size() {
return count;
}
public void push(T item) {
if (count == buffer.length) {
throw new RuntimeException("Ring buffer overflow");
}
buffer[indexIn] = item;
indexIn = (indexIn + 1) % buffer.length; // wrap-around
count++;
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Ring buffer underflow");
}
T item = buffer[indexOut];
buffer[indexOut] = null; // to help with garbage collection
count--;
indexOut = (indexOut + 1) % buffer.length; // wrap-around
return item;
}
public Iterator<T> iterator() {
return new RingBufferIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class RingBufferIterator implements Iterator<T> {
private int i = 0;
public boolean hasNext() {
return i < count;
}
public void remove() {
throw new UnsupportedOperationException();
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return buffer[i++];
}
}
}
Check out the request module.
It's more full featured than node's built-in http client.
var request = require('request');
var propertiesObject = { field1:'test1', field2:'test2' };
request({url:url, qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
});
I encountered the same issue when trying to use Cordova. Turns out I already had brew, try which brew
, but it was outdated. So, I had to update it first:
brew update
brew install ant
If you're looking for a solution for Redshift, this will work with the frame clause:
SELECT date,
last_value(columnName ignore nulls)
over (order by date
rows between unbounded preceding and current row) as columnName
from tbl
Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?
Since you don't use any suffix, the literals 13
and 4
are interpreted as integer:
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
Thus, since you declare 13
as integer, integer division will be performed:
For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined division operators are listed below. The operators all compute the quotient of x and y.
Integer division:
int operator /(int x, int y); uint operator /(uint x, uint y); long operator /(long x, long y); ulong operator /(ulong x, ulong y);
And so rounding down occurs:
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
If you do the following:
int x = 13f / 4f;
You'll receive a compiler error, since a floating-point division (the /
operator of 13f
) results in a float, which cannot be cast to int implicitly.
If you want the division to be a floating-point division, you'll have to make the result a float:
float x = 13 / 4;
Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0
. To explicitly declare the operands as float, using the f
suffix (13f
, 4f
).
I was facing the same issue. In pom.xml I have specified maven compiler plugin to pick 1.7 as source and target. Even then when I would import the git project in eclipse it would pick 1.5 as compile version for the project. To be noted that the eclipse has installed runtime set to JDK 1.8
I also checked that none of the .classpath .impl or .project file is checked in git repository.
Solution that worked for me: I simply deleted .classpath files and did a 'maven-update project'. .classpath file was regenerated and it picked up 1.7 as compile version from pom file.
In 2013, you should use something like Silex or Slim
Silex example:
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
Slim example:
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
<div class="d-flex justify-content-center align-items-center container ">
<div class="row ">
<form action="">
<div class="form-group">
<label for="inputUserName" class="control-label">Enter UserName</label>
<input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
<small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Enter Password</label>
<input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">
</div>
</form>
</div>
</div>
The alternative formulation of the question added in a later edit seems still to be unanswered: how to specify that among the children of an element, there must be one named child3
, one named child4
, and any number named child1
or child2
, with no constraint on the order in which the children appear.
This is a straightforwardly definable regular language, and the content model you need is isomorphic to a regular expression defining the set of strings in which the digits '3' and '4' each occur exactly once, and the digits '1' and '2' occur any number of times. If it's not obvious how to write this, it may help to think about what kind of finite state machine you would build to recognize such a language. It would have at least four distinct states:
No matter what state the automaton is in, '1' and '2' may be read; they do not change the machine's state. In the initial state, '3' or '4' will also be accepted; in the intermediate states, only '4' or '3' is accepted; in the final state, neither '3' nor '4' is accepted. The structure of the regular expression is easiest to understand if we first define a regex for the subset of our language in which only '3' and '4' occur:
(34)|(43)
To allow '1' or '2' to occur any number of times at a given location, we can insert (1|2)*
(or [12]*
if our regex language accepts that notation). Inserting this expression at all available locations, we get
(1|2)*((3(1|2)*4)|(4(1|2)*3))(1|2)*
Translating this into a content model is straightforward. The basic structure is equivalent to the regex (34)|(43)
:
<xsd:complexType name="paul0">
<xsd:choice>
<xsd:sequence>
<xsd:element ref="child3"/>
<xsd:element ref="child4"/>
</xsd:sequence>
<xsd:sequence>
<xsd:element ref="child4"/>
<xsd:element ref="child3"/>
</xsd:sequence>
</xsd:choice>
</xsd:complexType>
Inserting a zero-or-more choice of child1
and child2
is straightforward:
<xsd:complexType name="paul1">
<xsd:sequence>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="child1"/>
<xsd:element ref="child2"/>
</xsd:choice>
<xsd:choice>
<xsd:sequence>
<xsd:element ref="child3"/>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="child1"/>
<xsd:element ref="child2"/>
</xsd:choice>
<xsd:element ref="child4"/>
</xsd:sequence>
<xsd:sequence>
<xsd:element ref="child4"/>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="child1"/>
<xsd:element ref="child2"/>
</xsd:choice>
<xsd:element ref="child3"/>
</xsd:sequence>
</xsd:choice>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="child1"/>
<xsd:element ref="child2"/>
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
If we want to minimize the bulk a bit, we can define a named group for the repeating choices of child1
and child2
:
<xsd:group name="onetwo">
<xsd:choice>
<xsd:element ref="child1"/>
<xsd:element ref="child2"/>
</xsd:choice>
</xsd:group>
<xsd:complexType name="paul2">
<xsd:sequence>
<xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
<xsd:choice>
<xsd:sequence>
<xsd:element ref="child3"/>
<xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element ref="child4"/>
</xsd:sequence>
<xsd:sequence>
<xsd:element ref="child4"/>
<xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element ref="child3"/>
</xsd:sequence>
</xsd:choice>
<xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
In XSD 1.1, some of the constraints on all
-groups have been lifted, so it's possible to define this content model more concisely:
<xsd:complexType name="paul3">
<xsd:all>
<xsd:element ref="child1" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element ref="child2" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element ref="child3"/>
<xsd:element ref="child4"/>
</xsd:all>
</xsd:complexType>
But as can be seen from the examples given earlier, these changes to all
-groups do not in fact change the expressive power of the language; they only make the definition of certain kinds of languages more succinct.
You can use the Array.prototype.some() in the following way (as mentioned in the other answers):
https://jsfiddle.net/h1d69exj/2/
function findIndexInData(data, property, value) {
var result = -1;
data.some(function (item, i) {
if (item[property] === value) {
result = i;
return true;
}
});
return result;
}
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
alert(findIndexInData(data, 'prop2', "yutu")); // shows index of 1
Try the code below. It will work if you enter multiple lines in a single column.
create table products (prod_id number , prod_desc varchar2(50));
insert into products values(1,'test first
test second
test third');
select replace(replace(prod_desc,chr(10),' '),chr(13),' ') from products where prod_id=2;
Output :test first test second test third
JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
This can be solved by replacing Object
with Object[]
in the argument for geForObject("url",Object[].class)
.
References:
Shell environment does not load when running remote ssh command. You can edit ssh environment file:
vi ~/.ssh/environment
Its format is:
VAR1=VALUE1
VAR2=VALUE2
Also, check sshd
configuration for PermitUserEnvironment=yes
option.
>>> d = {u"a": u"b", u"c": u"d"}
>>> d
{u'a': u'b', u'c': u'd'}
>>> import json
>>> import yaml
>>> d = {u"a": u"b", u"c": u"d"}
>>> yaml.safe_load(json.dumps(d))
{'a': 'b', 'c': 'd'}
We encountered the same error message, with a completely different cause.
Setup:
When we added the second swift test case, after a clean (or on a team mate's machine), we saw this error when building the unit test target.
It was fixed by adding a dummy Obj-C class to the unit test target.
A reference is really a pointer with enough sugar to make it taste nice... ;)
But it also uses a different syntax to pointers, which makes it a bit easier to use references than pointers. Because of this, we don't need &
when calling the function that takes the pointer - the compiler deals with that for you. And you don't need *
to get the content of a reference.
To call a reference an alias is a pretty accurate description - it is "another name for the same thing". So when a
is passed as a reference, we're really passing a
, not a copy of a
- it is done (internally) by passing the address of a
, but you don't need to worry about how that works [unless you are writing your own compiler, but then there are lots of other fun things you need to know when writing your own compiler, that you don't need to worry about when you are just programming].
Note that references work the same way for int
or a class
type.
This should work for all IE8 minor versions
if ($.browser.msie && parseInt($.browser.version, 10) === 8) {
alert('IE8');
} else {
alert('Non IE8');
}
-- update
Please note that $.browser is removed from jQuery 1.9
There are 30+ answers here and some are same and some are unique. This answer is based on few of those answers. One of them being @Lenn Dolling's answer.
It combines 3 IDs and creates a 32-digit hex string. It has worked very well for me.
3 IDs are:
Pseudo-ID - It is generated based on physical device specifications
ANDROID_ID - Settings.Secure.ANDROID_ID
Bluetooth Address - Bluetooth adapter address
It will return something like this: 551F27C060712A72730B0A0F734064B1
Note: You can always add more IDs to the longId
string. For example, Serial #. wifi adapter address. IMEI. This way you are making it more unique per device.
@SuppressWarnings("deprecation")
@SuppressLint("HardwareIds")
public static String generateDeviceIdentifier(Context context) {
String pseudoId = "35" +
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 +
Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 +
Build.HOST.length() % 10 +
Build.ID.length() % 10 +
Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 +
Build.TYPE.length() % 10 +
Build.USER.length() % 10;
String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String btId = "";
if (bluetoothAdapter != null) {
btId = bluetoothAdapter.getAddress();
}
String longId = pseudoId + androidId + btId;
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(longId.getBytes(), 0, longId.length());
// get md5 bytes
byte md5Bytes[] = messageDigest.digest();
// creating a hex string
String identifier = "";
for (byte md5Byte : md5Bytes) {
int b = (0xFF & md5Byte);
// if it is a single digit, make sure it have 0 in front (proper padding)
if (b <= 0xF) {
identifier += "0";
}
// add number to string
identifier += Integer.toHexString(b);
}
// hex string to uppercase
identifier = identifier.toUpperCase();
return identifier;
} catch (Exception e) {
Log.e("TAG", e.toString());
}
return "";
}
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
This can be highly customized to suit your project!
A major cause of EXC_BAD_ACCESS is from trying to access released objects.
To find out how to troubleshoot this, read this document: DebuggingAutoReleasePool
Even if you don't think you are "releasing auto-released objects", this will apply to you.
This method works extremely well. I use it all the time with great success!!
In summary, this explains how to use Cocoa's NSZombie debugging class and the command line "malloc_history" tool to find exactly what released object has been accessed in your code.
Sidenote:
Running Instruments and checking for leaks will not help troubleshoot EXC_BAD_ACCESS. I'm pretty sure memory leaks have nothing to do with EXC_BAD_ACCESS. The definition of a leak is an object that you no longer have access to, and you therefore cannot call it.
UPDATE: I now use Instruments to debug Leaks. From Xcode 4.2, choose Product->Profile and when Instruments launches, choose "Zombies".
For committing, I use the following strategies:
commit as often as possible.
Each feature change/bugfix should get its own commit (don't commit many files at once since that will make the history for that file unclear -- e.g. If I change a logging module and a GUI module independently and I commit both at once, both changes will be visible in both file histories. This makes reading a file history difficult),
don't break the build on any commit -- it should be possible to retrieve any version of the repository and build it.
All files that are necessary for building and running the app should be in SVN. Test files and such should not, unless they are part of the unit tests.
I show you here the easiest way using Vs2017 and Vs2019 Open your xsd with Visual Studio and generate a sample xml file as in the url suggested.
2. Within “XML Schema Explorer” scroll all the way down to find the root/data node. Right click on root/data node and it will show “Generate Sample XML”. If it does not show, it means you are not on the data element node but you are on any of the data definition node.
As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.
Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,
int main()
{
int a = func();
}
int func()
{
return 1;
}
However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.
int func();
int main()
{
int a = func();
}
int func()
{
return 1;
}
You can chain your where
s directly, without function(q)
. There's also a nice date handling package in laravel, called Carbon. So you could do something like:
$projects = Project::where('recur_at', '>', Carbon::now())
->where('recur_at', '<', Carbon::now()->addWeek())
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.
EDIT: As Joel said, you could do:
$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
If you're into libraries, why not MyLibrary and getStyle.
The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.
Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.
curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
http://example.com/service
Using the exact JSON data from the question, the full command line would become:
curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],
"question":"Which band?",
"answers":[{"id":"a0","answer":"Answer1"},
{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Note: JSON data wrapped only for readability, not valid for curl
request.
Almost everything has been mentioned so far, so I'll only add that instead of pdb.set_trace()
one can use ipdb.set_trace() which uses iPython and therefore is more powerful (autocomplete and other goodies). This requires ipdb package, so you only need to pip install ipdb
Like this:
{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}
I came up with this solution which works in my case where I have objects created on multiple threads and are serializable:
public abstract class ObjBase implements Serializable
private static final long serialVersionUID = 1L;
private static final AtomicLong atomicRefId = new AtomicLong();
// transient field is not serialized
private transient long refId;
// default constructor will be called on base class even during deserialization
public ObjBase() {
refId = atomicRefId.incrementAndGet()
}
public long getRefId() {
return refId;
}
}
First off I would say use boost tokenizer.
Alternatively if your data is space separated then the string stream library is very useful.
But both the above have already been covered.
So as a third C-Like alternative I propose copying the std::string into a buffer for modification.
std::string data("The data I want to tokenize");
// Create a buffer of the correct length:
std::vector<char> buffer(data.size()+1);
// copy the string into the buffer
strcpy(&buffer[0],data.c_str());
// Tokenize
strtok(&buffer[0]," ");
You can use something like:
<beans>
<bean id="myBean" class="..." init-method="init"/>
</beans>
This will call the "init" method when the bean is instantiated.
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource
and supply it with StringReader
.
String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());
I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in
private void SetFont(Form f, string name, int size, FontStyle style)
{
Font replacementFont = new Font(name, size, style);
f.Font = replacementFont;
}
Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.
/// To call the function do this.
/// e.g in the form load event etc.
public Form1()
{
InitializeComponent();
SetFont(this, "Arial", 8, FontStyle.Bold);
// This sets the whole form and
// everything below it.
// Shaun Cassidy.
}
You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.
/// and then import the namespace
using Droitech.TextFont;
/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);
Simple.
Maybe try this code:
void wait (double x) {
DateTime t = DateTime.Now;
DateTime tf = DateTime.Now.AddSeconds(x);
while (t < tf) {
t = DateTime.Now;
}
}
Here's the steps to achieve this:
Download the sendmail.zip through this link
Open sendmail.ini and set the configuration as follows:
smtp_server=smtp.gmail.com
hostname=localhost
Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.
Run your WAMP Server. Enable ssl_module under Apache Module.
Next, enable php_openssl and php_sockets under PHP.
Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.
[mail function] ; For Win32 only. ; http://php.net/smtp ;SMTP = ; http://php.net/smtp-port ;smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
I hope this will work for you..
I tried pretty much everything suggested in the answers above. Unfortunately, nothing worked. Then I signout out of my Github account on VS Code and signed in again. Added the remote origin with the following command.
git remote add origin https://github.com/pete/first_app.git
And it was working.
#include <boost/locale.hpp>
namespace lcv = boost::locale::conv;
inline std::wstring fromUTF8(const std::string& s)
{ return lcv::utf_to_utf<wchar_t>(s); }
inline std::string toUTF8(const std::wstring& ws)
{ return lcv::utf_to_utf<char>(ws); }
The procedure name should be in caps while creating procedure in database. You may use small letters for your procedure name while calling from Java class like:
String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";
In database the name of procedure should be:
GETDBUSERBYUSERID -- (all letters in caps only)
This serves as one of the solutions for this problem.
My windows laptop has both the clients 32 & 64 bit I started facing all of sudden then I reordered the path variable like below
Before:
C:\app\oracle64\product\12.1.0\client_1\bin;
C:\app\oracle32\product\12.1.0\client_1\bin;
After:
C:\app\oracle32\product\12.1.0\client_1\bin;
C:\app\oracle64\product\12.1.0\client_1\bin;
started working... Hope this helps everyone.
a bit late but this is what i found out...
window.close()
will only work (IE is an exception) if the window that you are trying to close()
was opened by a script using window.open() method.
!(please see the comment of @killstreet below about anchor tag with target _blank)
TLDR: chrome & firefox allow to close them.
you will get console error: Scripts may not close windows that were not opened by script. as an error and nothing else.
you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.
i couldn't find any way to know if the page was opened from a open() or not, and close will not throw and errors. this will NOT print "test":
try{
window.close();
}
catch (e){
console.log("text");
}
you can read in MDN more about the close() function
If it says:
The term 'gradlew' is not recognized
Then using following command
npm start -- --reset-cache
worked for me. cheers!
Since MongoDB version 3.2 you can use updateMany():
> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
Try var
var s = new List<string> { "a", "bk", "ca", "d" };
on mac when anything else seems to work - select with mouse, right click choose copy. uff
Your onCreate()
method has several huge flaws:
1) onCreate
prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView
's text here more than ONE time as only the last change will be drawn and thus visible to the user!
2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep()
or Thread.wait()
in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)
What your initialization of your Activity does is:
TextView
object t
!TextView
in the variable t
later.t
(but keep in mind: it will be displayed only after onCreate()
finishes and the main event loop of your application runs!)onCreate
method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)onCreate()
method finishes and several other Activity lifecycle methods have been processed!The solution:
Set text only once in onCreate()
- this must be the first text that should be visible.
Create a Runnable
and a Handler
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
// do whatever you want to change here, like:
t.setText("Second text to display!");
}
};
private final Handler mHandler = new Handler();
install this runnable as a handler, possible in onCreate()
(but read my advice below):
// run the mUpdateUITimerTask's run() method in 10 seconds from now
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible!
When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image
For more Details check this
https://learning.getpostman.com/docs/postman/sending_api_requests/responses/
This is useful in contexts where the encoding is not told per HTTP header or other meta data, e.g. the local file system.
Imagine the following stylesheet:
[rel="external"]::after
{
content: ' ?';
}
If a reader saves the file to a hard drive and you omit the @charset
rule, most browsers will read it in the OS’ locale encoding, e.g. Windows-1252, and insert ↗ instead of an arrow.
Unfortunately, you cannot rely on this mechanism as the support is rather … rare.
And remember that on the net an HTTP header will always override the @charset
rule.
The correct rules to determine the character set of a stylesheet are in order of priority:
@charset
rule.The last rule is the weakest, it will fail in some browsers.
The charset
attribute in <link rel='stylesheet' charset='utf-8'>
is obsolete in HTML 5.
Watch out for conflict between the different declarations. They are not easy to debug.
@charset
if more than one name is registered for the same encoding.@charset
. There is a support table. I do not trust this. :)You need to use \n
inside quotes.
document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)
\n
is called a EOL
or line-break
, \n
is a common EOL
marker and is commonly refereed to as LF
or line-feed
, it is a special ASCII
character
There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.
Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:
module foo:
bar = "apples"
module a:
import foo
foo.bar = "oranges" # update bar inside foo module object
module b:
import foo
print foo.bar # if executed after a's "foo.bar" assignment, will print "oranges"
However, if you import symbol names instead of module names, this will not work.
For example, if I do this in module a:
from foo import bar
bar = "oranges"
No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".
This thread caught my attention since it deals with a simple problem that requires a lot of work (CPU cycles) even for a modern CPU. And one day I also stood there with the same ¤#%"#" problem. I had to flip millions of bytes. However I know all my target systems are modern Intel-based so let's start optimizing to the extreme!!!
So I used Matt J's lookup code as the base. the system I'm benchmarking on is a i7 haswell 4700eq.
Matt J's lookup bitflipping 400 000 000 bytes: Around 0.272 seconds.
I then went ahead and tried to see if Intel's ISPC compiler could vectorise the arithmetics in the reverse.c.
I'm not going to bore you with my findings here since I tried a lot to help the compiler find stuff, anyhow I ended up with performance of around 0.15 seconds to bitflip 400 000 000 bytes. It's a great reduction but for my application that's still way way too slow..
So people let me present the fastest Intel based bitflipper in the world. Clocked at:
Time to bitflip 400000000 bytes: 0.050082 seconds !!!!!
// Bitflip using AVX2 - The fastest Intel based bitflip in the world!!
// Made by Anders Cedronius 2014 (anders.cedronius (you know what) gmail.com)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
using namespace std;
#define DISPLAY_HEIGHT 4
#define DISPLAY_WIDTH 32
#define NUM_DATA_BYTES 400000000
// Constants (first we got the mask, then the high order nibble look up table and last we got the low order nibble lookup table)
__attribute__ ((aligned(32))) static unsigned char k1[32*3]={
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0x00,0x08,0x04,0x0c,0x02,0x0a,0x06,0x0e,0x01,0x09,0x05,0x0d,0x03,0x0b,0x07,0x0f,0x00,0x08,0x04,0x0c,0x02,0x0a,0x06,0x0e,0x01,0x09,0x05,0x0d,0x03,0x0b,0x07,0x0f,
0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0,0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0
};
// The data to be bitflipped (+32 to avoid the quantization out of memory problem)
__attribute__ ((aligned(32))) static unsigned char data[NUM_DATA_BYTES+32]={};
extern "C" {
void bitflipbyte(unsigned char[],unsigned int,unsigned char[]);
}
int main()
{
for(unsigned int i = 0; i < NUM_DATA_BYTES; i++)
{
data[i] = rand();
}
printf ("\r\nData in(start):\r\n");
for (unsigned int j = 0; j < 4; j++)
{
for (unsigned int i = 0; i < DISPLAY_WIDTH; i++)
{
printf ("0x%02x,",data[i+(j*DISPLAY_WIDTH)]);
}
printf ("\r\n");
}
printf ("\r\nNumber of 32-byte chunks to convert: %d\r\n",(unsigned int)ceil(NUM_DATA_BYTES/32.0));
double start_time = omp_get_wtime();
bitflipbyte(data,(unsigned int)ceil(NUM_DATA_BYTES/32.0),k1);
double end_time = omp_get_wtime();
printf ("\r\nData out:\r\n");
for (unsigned int j = 0; j < 4; j++)
{
for (unsigned int i = 0; i < DISPLAY_WIDTH; i++)
{
printf ("0x%02x,",data[i+(j*DISPLAY_WIDTH)]);
}
printf ("\r\n");
}
printf("\r\n\r\nTime to bitflip %d bytes: %f seconds\r\n\r\n",NUM_DATA_BYTES, end_time-start_time);
// return with no errors
return 0;
}
The printf's are for debugging..
Here is the workhorse:
bits 64
global bitflipbyte
bitflipbyte:
vmovdqa ymm2, [rdx]
add rdx, 20h
vmovdqa ymm3, [rdx]
add rdx, 20h
vmovdqa ymm4, [rdx]
bitflipp_loop:
vmovdqa ymm0, [rdi]
vpand ymm1, ymm2, ymm0
vpandn ymm0, ymm2, ymm0
vpsrld ymm0, ymm0, 4h
vpshufb ymm1, ymm4, ymm1
vpshufb ymm0, ymm3, ymm0
vpor ymm0, ymm0, ymm1
vmovdqa [rdi], ymm0
add rdi, 20h
dec rsi
jnz bitflipp_loop
ret
The code takes 32 bytes then masks out the nibbles. The high nibble gets shifted right by 4. Then I use vpshufb and ymm4 / ymm3 as lookup tables. I could use a single lookup table but then I would have to shift left before ORing the nibbles together again.
There are even faster ways of flipping the bits. But I'm bound to single thread and CPU so this was the fastest I could achieve. Can you make a faster version?
Please make no comments about using the Intel C/C++ Compiler Intrinsic Equivalent commands...
I had the same problem with a spring boot project. the solution was to downgrade the jar maven-jar-plugin from 3.2 to 2.6 . i had just to add this to the project pom:
<properties>
<maven-jar-plugin.version>2.6</maven-jar-plugin.version>
</properties>
I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:
public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public VndApiJsonMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
}
}
Which can be used simply like the following:
HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");
List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());
var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
Super simple and works exactly as I expected.
The problem is that an isin does not identify the exchange, only an issuer.
Let's say your isin is US4592001014
(IBM), one way to do it would be:
get the ticker (in A1):
=BDP("US4592001014 ISIN", "TICKER") => IBM
get a proper symbol (in A2)
=BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
where XX
depends on your terminal settings, which you can check on CNDF <Go>
.
get the main exchange composite ticker, or whatever suits your need (in A3):
=BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
and finally:
=BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
If your test coverage is good on all the public method inside the tested class, the privates methods called by the public one will be automatically tested since you will assert all the possible case.
The JUnit Doc says:
Testing private methods may be an indication that those methods should be moved into another class to promote reusability. But if you must... If you are using JDK 1.3 or higher, you can use reflection to subvert the access control mechanism with the aid of the PrivilegedAccessor. For details on how to use it, read this article.
Let me add another solution:
>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f =
'f1'
'f2'
'f3'
'f4'
'f5'
If N
is more than two digits long (>= 10
), you will start getting extra spaces. Add a call to strtrim(f)
to get rid of them.
As a bonus, there is an undocumented built-in function sprintfc
which nicely returns a cell arrays of strings:
>> N = 10;
>> f = sprintfc('f%d', 1:N)
f =
'f1' 'f2' 'f3' 'f4' 'f5' 'f6' 'f7' 'f8' 'f9' 'f10'
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
This comment syntax should work for you:
@* enter comments here *@
I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:
func dateFormat(layout string, d float64) string{
intTime := int64(d)
t := time.Unix(intTime, 0)
if layout == "" {
layout = "2006-01-02 15:04:05"
}
return t.Format(layout)
}
A regular expression might not be the most effective tool for this job.
Try using parse_url()
, combined with pathinfo()
:
$url = 'http://php.net/manual/en/function.preg-match.php';
$path = parse_url($url, PHP_URL_PATH);
$pathinfo = pathinfo($path);
echo $pathinfo['dirname'], '/', $pathinfo['filename'];
The above code outputs:
/manual/en/function.preg-match
You can try running a simple web server based on Twisted
Seems that maven now gives a solution here : Compiling Sources Using A Different JDK
Let's say your JAVA_HOME
points to JDK7 (which will run maven processes)
Your pom.xml
could be :
<build>
<plugins>
<!-- we want JDK 1.6 source and binary compatiblility -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<!-- ... -->
<!-- we want sources to be processed by a specific 1.6 javac -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<executable>${JAVA_1_6_HOME}/bin/javac</executable>
<compilerVersion>1.3</compilerVersion>
</configuration>
</plugin>
</plugins>
</build>
If your developpers just add (and customize) the following lines in their settings.xml
, your pom will be platform independant :
<settings>
[...]
<profiles>
[...]
<profile>
<id>compiler</id>
<properties>
<JAVA_1_4_HOME>C:\Program Files\Java\j2sdk1.4.2_09</JAVA_1_4_HOME>
<JAVA_1_6_HOME>C:\Program Files\Java\j2sdk1.6.0_18</JAVA_1_6_HOME>
</properties>
</profile>
</profiles>
[...]
<activeProfiles>
<activeProfile>compiler</activeProfile>
</activeProfiles>
</settings>
$('.page-address-edit').addClass('test1 test2 test3');
When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/authFailure").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
If you are still not having any joy, then you will need to provide more details/stacktrace etc.
None of the posted solutions worked for me.
I had to vi
into my Makefile and edit the path so that the path to the include
folder and the OS subsystem (in my case, -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux
) was correct. This allowed me to run make
and make install
without issues.
String s1 = "";
means that the empty String
is assigned to s1
.
In this case, s1.length()
is the same as "".length()
, which will yield 0
as expected.
String s2 = null;
means that (null
) or "no value at all" is assigned to s2
. So this one, s2.length()
is the same as null.length()
, which will yield a NullPointerException
as you can't call methods on null
variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
You can even declare an integer at the beginning of your main()
function (say int a;
) and put std::cin >> a;
just before the return value. So the program will keep running until you press a key and enter.
I had the same problem. Try this:
git pull origin master --allow-unrelated-histories
git push origin master
You have to create a separate volume for mysql data.
So it will look like this:
volumes_from:
- data
volumes:
- ./mysql-data:/var/lib/mysql
And no, /var/lib/mysql
is a path inside your mysql container and has nothing to do with a path on your host machine. Your host machine may even have no mysql at all. So the goal is to persist an internal folder from a mysql container.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
So none of these things worked for me. I am using the current dmg install of mysql community server. ps shows that all of the most critical parameters normally in my.cnf are passed on the command line, and I couldn't figure out where that was coming from. After doing a full text search of my box I found it in:
/Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
So you can either change them there, or take them out so it will actually respect the ones you have in your my.cnf wherever you decided to put it.
Enjoy!
Example of the file info found in that file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key> <string>com.oracle.oss.mysql.mysqld</string>
<key>ProcessType</key> <string>Interactive</string>
<key>Disabled</key> <false/>
<key>RunAtLoad</key> <true/>
<key>KeepAlive</key> <true/>
<key>SessionCreate</key> <true/>
<key>LaunchOnlyOnce</key> <false/>
<key>UserName</key> <string>_mysql</string>
<key>GroupName</key> <string>_mysql</string>
<key>ExitTimeOut</key> <integer>600</integer>
<key>Program</key> <string>/usr/local/mysql/bin/mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld</string>
<string>--user=_mysql</string>
<string>--basedir=/usr/local/mysql</string>
<string>--datadir=/usr/local/mysql/data</string>
<string>--plugin-dir=/usr/local/mysql/lib/plugin</string>
<string>--log-error=/usr/local/mysql/data/mysqld.local.err</string>
<string>--pid-file=/usr/local/mysql/data/mysqld.local.pid</string>
<string>--keyring-file-data=/usr/local/mysql/keyring/keyring</string>
<string>--early-plugin-load=keyring_file=keyring_file.so</string>
</array>
<key>WorkingDirectory</key> <string>/usr/local/mysql</string>
</dict>
</plist>
Setting these exact configurations helped resolving the issue.
spark-submit --conf spark.yarn.maxAppAttempts=2 --executor-memory 10g --num-executors 50 --driver-memory 12g
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
A Stacked bar chart should suffice:
Setup data as follows
Name Start End Duration (End - Start)
Fred 1/01/1981 1/06/1985 1612
Bill 1/07/1985 1/11/2000 5602
Joe 1/01/1980 1/12/2001 8005
Jim 1/03/1999 1/01/2000 306
Start
and Duration
as a stacked bar chartX-Axis minimum
to the desired start date Fill
Colour of thestart
range to no fill
Fill
of individual bars to suit(example prepared in Excel 2010)
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
res.writeHead(200,{'content-type':'image/jpg'});
fs.createReadStream('./image/demo.jpg').pipe(res);
}).listen(3000);
console.log('server running at 3000');
#!/usr/bin/env python
import inspect
called=lambda: inspect.stack()[1][3]
def caller1():
print "inside: ",called()
def caller2():
print "inside: ",called()
if __name__=='__main__':
caller1()
caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py
inside: caller1
inside: caller2
shahid@shahid-VirtualBox:~/Documents$
Since char
is a primitive type, you can just write c == ' '
.
You only need to call equals()
for reference types like String
or Character
.
In fact, the original S3 auth does allow for the content to be signed, albeit with a weak MD5 signature. You can simply enforce their optional practice of including a Content-MD5 header in the HMAC (string to be signed).
http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html
Their new v4 authentication scheme is more secure.
http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
Shorter syntax
select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
END
Others are correct in saying that setting button.enabled = false
doesn't prevent the button from triggering. However, I found that setting button.visible = false
does work. The button disappears and can't be clicked until you set visible
to true
again.
Ok I was googling around and get to this post several times so I think it'll be good to be described not only for Sherlock but for appcompat also:
Action Bar height using appCompat
Pretty similiar to @Anthony description you could find it with following code(I've just changed resource id):
TypedValue tv = new TypedValue();
if (getActivity().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))
{
int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
Pre Sandwitch Problem
I needed action bar height because on pre ICE_CREAM_SANDWITCH devices my view was overlaping action bar. I tried setting android:layout_marginTop="?android:attr/actionBarSize", android:layout_marginTop="?attr/actionBarSize", setting overlap off to view/actionbar and even fixed actionbar height with custom theme but nothing worked. That's how it looked:
Unfortunately I found out that with method described above I get only half of the height(I assume that options bar is not taken in place) so to completely fix the isue I need to double action bar height and everything seems ok:
If someone knows better solution(than doubling actionBarHeight) I'll be glad to let me know as I come from iOS development and I found most of Android view's stuff pretty confusing :)
Regards,
hris.to
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
In separate terminal windows do the following:
Start the broker:
mosquitto
Start the command line subscriber:
mosquitto_sub -v -t 'test/topic'
Publish test message with the command line publisher:
mosquitto_pub -t 'test/topic' -m 'helloWorld'
As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:
test/topic helloWorld
I had the same problem with one of my projects, however, none of the above helped to solve the warning. I checked the detailed build logfile, I used AsmSpy to verify that I used the correct versions for each project in the affected solution, I double checked the actual entries in each project file - nothing helped.
Eventually it turned out that the problem was a nested dependency of one of the references I had in one project. This reference (A) in turn required a different version of (B) which was referenced directly from all other projects in my solution. Updating the reference in the referenced project solved it.
Solution A
+--Project A
+--Reference A (version 1.1.0.0)
+--Reference B
+--Project B
+--Reference A (version 1.1.0.0)
+--Reference B
+--Reference C
+--Project C
+--Reference X (this indirectly references Reference A, but with e.g. version 1.1.1.0)
Solution B
+--Project A
+--Reference A (version 1.1.1.0)
I hope the above shows what I mean, took my a couple of hours to find out, so hopefully someone else will benefit as well.
Another (not recommended!) twist on the callable object like https://stackoverflow.com/a/279598/916373, if you don't mind using a funky call signature, would be to do
class foo(object):
counter = 0;
@staticmethod
def __call__():
foo.counter += 1
print "counter is %i" % foo.counter
>>> foo()()
counter is 1
>>> foo()()
counter is 2
It turns out that the cause was that this project wasn't being considered by Eclipse to actually be a Java EE project at all; it was an old project from 3.1, and the Eclipse 3.5 we are using now requires several "natures" to be set in the project configuration file.
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>InCode.inCodeNature</nature>
<nature>org.eclipse.dltk.javascript.core.nature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
</natures>
I was able to find the cause by creating a new "Dynamic Web Project" which properly read its JSP files, and diffing against the config of the older project.
The only way I could find to add these was by editing the .project file, but after re-opening the project, everything magically worked. The settings referenced by pribeiro, above, weren't necessary since the project already conformed to the default settings.
Both pribeiro and nitind's answers gave me ideas to jumpstart my search, thanks.
Is there a way of editing these "natures" from within the UI?
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
It works.
@marcio-junior's answer (https://stackoverflow.com/a/6497462/4038790) works perfectly, but I wanted to explain for those who don't understand why it works:
@a7omiton Along with @psyren89's response to your question
Think of the outer div
as a movie screen and the inner div
as the setting in which the characters move around. If you were viewing the setting in person, that is without a screen around it, you would be able to see all of the characters at once assuming your eyes have a large enough field of vision. That would mean the setting wouldn't have to scroll (move left to right) in order for you to see more of it and so it would stay still.
However, you are not at the setting in person, you are viewing it from your computer screen which has a width of 500px while the setting has a width of 1000px. Thus, you will need to scroll (move left to right) the setting in order to see more of the characters inside of it.
I hope that helps anyone who was lost on the principle.
You can enable query strings if you really insist. In your config.php you can enable query strings:
$config['enable_query_strings'] = TRUE;
For more info you can look at the bottom of this Wiki page: http://codeigniter.com/user_guide/general/urls.html
Still, learning to work with clean urls is a better suggestion.
As mentioned already primitives can not be set to the Object type null.
What I do in such cases is just to use -1
or Long.MIN_VALUE
.
Actually the ng-disabled directive works with the " || " logical operator for me. The " && " evaluate only one condition.
Download pip script from https://bootstrap.pypa.io/get-pip.py and then run using python as:-
python get-pip.py
or you can use python to install modules directly
python -m pip install <module>
I have a solution below and its works for me:
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
method: 'jsonp',
url: 'http://mywebservice',
params: {
format: 'jsonp',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
}
}]);
in 'http://mywebservice' there must be need a callback parameter which return JSON_CALLBACK with data.
There is a sample example below which works perfect
$scope.url = "https://angularjs.org/greet.php";
$http({
method: 'jsonp',
url: $scope.url,
params: {
format: 'jsonp',
name: 'Super Hero',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
example output:
{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}
I was having a problem fetching profile photos while using CURL. I thought for a while there was something wrong my implementation of the Facebook API, but I need to add a bit to my CURL called:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);