Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...
another way, not using regex, is to use fields/delimiter method eg
string="http://www.suepearson.co.uk/product/174/71/3816/"
echo $string | awk -F"/" '{print $1,$2,$3}' OFS="/"
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
is there a better way?
Well, if you are really looking for a better way, you can probably add another layer of abstraction on top of Rate. Well here is something I just came up with using Nullable Design Pattern.
using System; using System.Collections.Generic; namespace NullObjectPatternTest { public class Program { public static void Main(string[] args) { var items = new List { new Item(RateFactory.Create(20)), new Item(RateFactory.Create(null)) }; PrintPricesForItems(items); } private static void PrintPricesForItems(IEnumerable items) { foreach (var item in items) Console.WriteLine("Item Price: {0:C}", item.GetPrice()); } } public abstract class ItemBase { public abstract Rate Rate { get; } public int GetPrice() { // There is NO need to check if Rate == 0 or Rate == null return 1 * Rate.Value; } } public class Item : ItemBase { private readonly Rate _Rate; public override Rate Rate { get { return _Rate; } } public Item(Rate rate) { _Rate = rate; } } public sealed class RateFactory { public static Rate Create(int? rateValue) { if (!rateValue || rateValue == 0) return new NullRate(); return new Rate(rateValue); } } public class Rate { public int Value { get; set; } public virtual bool HasValue { get { return (Value > 0); } } public Rate(int value) { Value = value; } } public class NullRate : Rate { public override bool HasValue { get { return false; } } public NullRate() : base(0) { } } }
import {Component, View, OnInit, OnDestroy} from "angular2/core";
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
})
export class NewContactComponent implements OnInit, OnDestroy {
ticks = 0;
private timer;
// Subscription object
private sub: Subscription;
ngOnInit() {
this.timer = Observable.timer(2000,5000);
// subscribing to a observable returns a subscription object
this.sub = this.timer.subscribe(t => this.tickerFunc(t));
}
tickerFunc(tick){
console.log(this);
this.ticks = tick
}
ngOnDestroy(){
console.log("Destroy timer");
// unsubscribe here
this.sub.unsubscribe();
}
}
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
Add to your .gitconfig file next code:
[color]
ui = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
If want to remove the word from only the start of the string, then you could do:
string[string.startswith(prefix) and len(prefix):]
Where string is your string variable and prefix is the prefix you want to remove from your string variable.
For example:
>>> papa = "papa is a good man. papa is the best."
>>> prefix = 'papa'
>>> papa[papa.startswith(prefix) and len(prefix):]
' is a good man. papa is the best.'
See this answer for a a clean & simple 'class' solution with a private and public interface and support for composition
The only way I could get it to work:
comboBox1.Text = "";
For some reason ionden's solution didn't work for me.
A slight variation...
new File('/path/to/file').eachLine { line ->
println line
}
Close to what is already posted, but without the redundant parameter:
class String
def true?
self.to_s.downcase == "true"
end
end
usage:
do_stuff = "true"
if do_stuff.true?
#do stuff
end
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
You can use the following code. It is similar to existing functions except that you can force special character count:
function random_string() {
// 8 characters: 7 lower-case alphabets and 1 digit
$character_sets = [
["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
["count" => 1, "characters" => "0123456789"]
];
$temp_array = array();
foreach ($character_sets as $character_set) {
for ($i = 0; $i < $character_set["count"]; $i++) {
$random = random_int(0, strlen($character_set["characters"]) - 1);
$temp_array[] = $character_set["characters"][$random];
}
}
shuffle($temp_array);
return implode("", $temp_array);
}
If you dont have an entry point defined in your manifest invoking java -jar foo.jar
will not work.
Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:
java -cp foo.jar full.package.name.ClassName
See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
Seen here. You can unzip and
Clicking Local will prefix your location fith file:/C:/etc/folder
You can Click archive instead and select your zip, as suggested in the second popular question. It will prefix with jar://path.zip but it is not accepted by Eclipse itself. So, I used the plain folder solution.
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";
You should define the __unicode__
method on your model, and the template will call it automatically when you reference the instance.
You want the NPGSQL library. Your only other alternative is ODBC.
If you want to insert HTML code inside existing page's tag use Jnerator. This tool was created specially for this goal.
Instead of writing next code
var htmlCode = '<ul class=\'menu-countries\'><li
class=\'item\'><img src=\'au.png\'></img><span>Australia </span></li><li
class=\'item\'><img src=\'br.png\'> </img><span>Brazil</span></li><li
class=\'item\'> <img src=\'ca.png\'></img><span>Canada</span></li></ul>';
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
You can write more understandable structure
var jtag = $j.ul({
class: 'menu-countries',
child: [
$j.li({ class: 'item', child: [
$j.img({ src: 'au.png' }),
$j.span({ child: 'Australia' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'br.png' }),
$j.span({ child: 'Brazil' })
]}),
$j.li({ class: 'item', child: [
$j.img({ src: 'ca.png' }),
$j.span({ child: 'Canada' })
]})
]
});
var htmlCode = jtag.html();
var element = document.getElementById('myTag');
element.innerHTML = htmlCode;
import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)
Seen below :- output when i run JupyterNotebook outside a CONDA venv
/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul 2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
Seen below when i run same JupyterNoteBook within a CONDA Venv created with command --
conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV
in my Jupyter Notebook it prints :-
/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
also if you already have various VENV's created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu... JupyterNotebookScreencapture
Also to install ipykernel within an existing CONDA Virtual Environment -
$ /path/to/python -m ipykernel install --help
usage: ipython-kernel-install [-h] [--user] [--name NAME]
[--display-name DISPLAY_NAME]
[--profile PROFILE] [--prefix PREFIX]
[--sys-prefix]
Install the IPython kernel spec.
optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs.
I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.
As per the official documentation, there are four ways, you can allow complete access for robots to access your site.
Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt
looks like this.
User-agent: *
Disallow:
Create a /robots.txt
file with no content in it. Which will default to allow all for all type of Bots
.
Do not create a /robots.txt
altogether. Which should yield the exact same results as the above two.
From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots
know that these pages are not supposed to be indexed.
<META NAME="ROBOTS" CONTENT="NOINDEX">
In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD
tag of the page. More about this meta tag here.
Go to Control Panel ? System and Security ? System, and then click Advanced system settings on the left hand side menu.
On the Advanced tab, click Environment Variables.
Under 'User variables' append the PATH variable with path to your Python install directory:
C:\Python27;
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
I hope my script help you.
<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>
My script
<script>
$(".mostrar-producto").mouseover(function(){
$(".producto").fadeIn();
});
$(".mostrar-producto").mouseleave(function(){
$(".producto").fadeOut();
});
</script>
You cannot have spaces and tabs in the tag (i.e., name) of an XML elements, see the specs: http://www.w3.org/TR/REC-xml/#NT-STag. Beside alphanumeric characters, colon, underscore, dash and dot characters are allowed in a name, and the first letter cannot be a dash or a dot. Certain unicode characters are also permitted, without actually double-checking, I'd say that these are international letters.
A simple way to terminate a Python script early is to use the built-in quit()
function. There is no need to import any library, and it is efficient and simple.
Example:
#do stuff
if this == that:
quit()
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
You need to recalculate width and height after first condition. Here is the code of entire script:
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
While agf was right with the answer in the past, now with PEP-3124 we got our syntactic sugar.
See typing documentation for details on the @overload
decorator, but note that this is really just syntactic sugar and IMHO this is all people have been arguing about ever since.
Personally, I agree that having multiple functions with different signatures makes it more readable then having a single function with 20+ arguments all set to a default value (None
most of the time) and then having to fiddle around using endless if
, elif
, else
chains to find out what the caller actually wants our function to do with the provided set of arguments. This was long overdue following the Python Zen:
Beautiful is better than ugly.
and arguably also
Simple is better than complex.
Straight from the official Python documentation linked above:
from typing import overload
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> Tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
If you are not a big fan of operator overloading, or just more of a functional type:
// use flatMap
let result = [
["merge", "me"],
["We", "shall", "unite"],
["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]
// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]
As explained above not just the db datatype it will also affect the view that will be generated if you are scaffolding. string will generate a text_field text will generate a text_area
Use the convert function.
SELECT CONVERT(varchar(10), field_name) FROM table_name
Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null
comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null
the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.
Nonprimitive (int
s, char
s, double
s, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.
On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.
In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.
And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.
Java's actually very nicely made so that you shouldn't have to worry about null
ing variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.
*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.
In FreeBSD 11:
pkg install openldap-client # for lber.h
pkg install cyrus-sasl # if you need sasl.h
pip install python-ldap
In C/C++, pointers and arrays are (almost) equivalent.
int *a; a[0];
will return *a
, and a[1];
will return *(a + 1)
But array can't change the pointer it points to while pointer can.
new int[n]
will allocate some spaces for the "array"
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.
It doesn't read nicely though; perhaps a switch
would be more manageable?
public enum Direction {
NORTH(1) {
@Override
public Direction getOppositeDirection() {
return Direction.SOUTH;
}
},
SOUTH(-1) {
@Override
public Direction getOppositeDirection() {
return Direction.NORTH;
}
},
EAST(-2) {
@Override
public Direction getOppositeDirection() {
return Direction.WEST;
}
},
WEST(2) {
@Override
public Direction getOppositeDirection() {
return Direction.EAST;
}
};
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
public abstract Direction getOppositeDirection();
}
I failed even if I tried to update the SDK tools as mentioned here.
Here is how I solved the problem (for the library projects imported).
In File -> Project Structure -> Modules, I removed the problematic projects, and added them again by selecting New Module -> Android Library Module.
After rebuilding the project, I got all the R.java
files back.
Use the File.WriteAllText
method. It creates the file if it doesn't exist and overwrites it if it exists.
According to some developers, "Core Java" refers to package API java.util.*
, which is mostly used in coding.
The term "Core Java" is not defined by Sun, it's just a slang definition.
J2ME / J2EE still depend on J2SDK API's for compilation and execution.
Nobody would say java.util.*
is separated from J2SDK for usage.
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
You can try this:-
<a href="some.htm" target="_blank">Link Text</a>
and you can try this one also:-
<a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>
LDAP is trying to authenticate with AD when sending a transaction to another server DB. This authentication fails because the user has recently changed her password, although this transaction was generated using the previous credentials. This authentication will keep failing until ... unless you change the transaction status to Complete or Cancel in which case LDAP will stop sending these transactions.
will not work.. use $(window)
instead
$(window).on('shown.bs.modal', function() {
$('#code').modal('show');
alert('shown');
});
$(window).on('hidden.bs.modal', function() {
$('#code').modal('hide');
alert('hidden');
});
use this attribute in style
font-size: 11px !important;//your font size
by !important it override your css
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
Setting "expires" to a past date is the standard way to delete a cookie.
Your problem is probably because the date format is not conventional. IE probably expects GMT only.
My solution to this that works for the modern YouTube embed
format is as follows.
Assuming the iframe
your video is playing in has id="#video"
, this simple bit of Javascript will do the job.
$(document).ready(function(){
var stopVideo = function(player) {
var vidSrc = player.prop('src');
player.prop('src', ''); // to force it to pause
player.prop('src', vidSrc);
};
// at some appropriate time later in your code
stopVideo($('#video'));
});
I've seen proposed solutions to this issue involving use of the YouTube API
, but if your site is not an https
site, or your video is embedded using the modern format recommended by YouTube, or if you have the no-cookies
option set, then those solutions don't work and you get the "TV set to a dead channel" effect instead of your video.
I've tested the above on every browser I could lay my hands on and it works very reliably.
You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:
select *
from (
select 1 as Rank, id, add_date from Table
union all
select 2 as Rank, id, add_date from Table where distance < 5
union all
select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc
For OP's terminal Cmder
there is an integration guide, also hinted in the VS Code docs.
If you want to use VS Code tasks and encounter problems after switch to Cmder
, there is an update to @khernand's answer. Copy this into your settings.json
file:
"terminal.integrated.shell.windows": "cmd.exe",
"terminal.integrated.env.windows": {
"CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
"/k",
"%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
// OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],
The invoked file will open Cmder
as integrated terminal and switch to cmd
for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json
to make tasks work.
Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows"
setting, which lets you set your terminal for tasks globally and avoids issues with Cmder
.
"terminal.integrated.automationShell.windows": "cmd.exe"
Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.
Just make sure to add Shebang (#!/bin/bash
) line at the starting of your script and make the script executable(using chmod +x <File Name>
).
If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.
I searched on the internet and found a simple jquery code to handle this problem. In my side, it was solved and worked on ie 9.
$("input[placeholder]").each(function () {
var $this = $(this);
if($this.val() == ""){
$this.val($this.attr("placeholder")).focus(function(){
if($this.val() == $this.attr("placeholder")) {
$this.val("");
}
}).blur(function(){
if($this.val() == "") {
$this.val($this.attr("placeholder"));
}
});
}
});
I wanted an "expand/collapse" container with a plus and minus button to open and close it. This uses the standard bootstrap event and has animation. This is BS3.
<button id="button" type="button" class="btn btn-primary"
data-toggle="collapse" data-target="#demo">
<span class="glyphicon glyphicon-collapse-down"></span> Show
</button>
<div id="demo" class="collapse">
<ol class="list-group">
<li class="list-group-item">Warrior</li>
<li class="list-group-item">Adventurer</li>
<li class="list-group-item">Mage</li>
</ol>
</div>
$(function(){
$('#demo').on('hide.bs.collapse', function () {
$('#button').html('<span class="glyphicon glyphicon-collapse-down"></span> Show');
})
$('#demo').on('show.bs.collapse', function () {
$('#button').html('<span class="glyphicon glyphicon-collapse-up"></span> Hide');
})
})
If you want send ANSI color to console, get this tiny package,
What you have there will return no row at all if the user doesn't exist. Here's what you need:
SELECT CASE WHEN EXISTS (
SELECT *
FROM [User]
WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
There are several ways to do this, shown below.
As a friendly warning, be careful and up-front to the user when dealing with account, profile, and contact data. If you misuse a user's email address or other personal information, bad things can happen.
You can use AccountManager.getAccounts
or AccountManager.getAccountsByType
to get a list of all account names on the device. Fortunately, for certain account types (including com.google
), the account names are email addresses. Example snippet below.
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
...
}
}
Note that this requires the GET_ACCOUNTS
permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
More on using AccountManager
can be found at the Contact Manager sample code in the SDK.
As of Android 4.0 (Ice Cream Sandwich), you can get the user's email addresses by accessing their profile. Accessing the user profile is a bit heavyweight as it requires two permissions (more on that below), but email addresses are fairly sensitive pieces of data, so this is the price of admission.
Below is a full example that uses a CursorLoader
to retrieve profile data rows containing email addresses.
public class ExampleActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(
ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
// Potentially filter on ProfileQuery.IS_PRIMARY
cursor.moveToNext();
}
...
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
}
This requires both the READ_PROFILE
and READ_CONTACTS
permissions:
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.
You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
// results[0].geometry.location.latitude
// results[0].geometry.location.longitude
}
});
Update
Are you including the v3 javascript API?
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
</script>
for resizing my table I went with this solution in my tableview controller witch is perfectly fine:
[objectManager getObjectsAtPath:self.searchURLString
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSArray* results = [mappingResult array];
self.eventArray = results;
NSLog(@"Events number at first: %i", [self.eventArray count]);
CGRect newFrame = self.activityFeedTableView.frame;
newFrame.size.height = self.cellsHeight + 30.0;
self.activityFeedTableView.frame = newFrame;
self.cellsHeight = 0.0;
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
NSLog(@"Hit error: %@", error);
}];
The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?
I would suggest , to use .Net's IDisposable interface if your are thinking of to release instance after its usage.
See a sample implementation below.
public class Car : IDisposable
{
public void Dispose()
{
Dispose(true);
// any other managed resource cleanups you can do here
Gc.SuppressFinalize(this);
}
~Car() // finalizer
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_stream != null) _stream.Dispose(); // say you have to dispose a stream
}
_stream = null;
_disposed = true;
}
}
}
Now in your code:
void main()
{
using(var car = new Car())
{
// do something with car
} // here dispose will automtically get called.
}
i was getting error as "This driver is not configured for integrated authentication" while authenticating windows users by following jdbc string
jdbc:sqlserver://host:1433;integratedSecurity=true;domain=myDomain
So the updated connection string to make it work is as below.
jdbc:sqlserver://host:1433;authenticationScheme=NTLM;integratedSecurity=true;domain=myDomain
note: username entered was without domain.
Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.
<input [(ngModel)]="firstname" name="something">
This seems to work for me:
from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))
The trick is to wrap it in "display" as well.
The cleanest way of doing this is to iterate over all the features of the map. Markers (along with polygons, polylines, ect.) are stored in the data layer of the map.
function removeAllMarkers() {
map.data.forEach((feature) => {
feature.getGeometry().getType() === 'Point' ? map.data.remove(feature) : null
});
}
In the case that the markers are being added via drawing manager, it's best to create a global array of markers or pushing the markers into the data layer on creation like so:
google.maps.event.addListener(drawingManager, 'overlaycomplete', (e) => {
var newShape = e.overlay;
newShape.type = e.type;
if (newShape.type === 'marker') {
var pos = newShape.getPosition()
map.data.add({ geometry: new google.maps.Data.Point(pos) });
// remove from drawing layer
newShape.setMap(null);
}
});
I recommend the second approach as it allows you to use other google.maps.data class methods later.
If you want some space at left
and right
of input
view, you can add some padding like
private fun showAlertWithTextInputLayout(context: Context) {
val textInputLayout = TextInputLayout(context)
textInputLayout.setPadding(
resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
0,
resources.getDimensionPixelOffset(R.dimen.dp_19),
0
)
val input = EditText(context)
textInputLayout.hint = "Email"
textInputLayout.addView(input)
val alert = AlertDialog.Builder(context)
.setTitle("Reset Password")
.setView(textInputLayout)
.setMessage("Please enter your email address")
.setPositiveButton("Submit") { dialog, _ ->
// do some thing with input.text
dialog.cancel()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.cancel()
}.create()
alert.show()
}
dimens.xml
<dimen name="dp_19">19dp</dimen>
Hope it help
shortest one-liner solution to format seconds as hh:mm:ss: variant:
console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));_x000D_
// "2019-02-04 20:34:12"
_x000D_
You can add listener all video events nicluding ended, loadedmetadata, timeupdate
where ended
function gets called when video ends
$("#myVideo").on("ended", function() {_x000D_
//TO DO: Your code goes here..._x000D_
alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
alert("Video loaded");_x000D_
this.currentTime = 50;//50 seconds_x000D_
//TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
var cTime=this.currentTime;_x000D_
if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
alert("Video played "+cTime+" minutes");_x000D_
//TO DO: Your code goes here..._x000D_
var perc=cTime * 100 / this.duration;_x000D_
if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<video id="myVideo" controls="controls">_x000D_
<source src="your_video_file.mp4" type="video/mp4">_x000D_
<source src="your_video_file.mp4" type="video/ogg">_x000D_
Your browser does not support HTML5 video._x000D_
</video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
If you landed here looking for how to install Protocol Buffers on Mac, it can be done using Homebrew by running the command below
brew install protobuf
It installs the latest version of protobuf available. For me, at the time of writing, this installed the v3.7.1
If you'd like to install an older version, please look up the available ones from the package page Protobuf Package - Homebrew and install that specific version of the package.
The oldest available protobuf version in this package is v3.6.1.3
Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.
Map is Select
:
Enumerable.Range(1, 10).Select(x => x + 2);
Reduce is Aggregate
:
Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
Filter is Where
:
Enumerable.Range(1, 10).Where(x => x % 2 == 0);
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.
Simply edit "AXLAPIService.java" and change
url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");
to
url = new URL("file:./schema/current/AXLAPI.wsdl");
or where ever you want to store it.
You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.
One way to automatically do this is the bbox_inches='tight'
kwarg to plt.savefig
.
E.g.
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')
Another way is to use fig.tight_layout()
import matplotlib.pyplot as plt
import numpy as np
xs = np.linspace(0, 1, 20); ys = np.sin(xs)
fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)
# This should be called after all axes have been added
fig.tight_layout()
fig.savefig('test.png')
Here's a version for knockout.js
based on the accepted answer:
Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.
ko.bindingHandlers.svgConvert =
{
'init': function ()
{
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext)
{
var $img = $(element);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
$.get(imgURL, function (data)
{
// Get the SVG tag, ignore the rest
var $svg = $(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined')
{
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined')
{
$svg = $svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
}
};
Then just apply data-bind="svgConvert: true"
to your img tag.
This solution completely replaces the img
tag with a SVG and any additional bindings would not be respected.
index()
method from your controllergoto view
if this action open index.cshtml?
Your problem is the IIS pool is not have permission to access the physical path of the view.
you can test it by giving permission. for example :- go to c:\inetpub\wwwroot\yourweb
then right click on yourweb folder -> property ->security and add group name everyone and allow full control to your site . hope this fix your problem.
In your supplementary question you asked if www.example.com/file[/].html
is a valid URL.
That URL isn't valid because a URL is a type of URI and a valid URI must have a scheme like http:
(see RFC 3986).
If you meant to ask if http://www.example.com/file[/].html
is a valid URL then the answer is still no because the square bracket characters aren't valid there.
The square bracket characters are reserved for URLs in this format: http://[2001:db8:85a3::8a2e:370:7334]/foo/bar
(i.e. an IPv6 literal instead of a host name)
It's worth reading RFC 3986 carefully if you want to understand the issue fully.
If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?
The simplest explanation I can think of is that monads are a way of composing functions with embelished results (aka Kleisli composition). An "embelished" function has the signature a -> (b, smth)
where a
and b
are types (think Int
, Bool
) that might be different from each other, but not necessarily - and smth
is the "context" or the "embelishment".
This type of functions can also be written a -> m b
where m
is equivalent to the "embelishment" smth
. So these are functions that return values in context (think functions that log their actions, where smth
is the logging message; or functions that perform input\output and their results depends on the result of the IO action).
A monad is an interface ("typeclass") that makes the implementer tell it how to compose such functions. The implementer needs to define a composition function (a -> m b) -> (b -> m c) -> (a -> m c)
for any type m
that wants to implement the interface (this is the Kleisli composition).
So, if we say that we have a tuple type (Int, String)
representing results of computations on Int
s that also log their actions, with (_, String)
being the "embelishment" - the log of the action - and two functions increment :: Int -> (Int, String)
and twoTimes :: Int -> (Int, String)
we want to obtain a function incrementThenDouble :: Int -> (Int, String)
which is the composition of the two functions that also takes into account the logs.
On the given example, a monad implementation of the two functions applies to integer value 2 incrementThenDouble 2
(which is equal to twoTimes (increment 2)
) would return (6, " Adding 1. Doubling 3.")
for intermediary results increment 2
equal to (3, " Adding 1.")
and twoTimes 3
equal to (6, " Doubling 3.")
From this Kleisli composition function one can derive the usual monadic functions.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="css/index.css" rel="stylesheet" />
<script src="js/jquery-2.1.4.min.js"></script>
<script>
function copy()
{
try
{
$('#txt').select();
document.execCommand('copy');
}
catch(e)
{
alert(e);
}
}
</script>
</head>
<body>
<h4 align="center">Copy your code</h4>
<textarea id="txt" style="width:100%;height:300px;"></textarea>
<br /><br /><br />
<div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
</body>
</html>
If for a some reason can't use rsyslog, this will do:
ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"
the instanceOf
statement is often used in implementation of equals.
This is a popular pitfall !
The problem is that using instanceOf
violates the rule of symmetry:
(object1.equals(object2) == true)
if and only if (object2.equals(object1))
if the first equals is true, and object2 is an instance of a subclass of the class where obj1 belongs to, then the second equals will return false!
if the regarded class where ob1 belongs to is declared as final, then this problem can not arise, but in general, you should test as follows:
this.getClass() != otherObject.getClass();
if not, return false, otherwise test
the fields to compare for equality!
I wanted to post a real world example I just finished up:
background - I hibernate tools to generate the mappings for my database, a database I am changing as I develop. I change the database schema, push the changes and then run hibernate tools to generate the java code. All is well and good until I want to add methods to those mapped entities. If I modify the generated files, they will be overwritten every time I make a change to the database. So I extend the generated classes like this:
package com.foo.entities.custom
class User extends com.foo.entities.User{
public Integer getSomething(){
return super.getSomething();
}
public void setSomething(Integer something){
something+=1;
super.setSomething(something);
}
}
What I did above is override the existing methods on the super class with my new functionality (something+1) without ever touching the base class. Same scenario if you wrote a class a year ago and want to go to version 2 without changing your base classes (testing nightmare). hope that helps.
Use the password input type.
<input type="password" name="password" />
Here is a simple demo http://jsfiddle.net/cPaEN/
Below conf works for me:
JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME
JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"
/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"
Go to Eclipse, Click on Window from Menu bar then "Open Perspective -> other -> SVN Repository Exploring -> Click OK"
Now, after performing "Click OK" you need to go to truck (or place where your project is saved in SVN) then select project(which you want to Delete) then right click -> Delete.
This Will Delete project from subversion.
Reduce makes this fairly easy:
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
Here's a fully example using some mock data:
set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
# x a b y
#12 12 NA 18 NA
#13 13 NA 19 NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352
And here's an example using these data to replicate my.list
:
merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]
# matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1 ALGIERE 200 RI 026 S NA <NA> NA NA NA NA <NA>
#2 ALVES 100 RI 019 S NA <NA> NA NA NA NA <NA>
#3 BADEAU 100 RI 032 S NA <NA> NA NA NA NA <NA>
Note: It looks like this is arguably a bug in merge
. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame
which does make.unique
the names, causing the rbind
to fail.
# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y senate1995 name votes.year
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.
Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge
. Eg:
my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))
The merge
/Reduce
will then work fine.
[[
has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do
[[ -e $b ]]
to test whether a file exists. But with [
, you have to quote $b
, because it splits the argument and expands things like "a*"
(where [[
takes it literally). That has also to do with how [
can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).
[[
also has some other nice features, like regular expression matching with =~
along with operators like they are known in C-like languages. Here is a good page about it: What is the difference between test, [
and [[
? and Bash Tests
Sometimes there are source files which are missing from your target.
You can select the files that seem to be "missing" and check in the right-hand utility bar that their checkboxes are selected for the Target you are building.
Just use Date.parse()
which returns a Number, then use new Date()
to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
Least code would be:
>>> s = set([1, 2, 3])
>>> list(s)[0]
1
Obviously this would create a new list which contains each member of the set, so not great if your set is very large.
4 GB minus what is in use by the system if you link with /LARGEADDRESSAWARE.
Of course, you should be even more careful with pointer arithmetic if you set that flag.
A simple way to do so is to add the below code (for Seaborn):
for p in splot.patches:
splot.annotate(format(p.get_height(), '.1f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 9),
textcoords = 'offset points')
Example :
splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
splot.annotate(format(p.get_height(), '.1f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 9),
textcoords = 'offset points')
plt.show()
Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.
var path = require('path'),
fs = require('fs');
/**
* Find all files recursively in specific folder with specific extension, e.g:
* findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
* @param {String} startPath Path relative to this file or other file which requires this files
* @param {String} filter Extension name, e.g: '.html'
* @return {Array} Result files with path string in an array
*/
function findFilesInDir(startPath,filter){
var results = [];
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
results = results.concat(findFilesInDir(filename,filter)); //recurse
}
else if (filename.indexOf(filter)>=0) {
console.log('-- found: ',filename);
results.push(filename);
}
}
return results;
}
module.exports = findFilesInDir;
That's simple, in Java
your_component.setRotation(15);
or
your_component.setRotation(295.18f);
in XML
<Button android:rotation="15" />
You can use Model.query
, because the Model
(or usually its base class, especially in cases where declarative extension is used) is assigned Sesssion.query_property
. In this case the Model.query
is equivalent to Session.query(Model)
.
I am not aware of the way to modify the columns returned by the query (except by adding more using add_columns()
).
So your best shot is to use the Session.query(Model.col1, Model.col2, ...)
(as already shown by Salil).
From wechat api doc:
curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
If you're using Visual Studio you need to modify the project property: Configuration Properties -> Linker -> System -> SubSystem.
This should be set to: Console (/SUBSYSTEM:CONSOLE)
Also you should change your WinMain to be this signature:
int main(int argc, char **argv)
{
//...
return 0;
}
That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.
Disable ASLR:
sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'
Disable canaries:
gcc overflow.c -o overflow -fno-stack-protector
After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit
Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.
Now go and clobber that EIP!
All of the answers above break expected browser behavior. What most people want is something that will scroll to the top if it's a "new" page, but return to the previous position if you're getting there through the Back (or Forward) button.
If you assume HTML5 mode, this turns out to be easy (although I'm sure some bright folks out there can figure out how to make this more elegant!):
// Called when browser back/forward used
window.onpopstate = function() {
$timeout.cancel(doc_scrolling);
};
// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
doc_scrolling = $timeout( scroll_top, 50 );
// Moves entire browser window to top
scroll_top = function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
The way it works is that the router assumes it is going to scroll to the top, but delays a bit to give the browser a chance to finish up. If the browser then notifies us that the change was due to a Back/Forward navigation, it cancels the timeout, and the scroll never occurs.
I used raw document
commands to scroll because I want to move to the entire top of the window. If you just want your ui-view
to scroll, then set autoscroll="my_var"
where you control my_var
using the techniques above. But I think most people will want to scroll the entire page if you are going to the page as "new".
The above uses ui-router, though you could use ng-route instead by swapping $routeChangeSuccess
for$stateChangeSuccess
.
Maybe a late response but there is a package to handle this https://github.com/ACFBentveld/Await
var myObject = { // or your array
1 : 'My first item',
2 : 'My second item',
3 : 'My third item'
}
Await.each(myObject, function(key, value){
//your logic here
});
Await.done(function(){
console.log('The loop is completely done');
});
Using a regular expression you can count the number of lines as
str.split(/\r\n|\r|\n/).length
Alternately you can try split method as below.
var lines = $("#ptest").val().split("\n");
alert(lines.length);
working solution: http://jsfiddle.net/C8CaX/
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
The supercalifragilisticexpialidocious answer is:
add this at the top of your js file or script tag
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
document.body.scrollTop = 0; // For Safari
If you deal with .xlsm
file instead of .xls
you can use the old method. I was trying to modify vbaProject.bin
in .xlsm
several times using DBP->DBx
method by it didn't work, also changing value of DBP
didn't. So I was very suprised that following worked :
1. Save .xlsm
as .xls
.
2. Use DBP->DBx
method on .xls
.
3. Unfortunately some erros may occur when using modified .xls
file, I had to save .xls
as .xlsx
and add modules, then save as .xlsm
.
For adding some more information, your example will work without the @
symbol (it prevents escaping with \), this way:
string foo = "this \"word\" is escaped!";
It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).
Bootstrap 3
Here is a working left sidebar example:
http://bootply.com/90936 (similar to the Bootstrap docs)
The trick is using the affix
component along with some CSS to position it:
#sidebar.affix-top {
position: static;
margin-top:30px;
width:228px;
}
#sidebar.affix {
position: fixed;
top:70px;
width:228px;
}
EDIT- Another example with footer and affix-bottom
Bootstrap 4
The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top
class is explained in this answer.
Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?
I had the same problem. I made a simple UIView category that fixes that.
.h
#import <UIKit/UIKit.h>
@interface UIView (GCLibrary)
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@end
.m
#import "UIView+GCLibrary.h"
@implementation UIView (GCLibrary)
- (CGFloat) height {
return self.frame.size.height;
}
- (CGFloat) width {
return self.frame.size.width;
}
- (CGFloat) x {
return self.frame.origin.x;
}
- (CGFloat) y {
return self.frame.origin.y;
}
- (CGFloat) centerY {
return self.center.y;
}
- (CGFloat) centerX {
return self.center.x;
}
- (void) setHeight:(CGFloat) newHeight {
CGRect frame = self.frame;
frame.size.height = newHeight;
self.frame = frame;
}
- (void) setWidth:(CGFloat) newWidth {
CGRect frame = self.frame;
frame.size.width = newWidth;
self.frame = frame;
}
- (void) setX:(CGFloat) newX {
CGRect frame = self.frame;
frame.origin.x = newX;
self.frame = frame;
}
- (void) setY:(CGFloat) newY {
CGRect frame = self.frame;
frame.origin.y = newY;
self.frame = frame;
}
@end
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
You have an incompatibility between the version of ASM required by Hibernate (asm-1.5.3.jar) and the one required by Spring. But, actually, I wonder why you have asm-2.2.3.jar on your classpath (ASM is bundled in spring.jar and spring-core.jar to avoid such problems AFAIK). See HHH-2222.
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs
.
To determine if an argument was passed at all, I use a custom utility object as the default value:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
For ASP.NET pages I am using the following
BEFORE
<script src="/Scripts/pages/common.js" type="text/javascript"></script>
AFTER (force reload)
<script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>
Adding the DateTime.Now.Ticks works very well.
Horizontal centering is as easy as:
text-align: center
Vertical centering when the container is a known height:
height: 100px;
line-height: 100px;
vertical-align: middle
Vertical centering when the container isn't a known height AND you can set the image in the background:
background: url(someimage) no-repeat center center;
another method to find Instance name- Right clck on Database name and select Properties, in this part you can see view connection properties in left down corner, click that then you can see the Instance name.
Taken from spring's tutorial
mockMvc.perform(get("/" + userName + "/bookmarks/"
+ this.bookmarkList.get(0).getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.bookmarkList.get(0).getId().intValue())))
.andExpect(jsonPath("$.uri", is("http://bookmark.com/1/" + userName)))
.andExpect(jsonPath("$.description", is("A description")));
is
is available from import static org.hamcrest.Matchers.*;
jsonPath
is available from import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
and jsonPath
reference can be found here
You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List
I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary
public settings()
{
this.X = defaultForX;
this.Y = defaultForY;
// repeat ...
}
public void Parse(Uri uri)
{
// parse values from query string.
// if you need to distinguish from default vs. specified, add an appropriate property
}
This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.
SELECT *
FROM A.tableA JOIN B.tableB
or
SELECT *
FROM A.tableA JOIN B.tableB
ON A.tableA.id = B.tableB.a_id;
You could filter the file through cat -n
before piping to less
:
cat -n file.txt | less
Or, if your version of less
supports it, the -N
option:
less -N file.txt
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
google.com is not responding to HTTP HEAD
requests, which is why you are seeing a hang for the first command.
It does respond to GET
requests, which is why the third command works.
As for the second, curl just prints the headers from a standard request.
You could use CAST or CONVERT:
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
Thank you very much! Finally I solved the blurred pixels problem with this code:
<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>
With the addition of the 'half-pixel' does the trick to unblur lines.
The generic method for this is fairly simple:
public static String convertSecondsToHMmSs(long seconds) {
long s = seconds % 60;
long m = (seconds / 60) % 60;
long h = (seconds / (60 * 60)) % 24;
return String.format("%d:%02d:%02d", h,m,s);
}
You can add one
public static boolean isNullOrBlank(String param) {
return param == null || param.trim().length() == 0;
}
I have
public static boolean isSet(String param) {
// doesn't ignore spaces, but does save an object creation.
return param != null && param.length() != 0;
}
If you want to send data using jQuery Ajax then there is no need of form tag and submit button
Example:
<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
If you have control over the HTML then you could add a real element instead of a pseudo one. :before and :after pseudo elements are rendered right after the open tag or right before the close tag. The inline equivalent for this css
td { text-align: justify; }
td:after { content: ""; display: inline-block; width: 100%; }
Would be something like this:
<table>
<tr>
<td style="text-align: justify;">
TD Content
<span class="inline_td_after" style="display: inline-block; width: 100%;"></span>
</td>
</tr>
</table>
Keep in mind; Your "real" before and after elements and anything with inline css will greatly increase the size of your pages and ignore page load optimizations that external css and pseudo elements make possible.
there is no timeout, by default.
SELECT *
FROM sys.all_sql_modules
WHERE definition LIKE '%CreatedDate%'
window.location.href = window.location.href
The views are probably created using the WITH SCHEMABINDING option and this means they are explicitly wired up to prevent such changes. Looks like the schemabinding worked and prevented you from breaking those views, lucky day, heh? Contact your database administrator and ask him to do the change, after it asserts the impact on the database.
From MSDN:
SCHEMABINDING
Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified.
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
I would like to suggest new EmailAddressAttribute().IsValid(emailTxt)
for additional validation before/after validating using RegEx
Remember EmailAddressAttribute
is part of System.ComponentModel.DataAnnotations namespace
.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
I wanted to provide a solution based on the answer of @kopelitsa. The main differences being:
HandlerExceptionResolver
.First, you need to make sure, that you have a class that handles exceptions occurring in a regular RestController/Controller (a class annotated with @RestControllerAdvice
or @ControllerAdvice
and method(s) annotated with @ExceptionHandler
). This handles your exceptions occurring in a controller. Here is an example using the RestControllerAdvice:
@RestControllerAdvice
public class ExceptionTranslator {
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorDTO processRuntimeException(RuntimeException e) {
return createErrorDTO(HttpStatus.INTERNAL_SERVER_ERROR, "An internal server error occurred.", e);
}
private ErrorDTO createErrorDTO(HttpStatus status, String message, Exception e) {
(...)
}
}
To reuse this behavior in the Spring Security filter chain, you need to define a Filter and hook it into your security configuration. The filter needs to redirect the exception to the above defined exception handling. Here is an example:
@Component
public class FilterChainExceptionHandler extends OncePerRequestFilter {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.error("Spring Security Filter Chain Exception:", e);
resolver.resolveException(request, response, null, e);
}
}
}
The created filter then needs to be added to the SecurityConfiguration. You need to hook it into the chain very early, because all preceding filter's exceptions won't be caught. In my case, it was reasonable to add it before the LogoutFilter
. See the default filter chain and its order in the official docs. Here is an example:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private FilterChainExceptionHandler filterChainExceptionHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(filterChainExceptionHandler, LogoutFilter.class)
(...)
}
}
I decided to add a condition to the Where
Clause that always evaluates true but allows the coder to find your comment.
Select
...
From
...
Where
....
And "Comment: FYI, Access doesn't support normal comments!"<>""
The last line always evaluates to true so it doesn't affect the data returned but allows you to leave a comment for the next guy.
use DIRECTORY option.
Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907
DIRECTORY
Default: DATA_PUMP_DIR
Purpose
Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.
Syntax and Description
DIRECTORY=directory_object
The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.
A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.
Example
The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".
> impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp
LOGFILE=dpump_dir2:expfull.log
This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.
assertTrue("your message", previousTokenValues[1].compareTo(currentTokenValues[1]) > 0)
this passes for previous > current values
You can also add items in code:
cboWhatever.Items.Add("SomeItem");
Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:
Key Value Pair Combobox in WPF
Sum-up code would be something like this:
ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));
//MARK:
does not seem to work for me in Xcode 6.3.2. However, this is what I did to get it to work:
1) Code:
import Cocoa
class MainWindowController: NSWindowController {
//MARK: - My cool methods
func fly() {
}
func turnInvisible() {
}
}
2) In the jump bar
nothing appears to change when adding the //MARK
: comment. However, if I click on the rightmost name in the jump bar, in my case it says MainWindowController(with a leading C icon)
, then a popup window will display showing the effects of the //MARK: comment, namely a heading that says "My cool methods":
3) I also notice that if I click on one of the methods in my code, then the method becomes the rightmost entry in the jump bar. In order to get MainWindowController(with a leading C icon)
to be the rightmost entry in the jump bar, I have to click on the whitespace above my methods.
For Python 3:
from collections import ChainMap
a = {"a":1, "b":2}
b = {"c":5, "d":8}
dict(ChainMap(a, b)) # {"a":1, "b":2, "c":5, "d":8}
If you have the same key in both dictionaries, ChainMap
will use the first key's value and ignores the second key's value.
Cheers!
The best way is sudo apt-get install ruby-compass
to install compass.
Adding another use case where I found this happening. I was using a ADF Fusion application and the column type being used was a varchar2(4000) which could not accommodate the text and hence this error.
This might work:
mkdir {{FOLDER NAME}}
cd {{FOLDER NAME}}
touch {{FOLDER NAME}}/file.txt
You could also change your PYTHONPATH:
$ python -c 'import dateutil'
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named dateutil
$
$ PYTHONPATH="/usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg":"${PYTHONPATH}"
$ export PYTHONPATH
$ python -c 'import dateutil'
$
Where /usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg
is the place dateutil was installed in my box (centos using sudo yum install python-dateutil15
)
Well as we all know that it gets erased. But it can be known under some circumstances where the type is explicitly mentioned in the class hierarchy:
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public abstract class CaptureType<T> {
/**
* {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
*
* @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
*/
public Type getTypeParam() {
Class<?> bottom = getClass();
Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();
for (; ; ) {
Type genericSuper = bottom.getGenericSuperclass();
if (!(genericSuper instanceof Class)) {
ParameterizedType generic = (ParameterizedType) genericSuper;
Class<?> actualClaz = (Class<?>) generic.getRawType();
TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
Type[] reified = generic.getActualTypeArguments();
assert (typeParameters.length != 0);
for (int i = 0; i < typeParameters.length; i++) {
reifyMap.put(typeParameters[i], reified[i]);
}
}
if (bottom.getSuperclass().equals(CaptureType.class)) {
bottom = bottom.getSuperclass();
break;
}
bottom = bottom.getSuperclass();
}
TypeVariable<?> var = bottom.getTypeParameters()[0];
while (true) {
Type type = reifyMap.get(var);
if (type instanceof TypeVariable) {
var = (TypeVariable<?>) type;
} else {
return type;
}
}
}
/**
* Returns the raw type of the generic type.
* <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
* For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
*
* @return Class object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
* @see com.types.CaptureType
*/
public Class<T> getRawType() {
Type typeParam = getTypeParam();
if (typeParam != null)
return getClass(typeParam);
else throw new RuntimeException("Could not obtain type information");
}
/**
* Gets the {@link java.lang.Class} object of the argument type.
* <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
*
* @param type The type
* @param <A> type of class object expected
* @return The Class<A> object of the type
* @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
*/
public static <A> Class<A> getClass(Type type) {
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return (Class<A>) Array.newInstance(componentClass, 0).getClass();
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
} else if (type instanceof Class) {
Class claz = (Class) type;
return claz;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof TypeVariable) {
throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
}
/**
* This method is the preferred method of usage in case of complex generic types.
* <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
*
* @return TypeADT object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
*/
public TypeADT getParamADT() {
return recursiveADT(getTypeParam());
}
private TypeADT recursiveADT(Type type) {
if (type instanceof Class) {
return new TypeADT((Class<?>) type, null);
} else if (type instanceof ParameterizedType) {
ArrayList<TypeADT> generic = new ArrayList<>();
ParameterizedType type1 = (ParameterizedType) type;
return new TypeADT((Class<?>) type1.getRawType(),
Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
} else throw new UnsupportedOperationException();
}
}
public class TypeADT {
private final Class<?> reify;
private final List<TypeADT> parametrized;
TypeADT(Class<?> reify, List<TypeADT> parametrized) {
this.reify = reify;
this.parametrized = parametrized;
}
public Class<?> getRawType() {
return reify;
}
public List<TypeADT> getParameters() {
return parametrized;
}
}
And now you can do things like:
static void test1() {
CaptureType<String> t1 = new CaptureType<String>() {
};
equals(t1.getRawType(), String.class);
}
static void test2() {
CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
};
equals(t1.getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
}
private static void test3() {
CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
};
equals(t1.getParamADT().getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
}
static class Test4 extends CaptureType<List<String>> {
}
static void test4() {
Test4 test4 = new Test4();
equals(test4.getParamADT().getRawType(), List.class);
}
static class PreTest5<S> extends CaptureType<Integer> {
}
static class Test5 extends PreTest5<Integer> {
}
static void test5() {
Test5 test5 = new Test5();
equals(test5.getTypeParam(), Integer.class);
}
static class PreTest6<S> extends CaptureType<S> {
}
static class Test6 extends PreTest6<Integer> {
}
static void test6() {
Test6 test6 = new Test6();
equals(test6.getTypeParam(), Integer.class);
}
class X<T> extends CaptureType<T> {
}
class Y<A, B> extends X<B> {
}
class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
}
void test7(){
Z<String> z = new Z<>();
TypeADT param = z.getParamADT();
equals(param.getRawType(), Map.class);
List<TypeADT> parameters = param.getParameters();
equals(parameters.get(0).getRawType(), Integer.class);
equals(parameters.get(1).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
}
static void test8() throws IllegalAccessException, InstantiationException {
CaptureType<int[]> type = new CaptureType<int[]>() {
};
equals(type.getRawType(), int[].class);
}
static void test9(){
CaptureType<String[]> type = new CaptureType<String[]>() {
};
equals(type.getRawType(), String[].class);
}
static class SomeClass<T> extends CaptureType<T>{}
static void test10(){
SomeClass<String> claz = new SomeClass<>();
try{
claz.getRawType();
throw new RuntimeException("Shouldnt come here");
}catch (RuntimeException ex){
}
}
static void equals(Object a, Object b) {
if (!a.equals(b)) {
throw new RuntimeException("Test failed. " + a + " != " + b);
}
}
More info here. But again, it is almost impossible to retrieve for:
class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();
where it gets erased.
Try this general approach:
import re
my_string="hello python world , i'm a beginner "
p = re.compile("world(.*)")
print (p.findall(my_string))
#[" , i'm a beginner "]
A few points I find useful when applying this to my own plots:
fig.suptitle(title)
rather than plt.suptitle(title)
fig.tight_layout()
the title must be shifted with fig.subplots_adjust(top=0.88)
Example code taken from subplots demo in matplotlib docs and adjusted with a master title.
import matplotlib.pyplot as plt
import numpy as np
# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')
# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)
# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)
plt.show()
Try using sendmail instead of smtp driver (according to these recommendations: http://code.tutsplus.com/tutorials/sending-emails-with-laravel-4-gmail--net-36105)
MAIL_DRIVER=sendmail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=apppassword
MAIL_ENCRYPTION=tls
In case you want to check if multiple env variables are not set, you can do the following:
import os
MANDATORY_ENV_VARS = ["FOO", "BAR"]
for var in MANDATORY_ENV_VARS:
if var not in os.environ:
raise EnvironmentError("Failed because {} is not set.".format(var))
This solved the issue:
remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)
The distance between two geo-coordinates can be found by using Haversine formula . This formula is effective to calculate distance in a spherical body i.e earth in our case.
Faced the same issue on Spring MVC 5 + Tomcat 9 + JSP.
After the long research, came to an elegant solution (no need filters and no need changes in the Tomcat server.xml (starting from 8.0.0-RC3 version))
In the WebMvcConfigurer implementation set default encoding for messageSource (for reading data from messages source files in the UTF-8 encoding.
@Configuration
@EnableWebMvc
@ComponentScan("{package.with.components}")
public class WebApplicationContextConfig implements WebMvcConfigurer {
@Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
/* other beans and methods */
}
In the DispatcherServletInitializer implementation @Override the onStartup method and set request and resource character encoding in it.
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
// https://wiki.apache.org/tomcat/FAQ/CharacterEncoding
servletContext.setRequestCharacterEncoding("UTF-8");
servletContext.setResponseCharacterEncoding("UTF-8");
super.onStartup(servletContext);
}
/* servlet mappings, root and web application configs, other methods */
}
Save all message source and view files in UTF-8 encoding.
Add <%@ page contentType="text/html;charset=UTF-8" %> or <%@ page pageEncoding="UTF-8" %> in each *.jsp file or add jsp-config descriptor to web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>AppName</display-name>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line
import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')
Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64
, and then isnan
check should work
This is html part
<a href="{{route('download',$details->report_id)}}" type="button" class="btn btn-primary download" data-report_id="{{$details->report_id}}" >Download</a>
This is Route :
Route::get('/download/{id}', 'users\UserController@getDownload')->name('download')->middleware('auth');
This is function :
public function getDownload(Request $request,$id)
{
$file= public_path(). "/pdf/"; //path of your directory
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file.$pdfName, 'filename.pdf', $headers);
}
I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:
Get-Date (Get-Date).AddDays(-1) -format D
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
As the answer said above, CSS PIE makes things like border-radius and box-shadow work in IE6-IE8: http://css3pie.com/
That said I have still found things to be somewhat flaky when using PIE and now just accept that people using older browsers aren't going to see rounded corners and dropshadows.
My preference.
lineIter= iter(aFile)
for line in lineIter:
if line.startswith( ">" ):
someVaryingText= line
break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
if len(line.strip()) == 0:
break
acids.append( line )
At this point you have someVaryingText as a string, and the acids as a list of strings.
You can do "".join( acids )
to make a single string.
I find this less frustrating (and more flexible) than multiline regexes.
Try using this:
$(".move_to").on("click", function(e){
e.preventDefault();
$('#contactsForm').attr('action', "/test1").submit();
});
Moving the order in which you use .preventDefault()
might fix your issue. You also didn't use function(e)
so e.preventDefault();
wasn't working.
Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined
. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1
.
@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:
Starting state: you are on branch X
, and you want to cherry-pick the commits Y..Z
.
git checkout -b tempZ Z
git rebase Y
git checkout -b newX X
git cherry-pick Y..tempZ
git branch -D tempZ
What this does is to create a branch tempZ
based on Z
, but with the history from Y
onward linearized, and then cherry-pick that onto a copy of X
called newX
. (It's safer to do this on a new branch rather than to mutate X
.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick
works very much like rebase
in that respect). Finally it deletes the temporary tempZ
branch.
If step 2 gives the message "Current branch tempZ is up to date", then Y..Z
was already linear, so just ignore that message and proceed with steps 3 onward.
Then review newX
and see whether that did what you wanted.
(Note: this is not the same as a simple git rebase X
when on branch Z
, because it doesn't depend in any way on the relationship between X
and Y
; there may be commits between the common ancestor and Y
that you didn't want.)
You can solve your issue by using the 'contains' function within your Xpath query, as below:
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes("//*[contains(@class,'float')]")
To reuse this in a function do something similar to the following:
string classToFind = "float";
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", classToFind));
String active_network = ((ConnectivityManager)
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo().getSubtypeName();
should get you the network name
Have not tested it yet, but the looks are better than the one Alex mentions.
The description at winginx.com/en/htaccess says:
About the htaccess to nginx converter
The service is to convert an Apache's .htaccess to nginx configuration instructions.
First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.
Note server instructions (e.g. php_value, etc.) are ignored.
The converter does not check syntax, including regular expressions and logic errors.
Please, check the result manually before use.
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}
You can use css float
<div style='float: left;'><a href="login.php">Log in</a></div>
<div style='float: right;'><a href="home.php">Back to Home</a></div>
Have a look at this CSS Positioning
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which
/event.keyCode
and start using event.key
:
if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")
I recommended using SingleThread because you do not have to kill it after using. Also, "stop()" method is deprecated in Kotlin language.
private fun mDoThisJob(){
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
//TODO: You can write your periodical job here..!
}, 1, 1, TimeUnit.SECONDS)
}
Moreover, you can use it for periodical job. It is very useful. If you would like to do job for each second, you can set because parameters of it:
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
TimeUnit values are: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS.
@canerkaseler
Separate it into 2 triggers. One for the deletion and one for the insertion\ update.
It's simply pointless to create variable variable names. Why?
exec
or globals()
exec/globals()
againUsing a list is much easier:
# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
print string
print string[6] # or pick any of them
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
Calling async
code from synchronous code can be quite tricky.
I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await
and used to resume the method.
So if this is called in an UI context, when the await
completes, the async
method tries to re-enter that context to continue executing. Unfortunately, code using Wait
(or Result
) will block a thread in that context, so the async
method cannot complete.
The guidelines to avoid this are:
ConfigureAwait(continueOnCapturedContext: false)
as much as possible. This enables your async
methods to continue executing without having to re-enter the context.async
all the way. Use await
instead of Result
or Wait
.If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
Change the database.php file from
$db['default']['dbdriver'] = 'mysql';
to
$db['default']['dbdriver'] = 'mysqli';
Eclipse has no impact on Mac OS beyond it directory, so there is no problem uninstalling.
I think that What you are facing is the result of Eclipse switching the plugin distribution system recently. There are now two redundant and not very compatible means of installing plugins. It's a complete mess. You may be better off (if possible) installing a more recent version of Eclipse (maybe even the 3.5 milestones) as they seem to be more stable in that regard.
You will use props in your child component
for example
if your now component props is
{
booking: 4,
isDisable: false
}
you can use this props in your child compoenet
<div {...this.props}> ... </div>
in you child component, you will receive all your parent props.
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
This is 100% working:
Thats it, hope it helps
I suggest IGNITION this is even better than Droid fu
https://github.com/kaeppler/ignition
https://github.com/kaeppler/ignition/wiki/Sample-applications
I don't think it provides a multi-hop wireless packet routing environment. However you can try to integrate a simple routing mechanism. Just check out Wi-Share to get an idea how it can be done.
Yes, you can. But if you have non-unique entries on your table, it will fail. Here is the how to add unique constraint on your table. If you're using PostgreSQL 9.x you can follow below instruction.
CREATE UNIQUE INDEX constraint_name ON table_name (columns);
On python command line, first import that module for which you need location.
import module_name
Then type:
print(module_name.__file__)
For example to find out "pygal" location:
import pygal
print(pygal.__file__)
Output:
/anaconda3/lib/python3.7/site-packages/pygal/__init__.py
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
Problem Cause : The process of the current program is still running without interuption. (This is the reason why you haven't got this issue after a restart)
The fix is simple : Go to cmd and type the command taskkill -im process-name.exe -f
Eg:
taskkill -im demo.exe -f
here,
demo - is my program name
TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON
object. This contains the following methods:
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string.JSON.stringify()
method converts a JavaScript object or value to a JSON string.Example:
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
Try parent_window.maxsize(x,x);
to set the maximum size. It shouldn't get larger even if you set the background, etc.
Edit: use parent_window.minsize(x,x)
also to set it to a constant size!
The R
graphics
package has the function axTicks
that returns the tick locations of the ticks that the axis
and plot
functions would set automatically. The other answers given to this question define the tick locations manually which might not be convenient in some situations.
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
A minimal example would be
plot(10^(0:10), 0:10, log = 'x', xaxt = 'n')
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
There is also an log
parameter in the axTicks
function but in this situation it does not need to be set to get the proper logarithmic axis tick location.
To resolve the issue on a Debian/Ubuntu system modify the /etc/apache2/ports.conf
settings file by adding NameVirtualHost *:443
to it. My ports.conf
is the following at the moment:
# /etc/apache/ports.conf
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default
# This is also true if you have upgraded from before 2.2.9-3 (i.e. from
# Debian etch). See /usr/share/doc/apache2.2-common/NEWS.Debian.gz and
# README.Debian.gz
NameVirtualHost *:80
Listen 80
<IfModule mod_ssl.c>
# If you add NameVirtualHost *:443 here, you will also have to change
# the VirtualHost statement in /etc/apache2/sites-available/default-ssl
# to <VirtualHost *:443>
# Server Name Indication for SSL named virtual hosts is currently not
# supported by MSIE on Windows XP.
NameVirtualHost *:443
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
NameVirtualHost *:443
Listen 443
</IfModule>
Furthermore ensure that 'sites-available/default-ssl' is not enabled, type a2dissite default-ssl
to disable the site. While you're at it type a2dissite
by itself to get a list and see if there is any other site settings that you have enabled that might be mapping onto port 443.
Here's another way using Visual Studio: If you do New Item in Visual Studio and you select Web Form, it will create a standalone *.aspx web form, which is what you have for your current web form (is this what you did?). You need to select Web Content Form and then select the master page you want attached to it.
What actually helped me was to turn off the Resharper build and to use the VisualStudio Re-Build option on my project.
I had to include double quotes with the table name.
db=> \d
List of relations
Schema | Name | Type | Owner
--------+-----------------------------------------------+-------+-------
public | COMMONDATA_NWCG_AGENCIES | table | dan
...
db=> \d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".
???
Double quotes:
db=> \d "COMMONDATA_NWCG_AGENCIES"
Table "public.COMMONDATA_NWCG_AGENCIES"
Column | Type | Collation | Nullable | Default
--------------------------+-----------------------------+-----------+----------+---------
ID | integer | | not null |
...
Lots and lots of double quotes:
db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR: relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR: column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
ID
----
1
(1 row)
This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:
DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";
CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...
You should use something like this pg_dump --schema=your_schema_name db1
, for details take a look here