I had problem like this, but with several "actions". My solution looks like this:
<form method="POST" th:object="${searchRequest}" action="searchRequest" >
<input type="text" th:field="*{name}"/>
<input type="submit" value="find" th:value="find" />
</form>
...
<form method="POST" th:object="${commodity}" >
<input type="text" th:field="*{description}"/>
<input type="submit" value="add" />
</form>
And controller
@Controller
@RequestMapping("/goods")
public class GoodsController {
@RequestMapping(value = "add", method = GET)
public String showGoodsForm(Model model){
model.addAttribute(new Commodity());
model.addAttribute("searchRequest", new SearchRequest());
return "goodsForm";
}
@RequestMapping(value = "add", method = POST)
public ModelAndView processAddCommodities(
@Valid Commodity commodity,
Errors errors) {
if (errors.hasErrors()) {
ModelAndView model = new ModelAndView("goodsForm");
model.addObject("searchRequest", new SearchRequest());
return model;
}
ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
model.addObject(new Commodity());
model.addObject("searchRequest", new SearchRequest());
return model;
}
@RequestMapping(value="searchRequest", method=POST)
public String processFindCommodity(SearchRequest commodity, Model model) {
...
return "catalog";
}
I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".
As Chris Lutz mentioned, this is defined by the __repr__
method in your class.
From the documentation of repr()
:
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__repr__()
method.
Given the following class Test:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "<Test a:%s b:%s>" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is %s, b is %s" % (self.a, self.b)
..it will act the following way in the Python shell:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
If no __str__
method is defined, print(t)
(or print(str(t))
) will use the result of __repr__
instead
If no __repr__
method is defined then the default is used, which is pretty much equivalent to..
def __repr__(self):
return "<%s instance at %s>" % (self.__class__.__name__, id(self))
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.
if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/
i plan on following and trying to modify it to create a general template for java
if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.
If you are using Babel or such transpilers and using async/await you could do :
function onDrop() {
console.log("dropped");
}
async function dropAll( collections ) {
const drops = collections.map(col => conn.collection(col).drop(onDrop) );
await drops;
console.log("all dropped");
}
Check if the scrollable element is already scrolled to the top when trying to scroll up or to the bottom when trying to scroll down and then preventing the default action to stop the entire page from moving.
var touchStartEvent;
$('.scrollable').on({
touchstart: function(e) {
touchStartEvent = e;
},
touchmove: function(e) {
if ((e.originalEvent.pageY > touchStartEvent.originalEvent.pageY && this.scrollTop == 0) ||
(e.originalEvent.pageY < touchStartEvent.originalEvent.pageY && this.scrollTop + this.offsetHeight >= this.scrollHeight))
e.preventDefault();
}
});
As shown in this example, you can apply a background to a canvas
element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL()
.
Here are the contents of the example, for Stack Overflow posterity:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(lotsalasers.jpg) }
</style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(140,60,40,40);
var img = document.getElementsByTagName('img')[0];
img.src = can.toDataURL();
</script>
</body></html>
I have face the same problem and after times of trial and error, I found out that you can avoid scrollbars by overriding frame css class.
You can do like this:
iframe.fancybox-iframe {
overflow:hidden;
}
JS configuration:
jQuery(document).ready(function(){
$("a.various").fancybox({
'width' : 'auto',
'height' : 'auto',
'autoScale' : false,
'autoDimensions' : false,
'scrolling' : 'no',
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
});
Note: Your fancybox box type must be an iframe
for this to take effect.
This is what I did:
HTML
<div id="divProgress"></div>
<div id="divStepTitle">
<span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>
<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />
CSS
#divProgress
{
width: 600px;
}
#divStepTitle
{
width: 600px;
}
.spanStep
{
text-align: center;
width: 200px;
}
Javascript/jQuery
var progress = 0;
$(function({
//set step progress bar
$("#divProgress").progressbar();
//event handler for prev and next button
$("#btnPrev, #btnNext").click(function(){
step($(this));
});
});
function step(obj)
{
//switch to prev/next page
if (obj.val() == "Prev")
{
//set new value for progress bar
progress -= 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing previous page
}
else if (obj.val() == "Next")
{
//set new value for progress bar
progress += 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing next page
}
}
It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.
In foo.cc:
#include <cstdio> // for puts
#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"
int main(int argc, const char* argv[])
{
puts("Hello!");
bar();
zoo();
puts(Message::third);
return 0;
}
In messages.hh:
#ifndef MESSAGES_HH
#define MESSAGES_HH
namespace Message {
char const * const first = "Yes, this is the first message!";
char const * const second = "This is the second message.";
char const * const third = "Message #3.";
};
#endif
In bar.cc:
#include "messages.hh"
#include <cstdio>
void bar(void)
{
puts("Wow!");
printf("bar: %s\n", Message::first);
}
In zoo.cc:
#include <cstdio>
#include "messages.hh"
void zoo(void)
{
printf("zoo: %s\n", Message::second);
}
In bar.hh:
#ifndef BAR_HH
#define BAR_HH
#include "messages.hh"
void bar(void);
#endif
In zoo.hh:
#ifndef ZOO_HH
#define ZOO_HH
#include "messages.hh"
void zoo(void);
#endif
This yields the following output:
Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.
The data type char const * const
means a constant pointer to an array of constant characters. The first const
is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const
is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the const
s, but then the source code is less portable.
There is a simple solution I learned with "We <3 Swift" if you can't either import Foundation, use round() and/or does not want a String:
var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0
result: 31.726
Since you have jQuery on the page, you can remove that onclick
attribute and the majorpointsexpand
function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset
layout, it could break it. I'd suggest that you put a class
attribute in that hidden div, like class="majorpointsdetail"
and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset>
tag in your question so I'm assuming the hidden div is inside the fieldset.
Use StringBuilder
:
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
I think using dtype
where there is a name row is confusing the routine. Try
>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29111196e+12],
[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29111311e+12],
[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29112065e+12]])
>>> r[:,0] # Slice 0'th column
array([ 611.88243, 611.88243, 611.88243])
You can do this :
mysql -u USERNAME --password=PASSWORD --database=DATABASE --execute='SELECT `FIELD`, `FIELD` FROM `TABLE` LIMIT 0, 10000 ' -X > file.xml
I just went through this myself and chose to set the default value at the reducer INIT function.
If you bind your select with redux then best not 'de-bind' it with a select default value that doesn't represent the actual value, instead set the value when you initialize the object.
The best practice is to check if the array key exists using the built-in array_key_exists
function.
As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...
using System.Diagnostics;
...
Process.Start("process.exe");
The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.
This method allows far more control than I've mentioned.
The kernel is part of the operating system and closer to the hardware it provides low level services like:
An operating system also includes applications like the user interface (shell, gui, tools, and services).
$ file=${$(basename $file_path)%.*}
For person who are afraid on re-creating AppStore distribution certificate Apple documentation says:
Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the App Store nor does it affect your ability to update them.
But it affects apps for Apple Developer Enterprise ecosystem.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
git push --all
is the canonical way to push everything to a new bare repository.
Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with
git clone --bare
then use
git remote add origin <new-remote-repo>
in the original (non-bare) repository.
I think this is the best approach. Using generic ArrayAdapter class and extends your own Object adapter is as simple as follows:
public abstract class GenericArrayAdapter<T> extends ArrayAdapter<T> {
// Vars
private LayoutInflater mInflater;
public GenericArrayAdapter(Context context, ArrayList<T> objects) {
super(context, 0, objects);
init(context);
}
// Headers
public abstract void drawText(TextView textView, T object);
private void init(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
drawText(vh.textView, getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
private ViewHolder(View rootView) {
textView = (TextView) rootView.findViewById(android.R.id.text1);
}
}
}
and here your adapter (example):
public class SizeArrayAdapter extends GenericArrayAdapter<Size> {
public SizeArrayAdapter(Context context, ArrayList<Size> objects) {
super(context, objects);
}
@Override public void drawText(TextView textView, Size object) {
textView.setText(object.getName());
}
}
and finally, how to initialize it:
ArrayList<Size> sizes = getArguments().getParcelableArrayList(Constants.ARG_PRODUCT_SIZES);
SizeArrayAdapter sizeArrayAdapter = new SizeArrayAdapter(getActivity(), sizes);
listView.setAdapter(sizeArrayAdapter);
I've created a Gist with TextView layout gravity customizable ArrayAdapter:
If body contains a io.StringIO, you have to do like below:
object.get()['Body'].getvalue()
You need to alias the aggregate using the as
keyword in order to call it from mysql_fetch_assoc
$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
jQuery .on method is used to bind events even without the presence of element on page load. Here is the link It is used in this way:
$("#dataTable tbody tr").on("click", function(event){
alert($(this).text());
});
Before jquery 1.7, .live() method was used, but it is deprecated now.
As an addition to fuzzyman's reply:
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
Here is a trick on Windows:
you can use easy_install <package>
to install binary packages to avoid building a binary
you can use pip uninstall <package>
even if you used easy_install.
This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.
See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install
I will ask on the mailing list what is planned for that.
Here is the latest update:
The new supported way to install binaries is going to be wheel
!
It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1
https://pypi.python.org/pypi/wheel
http://wheel.readthedocs.org/en/latest/
I will test wheel
by creating an OS X installer for PySide
using wheel
instead of eggs. Will get back and report about this.
cheers - Chris
The transition to wheel
is almost over. Most packages are supporting wheel
.
I promised to build wheels for PySide
, and I did that last summer. Works great!
HINT:
A few developers failed so far to support the wheel format, simply because they forget to
replace distutils
by setuptools
.
Often, it is easy to convert such packages by replacing this single word in setup.py
.
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
I will illustrate it intuitively step by step in simple and readable python codes.
In short, a lambda is just an anonymous and inline function.
Let's start from assignment to understand lambdas
as a freshman with background of basic arithmetic.
The blueprint of assignment is 'the name = value', see:
In [1]: x = 1
...: y = 'value'
In [2]: x
Out[2]: 1
In [3]: y
Out[3]: 'value'
'x', 'y' are names and 1, 'value' are values. Try a function in mathematics
In [4]: m = n**2 + 2*n + 1
NameError: name 'n' is not defined
Error reports,
you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.
In [8]: n = 3.14
In [9]: m = n**2 + 2*n + 1
In [10]: m
Out[10]: 17.1396
It works now,what if you insist on combining the two seperarte lines to one.
There comes lambda
In [13]: j = lambda i: i**2 + 2*i + 1
In [14]: j
Out[14]: <function __main__.<lambda>>
No errors reported.
This is a glance at lambda
, it enables you to write a function in a single line as you do in mathematic into the computer directly.
We will see it later.
Let's continue on digging deeper on 'assignment'.
As illustrated above, the equals symbol =
works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).
Try this:
In [15]: x = print('This is a x')
This is a x
In [16]: x
In [17]: x = input('Enter a x: ')
Enter a x: x
It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation
How about compound statement,
In [18]: m = n**2 + 2*n + 1 if n > 0
SyntaxError: invalid syntax
#or
In [19]: m = n**2 + 2*n + 1, if n > 0
SyntaxError: invalid syntax
There comes def
enable it working
In [23]: def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
...:
In [24]: m(2)
Out[24]: 9
Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.:
is a variant of '='.
Find it, if just for understanding, everything starts from assignment and everything is assignment.
Now return to lambda
, we have a function named 'm'
Try:
In [28]: m = m(3)
In [29]: m
Out[29]: 16
There are two names of 'm' here, function m
already has a name, duplicated.
It's formatting like:
In [27]: m = def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
SyntaxError: invalid syntax
It's not a smart strategy, so error reports
We have to delete one of them,set a function without a name.
m = lambda n:n**2 + 2*n + 1
It's called 'anonymous function'
In conclusion,
lambda
in an inline function which enable you to write a function in one straight line as does in mathematicslambda
is anonymousHope, this helps.
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));
Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,
server.js
app.engine('handlebars', ViewEngine({
"helpers":{
isActive: (val, options)=>{
if (val === 3 || val === 0){
return options.fn(this)
}
}
}
}));
header.handlebars
<ul class="navlist">
<li class="navitem navlink {{#isActive 0}}active{{/isActive}}"
><a href="#">Home</a></li>
<li class="navitem navlink {{#isActive 1}}active{{/isActive}}"
><a href="#">Trending</a></li>
<li class="navitem navlink {{#isActive 2}}active{{/isActive}}"
><a href="#">People</a></li>
<li class="navitem navlink {{#isActive 3}}active{{/isActive}}"
><a href="#">Mystery</a></li>
<li class="navitem navbar-search">
<input type="text" id="navbar-search-input" placeholder="Search...">
<button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
</li>
</ul>
Depends where you store your crontab:
shell_exec('echo "'. $job .'" >> crontab');
In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
So, you can do this:
var timeoutID = window.setTimeout(function (self) {
console.log(self);
}, 500, this);
This is better in terms of performance than a scope lookup (caching this
into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy
or Function.prototype.bind
).
The code to make it work in IEs from Webreflection:
/*@cc_on
(function (modifierFn) {
// you have to invoke it as `window`'s property so, `window.setTimeout`
window.setTimeout = modifierFn(window.setTimeout);
window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
return function (callback, timeout){
var args = [].slice.call(arguments, 2);
return originalTimerFn(function () {
callback.apply(this, args)
}, timeout);
}
});
@*/
So if you have
floatInString = '5.0'
You can convert it to int
with floatInInt = int(float(floatInString))
All I did was go to the "Refactor" option on the top menu.
Then select "Migrate to AndroidX"
Accept to save the project as a zip file.
Please update Android Studio as well as Gradle to ensure no problems are encountered.
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!
You can't use delete
to remove an item from an array. This is only used to remove a property from an object.
You should use splice to remove an element from an array:
deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}
How about
grep -ch "^" file.txt
I have used the below as a background for the layout:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:dashWidth="10px"
android:dashGap="10px"
android:color="android:@color/black"
/>
</shape>
I had the same problem with the Macports port "openocd" (locally modified the Portfile to use the git repository) on a freshly installed machine.
The permanent fix is easy, define a dependency to pkgconfig in the Portfile: depends_lib-append port:pkgconfig
To upgrade your pip3, try running:
sudo -H pip3 install --upgrade pip3
To upgrade pip as well, you can follow it by:
sudo -H pip2 install --upgrade pip
In Rider, this would be Ctrl +Shift+Keypad *, 2
But!, you cannot use the number 2 on keypad, only number 2 on the top row of the keyboard would work.
If you want to use text word wrap in your Visual Studio Code editor, you have to press button Alt + Z for text word wrap. Its word wrap is toggled between text wrap or unwrap.
If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. You can directly use the map or bimap methods to transform your Map. A MapX can be constructed from an existing Map eg.
MapX<String, Column> y = MapX.fromMap(orgColumnMap)
.map(c->new Column(c.getValue());
If you also wish to change the key you can write
MapX<String, Column> y = MapX.fromMap(orgColumnMap)
.bimap(this::newKey,c->new Column(c.getValue());
bimap can be used to transform the keys and values at the same time.
As MapX extends Map the generated map can also be defined as
Map<String, Column> y
You can use the ternary operator easily:
{{ $usersType ? $usersType : '' }}
I usually use BOOST_FOREACH:
#include <boost/foreach.hpp>
BOOST_FOREACH( vector_type::value_type& value, v ) {
// do something with 'value'
}
It works on STL containers, arrays, C-style strings, etc.
public byte[] loadBinaryFile (String name) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(name));
byte[] theBytes = new byte[dis.available()];
dis.read(theBytes, 0, dis.available());
dis.close();
return theBytes;
} catch (IOException ex) {
}
return null;
} // ()
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out
params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
) into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS
) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util
type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:
OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);
A simpler way to do the same case is:
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
newDateFormat.parse(newDateFormat.format(
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
.parse(rs.getString("originalRevisionDate", "")))));
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
If you want to modify a control it must be done in the thread in which the control was created. This Invoke
method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).
In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created
private void btn_Click(object sender, EvenetArgs e)
{
var thread1 = new Thread(SetText1);
var thread2 = new Thread(SetText2);
thread1.Start();
thread2.Start();
}
private void SetText1()
{
textBox1.Text = "Test";
}
private void SetText2()
{
textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}
A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async
The defer and async attributes must not be specified if the src attribute is not present.
There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:
The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
This issue is not solved (yet), at least not easily / without scripting: see this post on git mailing list by Junio C Hamano explaining situation and providing call for a simple solution.
The major reasoning is that you shouldn't need this:
With git that is not ancient (i.e. v1.5.0 or newer), there is no reason to have local "dev" that purely track the remote anymore. If you only want to go-look-and-see, you can check out the remote tracking branch directly on a detached HEAD with "
git checkout origin/dev
".Which means that the only cases we need to make it convenient for users are to handle these local branches that "track" remote ones when you do have local changes, or when you plan to have some.
If you do have local changes on "dev" that is marked to track the remove "dev", and if you are on a branch different from "dev", then we should not do anything after "
git fetch
" updates the remote tracking "dev". It won't fast forward anyway
The call for a solution was for an option or external script to prune local branches that follow now remote-tracking branches, rather than to keep them up-to-date by fast-forwarding, like original poster requested.
So how about "
git branch --prune --remote=<upstream>
" that iterates over local branches, and if(1) it is not the current branch; and
(2) it is marked to track some branch taken from the <upstream>; and
(3) it does not have any commits on its own;then remove that branch? "
git remote --prune-local-forks <upstream>
" is also fine; I do not care about which command implements the feature that much.
Note: as of git 2.10 no such solution exists. Note that the git remote prune
subcommand, and git fetch --prune
are about removing remote-tracking branch for branch that no longer exists on remote, not about removing local branch that tracks remote-tracking branch (for which remote-tracking branch is upstream branch).
Just catch the submit event and prevent that, then do ajax
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
Super simple code using TryParse:
var value = "Active";
StatusEnum status;
if (!Enum.TryParse<StatusEnum>(value, out status))
status = StatusEnum.Unknown;
In Mvc using plain html in View Page with java script onclick
<input type="button" value="GO BACK" class="btn btn-primary"
onclick="location.href='@Request.UrlReferrer'" />
This works great. hope helps someone.
@JuanPieterse has already answered using @Html.ActionLink
so if possible someone can comment or answer using @Url.Action
I had the same issue (Unable to instantiate Activity) :
FIRST reason :
I was accessing
Camera mCamera;
Camera.Parameters params = mCamera.getParameters();
before
mCamera = Camera.open();
So right way of doing is, open the camera first and then access parameters.
SECOND reason : Declare your activity in the manifest file
<activity android:name=".activities.MainActivity"/>
THIRD reason : Declare Camera permission in your manifest file.
<uses-feature android:name="android.hardware.Camera"></uses-feature>
<uses-permission android:name="android.permission.CAMERA" />
Hope this helps
I don't have a high enough reputation to comment on Gavin Simpson's answer, but I wanted to warn that there seems to be a difference in the default treatment of missing values between the standard syntax and the formula syntax for aggregate
.
#Create some data with missing values
a<-data.frame(day=rep(1,5),hour=c(1,2,3,3,4),val=c(1,NA,3,NA,5))
day hour val
1 1 1 1
2 1 2 NA
3 1 3 3
4 1 3 NA
5 1 4 5
#Standard syntax
aggregate(a$val,by=list(day=a$day,hour=a$hour),mean,na.rm=T)
day hour x
1 1 1 1
2 1 2 NaN
3 1 3 3
4 1 4 5
#Formula syntax. Note the index for hour 2 has been silently dropped.
aggregate(val ~ hour + day,data=a,mean,na.rm=T)
hour day val
1 1 1 1
2 3 1 3
3 4 1 5
The key is "argument-less git-pull". When you do a git pull
from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge
setting to know where to pull from. git push -u
sets this information for the branch you're pushing.
To see the difference, let's use a new empty branch:
$ git checkout -b test
First, we push without -u
:
$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "test"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
Now if we add -u
:
$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.
Note that tracking information has been set up so that git pull
works as expected without specifying the remote or branch.
Update: Bonus tips:
git pull
this setting also affects default behavior of git push
. If you get in the habit of using -u
to capture the remote branch you intend to track, I recommend setting your push.default
config value to upstream
.git push -u <remote> HEAD
will push the current branch to a branch of the same name on <remote>
(and also set up tracking so you can do git push
after that).More concise than others:
def parseString(string):
try:
return int(string)
except ValueError:
return string
b = [[parseString(s) for s in clause.split(', ')] for clause in a]
Alternatively if your format is fixed as <string>, <int>, <int>
, you can be even more concise:
def parseClause(a,b,c):
return [a, int(b), int(c)]
b = [parseClause(*clause) for clause in a]
Completing @chuck answer for using composite indices with foreign keys.
You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.
For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:
class Company
{
public Guid Id { get; set; }
}
class Employee
{
public Guid Id { get; set; }
[Required]
public String Name { get; set; }
public Company Company { get; set; }
[Required]
public Guid CompanyId { get; set; }
}
Now the mapping of the Employee class:
class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap ()
{
ToTable("Employee");
Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(p => p.Name)
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 0);
Property(p => p.CompanyId )
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 1);
HasRequired(p => p.Company)
.WithMany()
.HasForeignKey(p => p.CompanyId)
.WillCascadeOnDelete(false);
}
}
Note that I also used @niaher extension for unique index annotation.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"@
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.
Syntax Gulp 3:
gulp.task('default', ['sass'], function() {....} );
Syntax Gulp 4:
gulp.task('default', gulp.series(sass), function() {....} );
You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81
I usually read command output in to variables using the FOR
command as it saves having to create temporary files. For example:
FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i
Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the %
in the FOR
statement by putting them twice:
FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%
There's a lot more you can do with FOR
. For more details just type HELP FOR
at command prompt.
# -*- mode: python -*-
block_cipher = None
a = Analysis(['SCRIPT.py'],
pathex=[
'folder path',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
],
binaries=[(''C:\\Users\\chromedriver.exe'')],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='NAME OF YOUR EXE',
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
If you want to insert other string somewhere else in existing string, you may use selection method below.
Calling character on second position:
>>> s = "0123456789"
>>> s[2]
'2'
Calling range with start and end position:
>>> s[4:6]
'45'
Calling part of a string before that position:
>>> s[:6]
'012345'
Calling part of a string after that position:
>>> s[4:]
'456789'
Inserting your string in 5th position.
>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'
Also s
is equivalent to s[:]
.
With your question you can use all your string, i.e.
>>> s = "L" + s + "LL"
or if "L"
is a some other string (for example I call it as l
), then you may use that code:
>>> s = l + s + (l * 2)
Assuming the element which is floated and will be centered is a div
with an id="content"
...
<body>
<div id="wrap">
<div id="content">
This will be centered
</div>
</div>
</body>
And apply the following CSS:
#wrap {
float: left;
position: relative;
left: 50%;
}
#content {
float: left;
position: relative;
left: -50%;
}
Here is a good reference regarding that.
The full list of commands is available at http://your-jenkins/cli
The command for a clean shutdown is http://your-jenkins/safe-shutdown
You may also want to use http://your-jenkins/safe-restart
Strings are hard work in C.
#include <stdio.h>
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
The 12
is enough bytes to store the text "pre_"
, the text "_suff"
, a string of up to two characters ("99"
) and the NULL terminator that goes on the end of C string buffers.
This will tell you how to use snprintf
, but I suggest a good C book!
Incase if you don't file in your local repo but in git repo, then simply open file in git repo through web interface and find Delete button at right corner in interface. Click Here, To view interface Delete Option
Based on your question:
My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?
Using the code you gave, you can do this:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import thread
def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(1024)
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
msg = raw_input('SERVER >> ')
#Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
clientsocket.send(msg)
clientsocket.close()
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print 'Got connection from', addr
while True:
c, addr = s.accept() # Establish connection with client.
thread.start_new_thread(on_new_client,(c,addr))
#Note it's (addr,) not (addr) because second parameter is a tuple
#Edit: (c,addr)
#that's how you pass arguments to functions when creating new threads using thread module.
s.close()
As Eli Bendersky mentioned, you can use processes instead of threads, you can also check python threading
module or other async sockets framework. Note: checks are left for you to implement how you want and this is just a basic framework.
Check your apache error log. I had this error "[error] (OS 5)Access is denied. : could not open transfer log file C:/wamp/logs/access.log. Unable to open logs" Then I rename my "access.log" to other name, you can delete if you don't need/never see your access log. Then restart your apache service. This happen because the file size too big. I think if you trying to open this file using notepad, it will not open, I tried to open that before. Hope it help.
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
Updated below for ES6
This MDN document describes extending classes well:
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
In particular, here is now they handle it:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayHello method
Student.prototype.sayHello = function(){
alert('hi, I am a student');
}
// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
alert('goodBye');
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
Note that Object.create()
is unsupported in some older browsers, including IE8:
If you are in the position of needing to support these, the linked MDN document suggests using a polyfill, or the following approximation:
function createObject(proto) {
function ctor() { }
ctor.prototype = proto;
return new ctor();
}
Using this like Student.prototype = createObject(Person.prototype)
is preferable to using new Person()
in that it avoids calling the parent's constructor function when inheriting the prototype, and only calls the parent constructor when the inheritor's constructor is being called.
Thankfully, the JavaScript designers have heard our pleas for help and have adopted a more suitable way of approaching this issue.
MDN has another great example on ES6 class inheritance, but I'll show the exact same set of classes as above reproduced in ES6:
class Person {
sayHello() {
alert('hello');
}
walk() {
alert('I am walking!');
}
}
class Student extends Person {
sayGoodBye() {
alert('goodBye');
}
sayHello() {
alert('hi, I am a student');
}
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
Clean and understandable, just like we all want. Keep in mind, that while ES6 is pretty common, it's not supported everywhere:
Try ContentTemplate:
<Button Grid.Row="2" Grid.Column="0" Width="20" Height="20"
Template="{StaticResource SomeTemplate}">
<Button.ContentTemplate>
<DataTemplate>
<Image Source="../Folder1/Img1.png" Width="20" />
</DataTemplate>
</Button.ContentTemplate>
</Button>
To have a little better navigation in insert mode, why not map some keys?
imap <C-b> <Left>
imap <C-f> <Right>
imap <C-e> <End>
imap <C-a> <Home>
" <C-a> is used to repeat last entered text. Override it, if its not needed
If you can work around making the Meta key work in your terminal, you can mock emacs mode even better. The navigation in normal-mode is way better, but for shorter movements it helps to stay in insert mode.
For longer jumps, I prefer the following default translation:
<Meta-b> maps to <Esc><C-left>
This shifts to normal-mode and goes back a word
You can do this in a one line LINQ statement. OK, I realise this is not necessarily the fastest, so doesn't technically answer the question, but it's probably the easiest to write:
str.All(c => c >= '0' && c <= '9')
This is what you can do:
SELECT *
FROM yourTable
PIVOT (MAX(xCount)
FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt
Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print
can be get using the str()
function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you '2008-11-22 19:53:42'
.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr()
function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'
.
What happened is that when you have printed the date using print
, it used str()
so you could see a nice date string. But when you have printed mylist
, you have printed a list of objects and Python tried to represent the set of data, using repr()
.
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str()
. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date)
.
One last thing. When you tried to print the dates, you printed mylist
. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str()
because print will use it for you. But it should not become a habit :-)
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime()
method.
strftime()
expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%"
represent a format for something:
%d
is the day number (2 digits, prefixed with leading zero's if necessary)%m
is the month number (2 digits, prefixed with leading zero's if necessary)%b
is the month abbreviation (3 letters)%B
is the month name in full (letters)%y
is the year number abbreviated (last 2 digits)%Y
is the year number full (4 digits)etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
Create a new 640x480 image and fill it with purple (red+blue):
cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255));
Note:
Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...
npm install --save koa-cors
...and use it in the code:
const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());
problem solved.
I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:
bootbox.confirm("Are you sure to want to delete , function(result) {
//here result will be true
// delete process code goes here
});
Offical bootboxjs site
For the sake of completeness, I'll point out that the broken "Version 2" logic can be replaced with a switch statement that works, and also make use of arrays for both speed and clarity, like so:
// used for $current_home = 'current'; $home_group = array( 'home' => True, ); // used for $current_users = 'current'; $user_group = array( 'users.online' => True, 'users.location' => True, 'users.featured' => True, 'users.new' => True, 'users.browse' => True, 'users.search' => True, 'users.staff' => True, ); // used for $current_forum = 'current'; $forum_group = array( 'forum' => True, ); switch (true) { case isset($home_group[$p]): $current_home = 'current'; break; case isset($user_group[$p]): $current_users = 'current'; break; case isset($forum_group[$p]): $current_forum = 'current'; break; default: user_error("\$p is invalid", E_USER_ERROR); }
I'm the author of modular-spring-contexts.
This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts
works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.
The key points then are
A simple example would look like this:
File moduleDefinitions.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:module id="serverModule">
<module:config location="/serverModule.xml" />
</module:module>
<module:module id="clientModule">
<module:config location="/clientModule.xml" />
<module:requires module="serverModule" />
</module:module>
</beans>
File serverModule.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
<constructor-arg index="0" value="123.45" />
<meta key="exported" value="true"/>
</bean>
</beans>
File clientModule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />
</beans>
Well yea, they are the same, but....!
window.location
is not working on some Internet Explorer browsers.
If the files are written using ES6 export, you can write:
module.exports = {
...require('./foo'),
...require('./bar'),
};
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
I don't have much experience working with php but from a logic standpoint this is what I would do.
Below is some pseudocode illustrating this technique:
for (int i = 0; i < MySQLResults.count; i++){
$objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name);
// Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
$objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
$objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
}
The 4th option described above is a simple and nice way to do it, which has to be combined with the 2nd option in the case where you have to handle a class hierarchy like for instance a member list which is any of a occurences of subclasses of a Member super class, eg Director extends Member or Student extends Member. In that case you have to give the subclass type in the json format
You can apply the list as separate arguments:
print(*L)
and let print()
take care of converting each element to a string. You can, as always, control the separator by setting the sep
keyword argument:
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join()
:
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L
!
If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.
<TextBlock>
<Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
Click here
</Hyperlink>
</TextBlock>
In the code-behind you would need to add something similar to this to handle the RequestNavigate event:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
// for .NET Core you need to add UseShellExecute = true
// see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
In addition you will also need the following imports:
using System.Diagnostics;
using System.Windows.Navigation;
It will look like this in your application:
net stop <your service> && net start <your service>
No net restart
, unfortunately.
Main Program -> Run -> Edit Configurations -> Inside Configuration there is Program arguments text box. add space separated argument in the text box. Then you can read those arguments in the args array (public static void main(String[] args))
Rather than silencing the warnings, gcc style is usually to use either standard C constructs or the __attribute__
extension to tell the compiler more about your intention. For instance, the warning about assignment used as a condition is suppressed by putting the assignment in parentheses, i.e. if ((p=malloc(cnt)))
instead of if (p=malloc(cnt))
. Warnings about unused function arguments can be suppressed by some odd __attribute__
I can never remember, or by self-assignment, etc. But generally I prefer just globally disabling any warning option that generates warnings for things that will occur in correct code.
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
Your port must be busy in some Other Process. So you can download TCPView on https://technet.microsoft.com/en-us/sysinternals/bb897437 and kill the process for used port.
If you don't know your port, double click on the server that is not starting and click on Open Server Properties Page and click on glassfish from left column. You will find the ports here.
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item.
When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case).
However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory.
Are you looking for this selector?:
.ui-menu .ui-menu-item a{
background:red;
height:10px;
font-size:8px;
}
Ugly demo:
Just replace with your code:
.ui-menu .ui-menu-item a{
color: #96f226;
border-radius: 0px;
border: 1px solid #454545;
}
This has always worked well for me. It's not messy and very clean.
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>
There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("\nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
This is the echo server handling multiple clients... Runs fine and good using Threads
// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server_X_Client {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
is= new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}
Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..
// A simple Client Server Protocol .. Client for Echo Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class NetworkClient {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}
I just did:
git merge --continue
At which point vi launched to edit a merge comment. A quick :wq and the merge was done.
The solution might be updating some tools.
Here's my scenario from 2020 with Ruby and Python:
I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
So what was still trying to use that old 1.0 version?
It tuned out it was Ruby 2.5.5.
So I just installed Ruby 2.5.8 and removed the old one.
Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.
If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)?
Yes, isolating platform-specific code with #ifdefs
is the conventional way this is done.
Another approach would be to have a have clean #ifdef
-less header which contains function declarations and put the implementations in platform specific source files.
For example, check out how POCO (Portable Components) C++ library does something similar for their Environment class.
At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).
Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
This solution is not good every time. But i have only two columns and I want second column to take all the remaining space. This worked for me
<tr>
<td class="text-nowrap">A</td>
<td class="w-100">B</td>
</tr>
Above solution didn't work for me.
First run brew doctor
.
if you see something like
Error: unknown or unsupported macOS version: :mountain_lion
then there are some outdated packages which needs to be removed, mine was
mongodb
.
It could be python@2
, node@6
or some other package.
uninstall those packages brew uninstall [name]
then run brew doctor
to verify if everything is ok.
Then you can reinstall those packages again after brew update && brew upgrade
.
You can't achieve text size change with a state list drawable. To change text color and text size do this:
Text color
To change the text color, you can create color state list resource. It will be a separate resource located in res/color/
directory. In layout xml you have to set it as the value for android:textColor
attribute. The color selector will then contain something like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/text_pressed" />
<item android:color="@color/text_normal" />
</selector>
Text size
You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.
Probably the easiest solution might be utilizing View.onTouchListener()
and handle the up and down events accordingly. Use something like this:
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// change text size to the "pressed value"
return true;
case MotionEvent.ACTION_UP:
// change text size to the "normal value"
return true;
default:
return false;
}
}
});
A different solution might be to extend the view and override the setPressed(Boolean)
method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).
I had also faced this issue. NO it will not affect your original repo by anyway. just simply delete it by entering the name of forked repo
public class NumberFormatExceptionExample {
private static final String str = "123.234";
public static void main(String[] args){
float i = Float.valueOf(str); //Float.parseFloat(str);
System.out.println("Value parsed :"+i);
}
}
This should resolve the problem.
Can anyone suggest how should we handle this when the string comes in 35,000.00
I dont know about a one-line FTP server, but if you do
python -m SimpleHTTPServer
It'll run an HTTP server on 0.0.0.0:8000, serving files out of the current directory. If you're looking for a way to quickly get files off a linux box with a web browser, you cant beat it.
If you are working on linux/mac you can do this.
from subprocess import call
script="cat *.csv>merge.csv"
call(script,shell=True)
You need to use event delegation because those buttons don't exist on load:
http://jsfiddle.net/isherwood/Z7fG7/1/
$(document).on('click', 'button.removebutton', function () { // <-- changes
alert("aa");
$(this).closest('tr').remove();
return false;
});
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
The Get-ChildItem cmdlet has an -Exclude
parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:
function GetFiles($path = $pwd, [string[]]$exclude) { foreach ($item in Get-ChildItem $path) { if ($exclude | Where {$item -like $_}) { continue } if (Test-Path $item.FullName -PathType Container) { $item GetFiles $item.FullName $exclude } else { $item } } }
NODE_ENV is an environmental variable that stands for node environment in express server.
It's how we set and detect which environment we are in.
It's very common using production
and development
.
Set:
export NODE_ENV=production
Get:
You can get it using app.get('env')
You can add global variable:
private Context context;
then assign the context from here:
@Override
public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}
Happy Codding :)
Like @ckpepper02 said, the body content:url option works well. I found however that if you modify it slightly you can just use it to add a header image of sorts using the :before pseudo element as follows.
@media print {
body:before { content: url(img/printlogo.png);}
}
That will slip the image at the top of the page, and from my limited testing, it works in Chrome and the IE9
-hanz
For Jquery UI buttons this works :
$("#buttonId").button( "option", "disabled", true | false );
Logical operators for boolean indexing in Pandas
It's important to realize that you cannot use any of the Python logical operators (and
, or
or not
) on pandas.Series
or pandas.DataFrame
s (similarly you cannot use them on numpy.array
s with more than one element). The reason why you cannot use those is because they implicitly call bool
on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:
>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.
However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array
, pandas.Series
, pandas.DataFrame
, or any other (conforming) numpy.array
subclass:
and
has np.logical_and
or
has np.logical_or
not
has np.logical_not
numpy.logical_xor
which has no Python equivalent but is a logical "exclusive or" operation So, essentially, one should use (assuming df1
and df2
are pandas DataFrames):
np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)
However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):
np.bitwise_and
or the &
operatornp.bitwise_or
or the |
operatornp.invert
(or the alias np.bitwise_not
) or the ~
operatornp.bitwise_xor
or the ^
operatorTypically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:
(df1 < 10) | (df2 > 10) # instead of the wrong df1 < 10 | df2 > 10
This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10
(where a
and b
are for example simple integers) and don't need the parenthesis.
It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:
>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])
>>> np.logical_and(a1, a2)
array([False, False, False, True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)
And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:
>>> a3 = np.array([1, 2, 3, 4])
>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])
Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
and | np.logical_and | np.bitwise_and | &
-------------------------------------------------------------------------------------
or | np.logical_or | np.bitwise_or | |
-------------------------------------------------------------------------------------
| np.logical_xor | np.bitwise_xor | ^
-------------------------------------------------------------------------------------
not | np.logical_not | np.invert | ~
Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise.
However be careful with the bitwise invert on plain Python bool
s because the bool will be interpreted as integers in this context (for example ~False
returns -1
and ~True
returns -2
).
For some reason, this was not working
<p:column headerText="" width="25px" sortBy="#{row.key}">
But this worked:
<p:column headerText="" width="25" sortBy="#{row.key}">
just like in C and C++, the boolean or operator is ||
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
Here are the steps:
localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3
<%@page import="java.util.Enumeration"%>
<%
Enumeration in = request.getParameterNames();
while(in.hasMoreElements()) {
String paramName = in.nextElement().toString();
out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
}
%>
key = datr
key2 = datr2
key3 = datr3
Notice, that if your module dependency has different flavors, you should use one of the strategies:
Like that:
dependencies {
compile project(path: ':module', configuration:'alphaDebug')
}
As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents
to access REST APIs:
$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');
Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.
I had the same problem. Try recompiling using -fPIC
flag.
In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.
This is the relevant part of the server code that helped:
if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}
html form should look something like:
<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
I followed @LachlanB approach and indeed the session was available when the session cookie was present on the request. The missing part is how the Session cookie is sent to the client the first time?
I created a HttpModule which not only enabling the HttpSessionState availability but also sends the cookie to the client when a new session is created.
public class WebApiSessionModule : IHttpModule
{
private static readonly string SessionStateCookieName = "ASP.NET_SessionId";
public void Init(HttpApplication context)
{
context.PostAuthorizeRequest += this.OnPostAuthorizeRequest;
context.PostRequestHandlerExecute += this.PostRequestHandlerExecute;
}
public void Dispose()
{
}
protected virtual void OnPostAuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (this.IsWebApiRequest(context))
{
context.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
protected virtual void PostRequestHandlerExecute(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (this.IsWebApiRequest(context))
{
this.AddSessionCookieToResponseIfNeeded(context);
}
}
protected virtual void AddSessionCookieToResponseIfNeeded(HttpContext context)
{
HttpSessionState session = context.Session;
if (session == null)
{
// session not available
return;
}
if (!session.IsNewSession)
{
// it's safe to assume that the cookie was
// received as part of the request so there is
// no need to set it
return;
}
string cookieName = GetSessionCookieName();
HttpCookie cookie = context.Response.Cookies[cookieName];
if (cookie == null || cookie.Value != session.SessionID)
{
context.Response.Cookies.Remove(cookieName);
context.Response.Cookies.Add(new HttpCookie(cookieName, session.SessionID));
}
}
protected virtual string GetSessionCookieName()
{
var sessionStateSection = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
return sessionStateSection != null && !string.IsNullOrWhiteSpace(sessionStateSection.CookieName) ? sessionStateSection.CookieName : SessionStateCookieName;
}
protected virtual bool IsWebApiRequest(HttpContext context)
{
string requestPath = context.Request.AppRelativeCurrentExecutionFilePath;
if (requestPath == null)
{
return false;
}
return requestPath.StartsWith(WebApiConfig.UrlPrefixRelative, StringComparison.InvariantCultureIgnoreCase);
}
}
In languages that support regular expressions with non-capturing groups:
((?:[^/]*/)*)(.*)
I'll explain the gnarly regex by exploding it...
(
(?:
[^/]*
/
)
*
)
(.*)
What the parts mean:
( -- capture group 1 starts
(?: -- non-capturing group starts
[^/]* -- greedily match as many non-directory separators as possible
/ -- match a single directory-separator character
) -- non-capturing group ends
* -- repeat the non-capturing group zero-or-more times
) -- capture group 1 ends
(.*) -- capture all remaining characters in group 2
To test the regular expression, I used the following Perl script...
#!/usr/bin/perl -w
use strict;
use warnings;
sub test {
my $str = shift;
my $testname = shift;
$str =~ m#((?:[^/]*/)*)(.*)#;
print "$str -- $testname\n";
print " 1: $1\n";
print " 2: $2\n\n";
}
test('/var/log/xyz/10032008.log', 'absolute path');
test('var/log/xyz/10032008.log', 'relative path');
test('10032008.log', 'filename-only');
test('/10032008.log', 'file directly under root');
The output of the script...
/var/log/xyz/10032008.log -- absolute path
1: /var/log/xyz/
2: 10032008.log
var/log/xyz/10032008.log -- relative path
1: var/log/xyz/
2: 10032008.log
10032008.log -- filename-only
1:
2: 10032008.log
/10032008.log -- file directly under root
1: /
2: 10032008.log
HTML
<input type="button" value="My Button"
onclick="location.href = 'https://myurl'" />
MVC
<input type="button" value="My Button"
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />
This could be due running wrong scheme as well.
By default mongodb has no enabled access control, so there is no default user or password.
To enable access control, use either the command line option --auth
or security.authorization configuration file setting.
You can use the following procedure or refer to Enabling Auth in the MongoDB docs.
Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db1
Connect to the instance.
mongo --port 27017
Create the user administrator.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin"
The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).
As RFC 5280 says:
The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.
X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.
The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".
In the context of the article you're linking to, the subject would be the user/owner of the cert.
Also consider using Array()
. From the Ruby Community Style Guide:
Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.
# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }
# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }
# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }
MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.
I discovered this after a lot of experimentation.
In the initialisation of your activity:
setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
activity.openContextMenu(view);
return true; // avoid extra click events
}
});
setOnTouch(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent e){
switch(e.getAction & MotionEvent.ACTION_MASK){
// do drag/gesture processing.
}
// you MUST return false for ACTION_DOWN and ACTION_UP, for long click to work
// you can return true for ACTION_MOVEs that you consume.
// DOWN/UP are needed by the long click timer.
// if you want, you can consume the UP if you have made a drag - so that after
// a long drag, no long-click is generated.
return false;
}
});
setLongClickable(true);
not sure if anyone notice it may be correct to return a 301 but browsers choke on it to doing
rewrite ^(.*)$ https://yoursite.com$1;
is faster than:
return 301 $scheme://yoursite.com$request_uri;
The way you have added a row into the table layout you can add multiple TableRow
instances into your tableLayout
object
tl.addView(row1);
tl.addView(row2);
etc...
All: Evidently this is working as designed. Please see new ref man dated 2019-7-23, Section 6.1.6, Security Issues with LOAD DATA LOCAL.
Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html
<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {
overflow: scroll;
width:100%;
}
#outer_wrapper #inner_wrapper {
width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
width: 250px;
height:300px;
float: left;
margin: 0 4px 0 0;
border:1px grey solid;
}
</style>
</head>
<body>
<div id="outer_wrapper">
<div id="inner_wrapper">
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<!-- more boxes here -->
</div>
</div>
</body>
</html>
The jar was compiled to be 1.6
compliant. That is why you get this error. Two resolutions:
1) Use Java 1.6
OR
2) Recompile the jar to be compliant for your environment 1.7
When I tried to access the result from
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
it was plain text result with no key-value pairs Here is an example
var fruits = {
apple: "fruits/apple.png",
banana: "fruits/banana.png",
watermelon: "watermelon.jpg",
grapes: "grapes.png",
orange: "orange.jpg"
}
Now i want to get all links in a separated array , but with this code
function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
console.log('\"'+obJect[x]+'\"');
});
}
the result of :
linksOfPics(fruits)
"fruits/apple.png"
"fruits/banana.png"
"watermelon.jpg"
"grapes.png"
"orange.jpg"
undefined
I figured out this one which solves what I'm looking for
console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]
Not tested, but I think this will be close?
SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2
The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.
The following will do.
unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));
And setting &x
to char *
will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.
String text="";
for (Iterator i = keys.iterator(); i.hasNext()
{
String key = (String) i.next();
String value = (String) map.get(key);
text+=key + " = " + value;
}
textview.setText(text);
Hashmaps can only use classes
, not primitives
. This page from programmerinterview.com might be of use in guiding you to finding the answer. To be honest, I haven't figured out the answer to this problem in detail myself.
Try:
=ArrayFormula(QUERY(A:A&{"",""};"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'";1))
22/07/2014 Some time in the last month, Sheets has started supporting more flexible concatenation of arrays, using an embedded array. So the solution may be shortened slightly to:
=QUERY({A:A,A:A},"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'",1)
For Unix systems command time
(/usr/bin/time) gives you that info if you pass -v. See Maximum resident set size
below, which is the maximum (peak) real (not virtual) memory that was used during program execution:
$ /usr/bin/time -v ls /
Command being timed: "ls /"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 250%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 315
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
I had the same issue. The problem was that I copied the code from another service as a starting point and did not change the service class in .svc file
Open the .svc file an make sure that the Service attribute is correct.
<%@ ServiceHost Language="C#" Debug="true" Service="SME.WCF.ApplicationServices.ReportRenderer" CodeBehind="ReportRenderer.svc.cs" %>
Another way to quickly change tabs would be in VSCode 1.45 (April 2020)
Switch tabs using mouse wheel
When you use the mouse wheel to scroll over editor tabs, you can currently not switch to the tab, only reveal tabs that are out of view.
Now with a new setting
workbench.editor.scrollToSwitchTabs
this behaviour can be changed if you change it totrue
.Note: you can also press and hold the Shift key while scrolling to get the opposite behaviour (i.e. you can switch to tabs even with this setting being turned off).
You can also try recfromcsv()
which can guess data types and return a properly formatted record array.
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
You can load an HTML
attributed string in Swift
as follow
var Str = NSAttributedString(
data: htmlstring.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
label.attributedText = Str
To load a html
from file
if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) {
let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
textView.attributedText = attributedString
textView.editable = false
}
http://sketchytech.blogspot.in/2013/11/creating-nsattributedstring-from-html.html
And setup string as per your required attribute....follow this..
http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
If you are using Windows Authentication, make sure to log-in to Windows at least once with that user.
Looks like it is a known problem with EdmGen: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/12aaac4d-2be8-44f3-9448-d7c659585945/
Set up your storyboard with two buttons and hook them up to your view controller (see code below).
Add an image to your Assets.xcassets. I called mine "lion".
import UIKit
class ViewController: UIViewController {
// share text
@IBAction func shareTextButton(_ sender: UIButton) {
// text to share
let text = "This is some text that I want to share."
// set up activity view controller
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
// share image
@IBAction func shareImageButton(_ sender: UIButton) {
// image to share
let image = UIImage(named: "Image")
// set up activity view controller
let imageToShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
}
Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.
excludedActivityTypes
as shown in the code above. popoverPresentationController?.sourceView
line will cause your app to crash when run on an iPad.UIDocumentInteractionController
for that.jQuery version:
$(window).unload(function(){
// Do Something
});
Update: jQuery 3:
$(window).on("unload", function(e) {
// Do Something
});
Thanks Garrett
Basically you need 3 divs. First as wrapper
, second as left
and third as right
.
.wrapper {
width:500px;
overflow:hidden;
}
.left {
width:250px;
float:left;
}
.right {
width:250px;
float:right;
}
Example how to make 2 columns http://jsfiddle.net/huhu/HDGvN/
CSS Cheat Sheet for reference
At some point, isn't it easier(or just as easy) to use a forEach
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
var reduced = []_x000D_
options.forEach(function(option) {_x000D_
if (option.assigned) {_x000D_
var someNewValue = { name: option.name, newProperty: 'Foo' }_x000D_
reduced.push(someNewValue);_x000D_
}_x000D_
});_x000D_
_x000D_
document.getElementById('output').innerHTML = JSON.stringify(reduced);
_x000D_
<h1>Only assigned options</h1>_x000D_
<pre id="output"> </pre>
_x000D_
However it would be nice if there was a malter()
or fap()
function that combines the map
and filter
functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.
What is the difference between Git and GitHub?
Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.
GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.
Is Git saving every repository locally (in the user's machine) and in GitHub?
No, it's only local. You can decide to push (publish) some branches on GitHub.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.
How does Git compare to a backup system such as Time Machine?
It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, committing and pushing are both manual.
If are not collaborating and you are already using a backup system why would you use Git?
If you encounter an error between commits you can use the command git diff
to see the differences between the current code and the last working commit, helping you to locate your error.
You can also just go back to the last working commit.
If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.
You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.
Make sure you check gitimmersion.com.
Install "xclip" if you haven't...
sudo apt-get install xclip
Xclip puts the data into the "selection/highlighted" clipboard that you middle-click to paste as opposed to "ctrl+v"
While in vim use ex commands:
7w !xclip
or
1,7w !xclip
or
%w !xclip
Then just middle-click to paste into any other application...
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
I always liked using date -r /the/file +%s
to find its age.
You can also do touch --date '2015-10-10 9:55' /tmp/file
to get extremely fine-grained time on an arbitrary date/time.
Simply put id attribute in your input text field -
<input type="text" maxlength="3" name="value" id="value" />
You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.
In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.
Use Integer
instead.
HashMap<Integer, MyObject> myMap = new HashMap<Integer, MyObject>();
Java will automatically autobox your int
primitive values to Integer
objects.
Read more about autoboxing from Oracle Java documentations.
just use \r\n for endline if you are using windows operating system.
The message is actually pretty clear: something creates a ThreadLocal
with value of type org.apache.axis.MessageContext
- this is a great hint. It most likely means that Apache Axis framework forgot/failed to cleanup after itself. The same problem occurred for instance in Logback. You shouldn't bother much, but reporting a bug to Axis team might be a good idea.
Tomcat reports this error because the ThreadLocal
s are created per HTTP worker threads. Your application is undeployed but HTTP threads remain - and these ThreadLocal
s as well. This may lead to memory leaks (org.apache.axis.MessageContext
can't be unloaded) and some issues when these threads are reused in the future.
For details see: http://wiki.apache.org/tomcat/MemoryLeakProtection
Worked for me after replacing
SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME");
with
SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME").setMaster("local[2]").set("spark.executor.memory","1g");
Found this solution on some other thread on stackoverflow.
I have code to perform UTC to Local and Local to UTC times which allows conversion using code like this
DECLARE @usersTimezone VARCHAR(32)='Europe/London'
DECLARE @utcDT DATETIME=GetUTCDate()
DECLARE @userDT DATETIME=[dbo].[funcUTCtoLocal](@utcDT, @usersTimezone)
and
DECLARE @usersTimezone VARCHAR(32)='Europe/London'
DECLARE @userDT DATETIME=GetDate()
DECLARE @utcDT DATETIME=[dbo].[funcLocaltoUTC](@userDT, @usersTimezone)
The functions can support all or a subset of timezones in the IANA/TZDB as provided by NodaTime - see the full list at https://nodatime.org/TimeZones
Be aware that my use case means I only need a 'current' window, allowing the conversion of times within the range of about +/- 5 years from now. This means that the method I've used probably isn't suitable for you if you need a very wide period of time, due to the way it generates code for each timezone interval in a given date range.
The project is on GitHub: https://github.com/elliveny/SQLServerTimeConversion
This generates SQL function code as per this example
System.Reflection.Assembly.GetExecutingAssembly().Location
Generically, you can use a custom font using @font-face
in your CSS. Here's a very basic example:
@font-face {
font-family: 'YourFontName'; /*a name to be used later*/
src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}
Then, trivially, to use the font on a specific element:
.classname {
font-family: 'YourFontName';
}
(.classname
is your selector).
Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.
You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face
rules, so you don't have to write your own).
while also preventing people from having free access to download the font, if possible
Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.
I hope that helped!
I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding
style="position: relative; bottom: 0px"
to your Widget2 tag. Also try:
style="position: absolute; bottom: 0px"
if you want to snap your widget to the bottom of the screen.
I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.
You can also Try this:
var results= persons.GroupBy(n => new { n.PersonId, n.car})
.Select(g => new {
g.Key.PersonId,
g.Key.car)}).ToList();
I had the same problem with Pool()
in Python 3.6.3.
Error received: TypeError: can't pickle _thread.RLock objects
Let's say we want to add some number num_to_add
to each element of some list num_list
in parallel. The code is schematically like this:
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list))
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
def run_parallel(self, num, shared_new_num_list):
new_num = num + self.num_to_add # uses class parameter
shared_new_num_list.append(new_num)
The problem here is that self
in function run_parallel()
can't be pickled as it is a class instance. Moving this parallelized function run_parallel()
out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add
and then you have to pass it as an argument.
Solution:
def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
new_num = num + to_add
shared_new_num_list.append(new_num)
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
Other suggestions above didn't help me.
My Project Build Target of android-support-v7-appcompat was with API 19 just changed it to API 20 it worked for me
Right click on android-support-v7-appcompat
library project
Go to properties
Click on Android
Change project build Target from Android 4.x.x to Android 5.0
This helped me hopefully it helps others too.
use getContext() instead of MainActivity.this
Intent intent = new Intent(getContext(), SecondActivity.class);
startActivity(start);
I think the equivalent is Int64
One way to resolve this is to login to your root user in phpmyadmin, go to the users tab, find and select the specific user that can't access the select and other queries . Then tick the all checkboxes and just click go. Now that user can select, update and whatever they want.
From iOS 8 we can use the new isOperatingSystemAtLeastVersion
method on NSProcessInfo
NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
// iOS 8.0.1 and above logic
} else {
// iOS 8.0.0 and below logic
}
Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with
if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
// conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
// we're on iOS 7 or below
}
For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
// Load resources for iOS 6.1 or earlier
} else {
// Load resources for iOS 7 or later
}
$(".thumbs").hover(
function(){
if (!$(this).hasClass("selected")) {
$(this).stop().fadeTo("normal", 1.0);
}
},
function(){
if (!$(this).hasClass("selected")) {
$(this).stop().fadeTo("slow", 0.3);
}
}
);
Putting an if inside of each part of the hover will allow you to change the select class dynamically and the hover will still work.
$(".thumbs").click(function() {
$(".thumbs").each(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
$(this).hover();
}
});
$(this).addClass("selected");
});
As an example I've also attached a click handler to switch the selected class to the clicked item. Then I fire the hover event on the previous item to make it fade out.
In the module build.gradle, in the task field, I get an error unless I use:
def ndkDir = plugins.getPlugin('com.android.application').sdkHandler.getNdkFolder()
I see people using
def ndkDir = android.plugin.ndkFolder
and
def ndkDir = plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder()
but neither of those worked until I changed it to the plugin I was actually importing.
You can hang a lot of functions on the onClick
event for one element. How can you be sure the false
one will be the last one to fire? preventDefault
on the other hand will definitely prevent only the default behavior of the element.
Only for mariaDB
It doesn't get simpler then this, Just execute this in mysql prompt.
kill USER username;
It will kill all process under provided username. because most of the people use same user for all purpose, it works!
I have tested this on MariaDB not sure about mysql.
You cannot display images in a console window. You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC or PyFLTK. There are plenty of tutorial how to create siomple windows and loading images iun python.
I'd create a cte and do an inner join. It's not efficient but it's convenient
with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER()
OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM TABLE)
select *
from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table
group by date, status, title) t2
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title
In essence, It means that it takes the same amount of time to look up a value in your collection whether you have a small number of items in your collection or very very many (within the constraints of your hardware)
O(n) would mean that the time it takes to look up an item is proportional to the number of items in the collection.
Typical examples of these are arrays, which can be accessed directly, regardless of their size, and linked lists, which must be traversed in order from the beginning to access a given item.
The other operation usually discussed is insert. A collection can be O(1) for access but O(n) for insert. In fact an array has exactly this behavior, because to insert an item in the middle, You would have to move each item to the right by copying it into the following slot.
There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse
for more details. In this case, you probably want:
git diff HEAD@{1}
The @{1}
means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD
on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.
I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do
git diff HEAD@{1} filename
This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.
Check for id. It may have root permissions.
So type su and then execute the script as ./scripts/replace-md5sums.py.
It works.
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}