I had the same problem. So I took the source code of java.util.TreeMap and wrote IndexedTreeMap. It implements my own IndexedNavigableMap:
public interface IndexedNavigableMap<K, V> extends NavigableMap<K, V> {
K exactKey(int index);
Entry<K, V> exactEntry(int index);
int keyIndex(K k);
}
The implementation is based on updating node weights in the red-black tree when it is changed. Weight is the number of child nodes beneath a given node, plus one - self. For example when a tree is rotated to the left:
private void rotateLeft(Entry<K, V> p) {
if (p != null) {
Entry<K, V> r = p.right;
int delta = getWeight(r.left) - getWeight(p.right);
p.right = r.left;
p.updateWeight(delta);
if (r.left != null) {
r.left.parent = p;
}
r.parent = p.parent;
if (p.parent == null) {
root = r;
} else if (p.parent.left == p) {
delta = getWeight(r) - getWeight(p.parent.left);
p.parent.left = r;
p.parent.updateWeight(delta);
} else {
delta = getWeight(r) - getWeight(p.parent.right);
p.parent.right = r;
p.parent.updateWeight(delta);
}
delta = getWeight(p) - getWeight(r.left);
r.left = p;
r.updateWeight(delta);
p.parent = r;
}
}
updateWeight simply updates weights up to the root:
void updateWeight(int delta) {
weight += delta;
Entry<K, V> p = parent;
while (p != null) {
p.weight += delta;
p = p.parent;
}
}
And when we need to find the element by index here is the implementation that uses weights:
public K exactKey(int index) {
if (index < 0 || index > size() - 1) {
throw new ArrayIndexOutOfBoundsException();
}
return getExactKey(root, index);
}
private K getExactKey(Entry<K, V> e, int index) {
if (e.left == null && index == 0) {
return e.key;
}
if (e.left == null && e.right == null) {
return e.key;
}
if (e.left != null && e.left.weight > index) {
return getExactKey(e.left, index);
}
if (e.left != null && e.left.weight == index) {
return e.key;
}
return getExactKey(e.right, index - (e.left == null ? 0 : e.left.weight) - 1);
}
Also comes in very handy finding the index of a key:
public int keyIndex(K key) {
if (key == null) {
throw new NullPointerException();
}
Entry<K, V> e = getEntry(key);
if (e == null) {
throw new NullPointerException();
}
if (e == root) {
return getWeight(e) - getWeight(e.right) - 1;//index to return
}
int index = 0;
int cmp;
index += getWeight(e.left);
Entry<K, V> p = e.parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
while (p != null) {
cmp = cpr.compare(key, p.key);
if (cmp > 0) {
index += getWeight(p.left) + 1;
}
p = p.parent;
}
} else {
Comparable<? super K> k = (Comparable<? super K>) key;
while (p != null) {
if (k.compareTo(p.key) > 0) {
index += getWeight(p.left) + 1;
}
p = p.parent;
}
}
return index;
}
You can find the result of this work at http://code.google.com/p/indexed-tree-map/
TreeSet/TreeMap (as well as their indexed counterparts from the indexed-tree-map project) do not allow duplicate keys , you can use 1 key for an array of values. If you need a SortedSet with duplicates use TreeMap with values as arrays. I would do that.
I created a PyPI module for this reason:
pip install screeninfo
The code:
from screeninfo import get_monitors
for m in get_monitors():
print(str(m))
Result:
monitor(1920x1080+1920+0)
monitor(1920x1080+0+0)
It supports multi monitor environments. Its goal is to be cross platform; for now it supports Cygwin and X11 but pull requests are totally welcome.
Edit December 2018: Apple seem to have finally added a button for removing the app in certain situations, including apps that never went on sale (thanks to @iwill for pointing that out), basically making the below answer irrelevant.
Edit: turns out the deleted apps still appear in Xcode -> Organizer -> Archives and there is no way to delete them from there even if there are no archives! So more looks like a fake delete of sorts.
Currently (Edit: as of July 2016) there is no way of deleting your app if it never went on sale.
However, all information except for SKU can be edited and thus reused for a new app, including the app name, Bundle ID, icon, etc etc. Because SKU can be anything (some people say they use numbers 1, 2, 3 for example) then it shouldn't be a big deal to use something unrelated for your new app.
(Honestly though I'm hoping Apple will fix this soon. I almost hear some Apple devs finding excuses for not implementing it (you know, it will break the database and will kill innocent pandas) and some managers telling the devs to just frigging do it regardless.)
Follow the above image to edit rows from 200 to 100,000 Rows
The answer by @ajcr explains how the dot
and matmul
(invoked by the @
symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.
To clarify the differences take a 4x4 array and return the dot
product and matmul
product with a 3x4x2 'stack of matricies' or tensor.
import numpy as np
fourbyfour = np.array([
[1,2,3,4],
[3,2,1,4],
[5,4,6,7],
[11,12,13,14]
])
threebyfourbytwo = np.array([
[[2,3],[11,9],[32,21],[28,17]],
[[2,3],[1,9],[3,21],[28,7]],
[[2,3],[1,9],[3,21],[28,7]],
])
print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))
The products of each operation appear below. Notice how the dot product is,
...a sum product over the last axis of a and the second-to-last of b
and how the matrix product is formed by broadcasting the matrix together.
4x4*3x4x2 dot:
[[[232 152]
[125 112]
[125 112]]
[[172 116]
[123 76]
[123 76]]
[[442 296]
[228 226]
[228 226]]
[[962 652]
[465 512]
[465 512]]]
4x4*3x4x2 matmul:
[[[232 152]
[172 116]
[442 296]
[962 652]]
[[125 112]
[123 76]
[228 226]
[465 512]]
[[125 112]
[123 76]
[228 226]
[465 512]]]
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
From what you printed, it seems var2
is an array containing one string. Or actually, it appears to hold the result of running .inspect
on an array containing one string. It would be helpful to show how you are initializing them.
irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]
In your controller use:
var path = HttpContext.Server.MapPath("~/Data/data.html");
This allows you to test the controller with Moq like so:
var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;
Finally found in http://viralpatel.net/blogs/2009/09/setting-height-selectbox-combobox-ie.html a simple solution (at least for IE8):
font-size: 1.0em;
BTW, for Google Chrome, found this workaround at How to standardize the height of a select box between Chrome and Firefox? */
-webkit-appearance: menulist-button;
I am using both in my app.
Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.
I created two fragments in the same activity and called the same time with two same kind of URLs.
09-23 20:12:32.830 16002-16002/com.urbanpro.seeker E/RETROFIT? RestAdapter Init
09-23 20:12:32.833 16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837 16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860 16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537 16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553 16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends
If you are using Spyder, the lines just print continuously with all the previous solutions. A way to avoid that is using:
for i in range(1000):
print('\r' + str(round(i/len(df)*100,1)) + '% complete', end='')
sys.stdout.flush()
type()
?
>>> class A:
... def whoami(self):
... print(type(self).__name__)
...
>>>
>>> class B(A):
... pass
...
>>>
>>>
>>> o = B()
>>> o.whoami()
'B'
>>>
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
use like this your inline css
<td width="178" rowspan="3" valign="top"
align="right" background="images/left.jpg"
style="background-repeat:background-position: right top;">
</td>
As you can see, there is a lot of solutions, they mainly parse the JSON to check it and at the end you will have to parse it to be sure.
But, depending on the context, you may improve the performances with a pre-check.
What I do when I call APIs, is just checking that the first character is '{' and the last is '}'. If it's not the case, I don't bother creating a parser.
$('#tblSub1View').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bDestroy": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0, 1]
}],
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"iDisplayLength": 10,
});
Also:
find ./ -type f -print0 | xargs -0 grep "foo"
but grep -r
is a better answer.
try like this. hope it works
drawable-sw720dp-xxhdpi and values-sw720dp-xxhdpi
drawable-sw720dp-xxxhdpi and values-sw720dp-xxxhdpi
link might destroy so pasted ans
reference Android xxx-hdpi real devices
xxxhdpi was only introduced because of the way that launcher icons are scaled on the nexus 5's launcher Because the nexus 5's default launcher uses bigger icons, xxxhdpi was introduced so that icons would still look good on the nexus 5's launcher.
also check these links
Different resolution support android
Application Skeleton to support multiple screen
Is there a list of screen resolutions for all Android based phones and tablets?
Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.
location / {
root /path/to/root/of/static/files;
try_files $uri $uri/ @apachesite;
expires max;
access_log off;
}
location @apachesite {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files
. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.
I hope this helps:
var token = document.getElementById('token').value;
var nombre = document.getElementById('txtNombre').value;
$("#txtNombre").keyup(function () {
$.ajax({
type: "POST",
url: host() + "Formulario/BuscarNombreAutocompletar/",
data: JSON.stringify({ "nombre": nombre }),
headers: {
'Authorization': 'Bearer ' + token
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dataArray = [];
if (controlCarga(data)) {
$.each(data[1], function (i, item) {
dataArray.push(item.frmNombre)
});
$('#txtNombre').autocomplete({
clearButton: true,
source: dataArray,
selectFirst: true,
minLength: 2
});
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error: ' + xhr.responseText);
}
});
});
Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
Using apkanalyzer
that is now part of cmdline-tools
:
$ apkanalyzer manifest version-code my_app.apk
1
$ apkanalyzer manifest version-name my_app.apk
1.2.3.4
// open in default browser
Process.Start("http://www.stackoverflow.net");
// open in Internet Explorer
Process.Start("iexplore", @"http://www.stackoverflow.net/");
// open in Firefox
Process.Start("firefox", @"http://www.stackoverflow.net/");
// open in Google Chrome
Process.Start("chrome", @"http://www.stackoverflow.net/");
You can escape the "space" char by putting a \ right before it.
You can also use ngrok: https://ngrok.com/. I use it all the time to have a public server running on my localhost. Hope this helps.
Another options which even provides your own custom domain for free are serveo.net and https://localtunnel.github.io/www/
We can also use str_extract
from stringr
years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20 1
If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all
which unlike str_extract
returns all the macthes.
years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20" "1"
stringr::str_extract_all(years, "\\d+")
#[[1]]
#[1] "20" "21"
#[[2]]
#[1] "1"
Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.
From AngularJS 1.0.8
directives.directive('ngBindHtmlUnsafe', [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
}
}]);
To use:
<div ng-bind-html-unsafe="group.description"></div>
To disable $sce
:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
A trap is an exception in a user process. It's caused by division by zero or invalid memory access. It's also the usual way to invoke a kernel routine (a system call) because those run with a higher priority than user code. Handling is synchronous (so the user code is suspended and continues afterwards). In a sense they are "active" - most of the time, the code expects the trap to happen and relies on this fact.
An interrupt is something generated by the hardware (devices like the hard disk, graphics card, I/O ports, etc). These are asynchronous (i.e. they don't happen at predictable places in the user code) or "passive" since the interrupt handler has to wait for them to happen eventually.
You can also see a trap as a kind of CPU-internal interrupt since the handler for trap handler looks like an interrupt handler (registers and stack pointers are saved, there is a context switch, execution can resume in some cases where it left off).
git log -1
will display the latest commit message or git log -1 --oneline
if you only want the sha1 and associated commit message to be displayed.
There is a very easy option using Visual Studio Code:
You need to add two jars into the WEB-INF/lib directory or your webapp (or lib directory of the server):
I'd say this is the modern C++ way.
#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);
EDIT:
so the right way to store a pointer as an integer is to use the uintptr_t
or intptr_t
types. (See also in cppreference integer types for C99).
these types are defined in <stdint.h>
for C99 and in the namespace std
for C++11 in <cstdint>
(see integer types for C++).
C++11 (and onwards) Version
#include <cstdint>
std::uintptr_t i;
C++03 Version
extern "C" {
#include <stdint.h>
}
uintptr_t i;
C99 Version
#include <stdint.h>
uintptr_t i;
In C there is only one cast and using the C cast in C++ is frowned upon (so don't use it in C++). In C++ there is different casts. reinterpret_cast
is the correct cast for this conversion (See also here).
C++11 Version
auto i = reinterpret_cast<std::uintptr_t>(p);
C++03 Version
uintptr_t i = reinterpret_cast<uintptr_t>(p);
C Version
uintptr_t i = (uintptr_t)p; // C Version
I have worked on some servers where sort don't support '-u' option. there we have to use
sort xyz | uniq
A little error checking goes a long way -- you can always test the value of errno or call perror() or strerror() to get more information about why the fopen() call failed.
Otherwise the suggestions about checking the path are probably correct... most likely you're not in the directory you think you are from the IDE and don't have the permissions you expect.
In similar case I used: white-space: nowrap;
If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.
Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)
Negative margins would be an easy solution.
Such hack like "tabIndex=-1" not work for me with Chrome v53.
This is which works for chrome, and most browsers:
function removeTabIndex(element) {_x000D_
element.removeAttribute('tabindex');_x000D_
}
_x000D_
<input tabIndex="1" />_x000D_
<input tabIndex="2" id="notabindex" />_x000D_
<input tabIndex="3" />_x000D_
<button tabIndex="4" onclick="removeTabIndex(document.getElementById('notabindex'))">Remove tabindex</button>
_x000D_
In this case, where the DataFrame
is long but not too wide, you can simply slice it:
>>> df = pd.DataFrame({"A": range(1000), "B": range(1000)})
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
A 1000 non-null values
B 1000 non-null values
dtypes: int64(2)
>>> df[:5]
A B
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
If it's both wide and long, I tend to use .ix
:
>>> df = pd.DataFrame({i: range(1000) for i in range(100)})
>>> df.ix[:5, :10]
0 1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
In java, String is immutable. Being immutable we mean that once a String is created, we can not change its value. StringBuffer is mutable. Once a StringBuffer object is created, we just append the content to the value of object instead of creating a new object. StringBuilder is similar to StringBuffer but it is not thread-safe. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest. You can learn difference between String, StringBuilder and StringBuffer by implementing them.
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 });
//Or
using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
}
//Or
using(var context = new MyDataContext())
{
object[] parameters = { param1, param2, param3 };
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
parameters).ToList();
}
//Or
using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
param1, param2, param3).ToList();
}
<select>
<option value="" disabled selected hidden>Select an Option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
</select>
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
This is an attempt to improve on Brent Bradburn's great approach as follows:
sh -c
)-f <file>
@
to prevent it from being echoed before executionCuriously, GNU make
has no feature for listing just the names of targets defined in a makefile. While the -p
option produces output that includes all targets, it buries them in a lot of other information and also executes the default target (which could be suppressed with -f/dev/null
).
Place the following rule in a makefile for GNU make
to implement a target named list
that simply lists all target names in alphabetical order - i.e.: invoke as make list
:
.PHONY: list
list:
@$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$'
Important: On pasting this, make sure that the last line is indented by exactly 1 actual tab char. (spaces do not work).
Note that sorting the resulting list of targets is the best option, since not sorting doesn't produce a helpful ordering in that the order in which the targets appear in the makefile is not preserved.
Also, the sub-targets of a rule comprising multiple targets are invariably output separately and will therefore, due to sorting, usually not appear next to one another; e.g., a rule starting with a z:
will not have targets a
and z
listed next to each other in the output, if there are additional targets.
Explanation of the rule:
.PHONY: list
$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null
make
again in order to print and parse the database derived from the makefile:
-p
prints the database-Rr
suppresses inclusion of built-in rules and variables-q
only tests the up-to-date-status of a target (without remaking anything), but that by itself doesn't prevent execution of recipe commands in all cases; hence:-f $(lastword $(MAKEFILE_LIST))
ensures that the same makefile is targeted as in the original invocation, regardless of whether it was targeted implicitly or explicitly with -f ...
.include
directives; to address this, define variable THIS_FILE := $(lastword $(MAKEFILE_LIST))
before any include
directives and use -f $(THIS_FILE)
instead.:
is a deliberately invalid target that is meant to ensure that no commands are executed; 2>/dev/null
suppresses the resulting error message. Note: This relies on -p
printing the database nonetheless, which is the case as of GNU make 3.82. Sadly, GNU make offers no direct option to just print the database, without also executing the default (or given) task; if you don't need to target a specific Makefile, you may use make -p -f/dev/null
, as recommended in the man
page.-v RS=
/^# File/,/^# Finished Make data base/
if ($$1 !~ "^[#.]")
#
... ignores non-targets, whose blocks start with # Not a target:
.
... ignores special targets:
egrep -v -e '^[^[:alnum:]]' -e '^$@$$'
removes unwanted targets from the output:
'^[^[:alnum:]]'
... excludes hidden targets, which - by convention - are targets that start neither with a letter nor a digit.'^$@$$'
... excludes the list
target itselfRunning make list
then prints all targets, each on its own line; you can pipe to xargs
to create a space-separated list instead.
int
means interrupt, and the number 0x80
is the interrupt number.
An interrupt transfers the program flow to whomever is handling that interrupt, which is interrupt 0x80
in this case.
In Linux, 0x80
interrupt handler is the kernel, and is used to make system calls to the kernel by other programs.
The kernel is notified about which system call the program wants to make, by examining the value in the register %eax
(AT&T syntax, and EAX in Intel syntax). Each system call have different requirements about the use of the other registers. For example, a value of 1
in %eax
means a system call of exit()
, and the value in %ebx
holds the value of the status code for exit()
.
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
You haven't actually asked a question, but assuming you have one, this could be your answer...
Assuming all characters, except the "Special Characters" are allowed you can write
String regex = "^[^<>'\"/;`%]*$";
The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
$host = $_SERVER['HTTP_HOST'];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
$domain = $matches[0];
$url = explode($domain, $host);
$subdomain = str_replace('.', '', $url[0]);
echo 'subdomain: '.$subdomain.'<br />';
echo 'domain: '.$domain.'<br />';
Another alternative:
>>> import re
>>> str = 'this is a string with multiple spaces and tabs'
>>> str = re.sub('[ \t]+' , ' ', str)
>>> print str
this is a string with multiple spaces and tabs
You can retrieve the list of column name by simple query and then remove those column by apply where query like this.
SELECT * FROM (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
) AS allColumns
WHERE allColumns.COLUMN_NAME NOT IN ('unwantedCol1', 'unwantedCol2')
I use the following Interactivity Behavior to provide an unloading event to WPF UserControls. You can include the behavior in the UserControls XAML. So you can have the functionality without placing the logic it in every single UserControl.
XAML declaration:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
<behaviors:UserControlSupportsUnloadingEventBehavior UserControlClosing="UserControlClosingHandler" />
</i:Interaction.Behaviors>
CodeBehind handler:
private void UserControlClosingHandler(object sender, EventArgs e)
{
// to unloading stuff here
}
Behavior Code:
/// <summary>
/// This behavior raises an event when the containing window of a <see cref="UserControl"/> is closing.
/// </summary>
public class UserControlSupportsUnloadingEventBehavior : System.Windows.Interactivity.Behavior<UserControl>
{
protected override void OnAttached()
{
AssociatedObject.Loaded += UserControlLoadedHandler;
}
protected override void OnDetaching()
{
AssociatedObject.Loaded -= UserControlLoadedHandler;
var window = Window.GetWindow(AssociatedObject);
if (window != null)
window.Closing -= WindowClosingHandler;
}
/// <summary>
/// Registers to the containing windows Closing event when the UserControl is loaded.
/// </summary>
private void UserControlLoadedHandler(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
throw new Exception(
"The UserControl {0} is not contained within a Window. The UserControlSupportsUnloadingEventBehavior cannot be used."
.FormatWith(AssociatedObject.GetType().Name));
window.Closing += WindowClosingHandler;
}
/// <summary>
/// The containing window is closing, raise the UserControlClosing event.
/// </summary>
private void WindowClosingHandler(object sender, CancelEventArgs e)
{
OnUserControlClosing();
}
/// <summary>
/// This event will be raised when the containing window of the associated <see cref="UserControl"/> is closing.
/// </summary>
public event EventHandler UserControlClosing;
protected virtual void OnUserControlClosing()
{
var handler = UserControlClosing;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
With SQL 2012 and later, you could use TRY_CAST
/TRY_CONVERT
to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL
-- note though that this will match scientific notation too (1+E34). (If you use decimal
, then scientific notation won't match)
The most likely culprit is Microsoft Internet Information Server. You can stop the service from the command line on Windows 7/Vista:
net stop was /y
or XP:
net stop iisadmin /y
read this http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
in Xcode 8.3.2, iOS 10.3 Thats is good to now
Sample1:
let dayMoveRaw = 5
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05
Sample2:
let dayMoveRaw = 55
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
import traceback
traceback.print_exc()
When doing this inside an except ...:
block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.
First, you may want to install glances:
sudo apt-get install python-pip build-essential python-dev lm-sensors
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances
Then run it in the terminal!
glances
In your Python code, add at the begin of the file, the following:
import os
import gc # Garbage Collector
After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:
del myBigVar
gc.collect()
In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!
Good luck!
P.S. I assume you are working on a Debian or Ubuntu system
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"]; echo nl2br($text);
If the error is thrown inside a closure that defines self
as unowned
, you may be limited in what you can access and will get this error code in certain situations. Especially while debugging. If this is the case for you try changing [unowned self]
to [weak self]
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.
borders
linear-gradient
conic-gradient
transform
and overflow
clip-path
I think that all have been covered here except for method 3, using the conic-gradient
, so I will share it here:
.triangle{_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
Please check this gist.
https://gist.github.com/ecdundar/789660d830d6d40b6c90
#!/bin/bash
# copymysql.sh
# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200
MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"
REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "
LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "
IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema' ;"
# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`
# COPY ALL TABLES
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
IGNOREVIEWS=""
for view in $views; do
IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view "
done
echo "TABLES "$db
$MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
$MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction $db | mysql $LOCALCONNECTION $db
done
# COPY ALL PROCEDURES
for db in $databases; do
echo "PROCEDURES "$db
#PROCEDURES
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL TRIGGERS
for db in $databases; do
echo "TRIGGERS "$db
#TRIGGERS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL VIEWS
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
MYVIEWS=""
for view in $views; do
MYVIEWS=${MYVIEWS}" "$view" "
done
echo "VIEWS "$db
if [ -n "$MYVIEWS" ]; then
#VIEWS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
fi
done
echo "OK!"
With the xhr2 library you can globally overwrite XMLHttpRequest
from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.
global.XMLHttpRequest = require('xhr2');
I also received this error while writing a custom form control component in Angular 7. However, none of the answers are applicable to Angular 7.
In my case, the following needed to be add to the @Component
decorator:
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyCustomComponent), // replace name as appropriate
multi: true
}
]
This is a case of "I don't know why it works, but it does." Chalk it up to poor design/implementation on the part of Angular.
This one is working fine using V 4.0.3
var vv = $('.mySelect2');
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label);
Location:
C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe
There is a wonderful library called Functional Java which handles many of the things you'd want Java to have but it doesn't. Then again, there's also this wonderful language Scala which does everything Java should have done but doesn't while still being compatible with anything written for the JVM.
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
It's always worth grouping elements into sections that are relevant. In your case, a parent element that contains two columns;
HTML:
<div class='container2'>
<img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails' />
<div class="text">
<h4>Facebook</h4>
<p>
fine location, GPS, coarse location
<span>0 mins ago</span>
</p>
</div>
</div>
CSS:
* {
padding:0;
margin:0;
}
.iconDetails {
margin:0 2%;
float:left;
height:40px;
width:40px;
}
.container2 {
width:100%;
height:auto;
padding:1%;
}
.text {
float:left;
}
.text h4, .text p {
width:100%;
float:left;
font-size:0.6em;
}
.text p span {
color:#666;
}
NODE_ENV
is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV
specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.
You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:
var environment = process.env.NODE_ENV
Assume production if you don't recognise the value:
var isDevelopment = environment === 'development'
if (isDevelopment) {
setUpMoreVerboseLogging()
}
You can alternatively using express' app.get('env')
function, but note that this is NOT RECOMMENDED as it defaults to "development"
, which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).
Be aware that if you haven't explicitly set NODE_ENV
for your environment, it will be undefined
if you access it from process.env
, there is no default.
How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.
If you want to set the environment variable as a one-off, you can do so from the command line:
export NODE_ENV=production
$env:NODE_ENV = 'production'
In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!
Convention has dictated that there are two 'main' values you should use for NODE_ENV
, either production
or development
, all lowercase. There's nothing to stop you from using other values, (test
, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production'
or 'development'
to determine what to do, so there may be side effects that aren't immediately obvious.
Finally, note that it's a really bad idea to try to set NODE_ENV
from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.
Update: For bash scripts, the most direct and performant approach is:
if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
echo "pattern exists!"
fi
This will work very speedily even in directories with millions of files and does not involve a new subshell.
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
You need to prevent the default event (following the link), otherwise your link will load a new page:
$(document).ready(function(){
$('.play_navigation a').click(function(e){
e.preventDefault();
console.log("this is the click");
});
});
As pointed out in comments, if your link has no href, then it's not a link, use something else.
Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.
I was trying to use @class "Myclass.h"
.
When I changed it to #import "Myclass.h"
, it worked fine.
the following implements A friend's suggestion
#!/bin/bash
rcut(){
nu="$( echo $1 | cut -d"$DELIM" -f 2- )"
if [ "$nu" != "$1" ]
then
rcut "$nu"
else
echo "$nu"
fi
}
$ export DELIM=.
$ rcut a.b.c.d
d
I have edited one of the previous post. Now, it is way more simple and it works perfectly.
<input style="position: absolute;left:-9999px;" type="radio" name="emotion" id="sad" />
<label for="sad"><img src="red.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm sad" /></label>
<input style="position: absolute;left:-9999px;" type="radio" name="emotion" id="happy" />
<label for="happy"><img src="blue.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm happy" /></label>
You also can use graceful restart the apache server with service apache2 reload
or apachectl -k graceful
.
As the apache doc says:
The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.
I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:
String cannot be resolved to a variable
With this Java code:
if (true)
String my_variable = "somevalue";
System.out.println("foobar");
You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?
Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.
If you put braces around the conditional block like this:
if (true){
String my_variable = "somevalue"; }
System.out.println("foobar");
Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.
SOLUTION 1 (combine find
and grep
)
The purpose of this solution is not to deal with grep
performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.
Use find
, for excluding directories foo and bar :
find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
Then combine find
and the non-recursive use of grep
, as a portable solution :
find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
SOLUTION 2 (using the --exclude-dir
option of grep
):
You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.
grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
To exclude multiple directories, use --exclude-dir
as:
--exclude-dir={node_modules,dir1,dir2,dir3}
SOLUTION 3 (Ag)
If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in .gitignore
, so you don't have to keep passing the same cumbersome exclude options to grep
or find
.
The best way to understand is to simply think from top to bottom ( Large Desktops to Mobile Phones)
Firstly, as B3 is mobile first so if you use xs then the columns will be same from Large desktops to xs ( i recommend using xs or sm as this will keep everything the way you want on every screen size )
Secondly if you want to give different width to columns on different devices or resolutions, than you can add multiple classes e.g
the above will change the width according to the screen resolutions, REMEMBER i am keeping the total columns in each class = 12
I hope my answer would help!
A bit more universal <select name="env" style="width: 200px; position:absolute;" onchange="this.nextElementSibling.value=this.value">_x000D_
<option></option>_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option> _x000D_
</select>_x000D_
<input style="width: 178px; margin-top: 1px; border: none; position:relative; left:1px; margin-right: 25px;" value="123456789012345678901234"/>layout ...
_x000D_
from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))
first you need to import Sum then ..
RENAME TABLE old_table_name TO new_table_name;
$ aws configure
and use the new key and secret.Run the command again:
serverless invoke local --function create --path mocks/create-event.json
Additionally, if you want to use the filter in your controller the same way you do it here:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
You could do something like:
var filteredItems = $scope.$eval('items | filter:filter:criteriaMatch(criteria)');
I think this is a good structure. And it is a nicely written blog explaining the mindset of these choices.
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
You can use $inject service to inject a service in you config
app.config(function($provide){ $provide.decorator("$exceptionHandler", function($delegate, $injector){ return function(exception, cause){ var $rootScope = $injector.get("$rootScope"); $rootScope.addError({message:"Exception", reason:exception}); $delegate(exception, cause); }; }); });
Source: http://odetocode.com/blogs/scott/archive/2014/04/21/better-error-handling-in-angularjs.aspx
My fellows,
In January 2019 I used a code made before:
<script type="text/javascript">
function imprimir() {
var divToPrint=document.getElementById("ConsutaBPM");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
</script>
To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...
The table mas be defined with BORDER and CELLPADDING:
<table border='1' cellpadding='1' id='Tablbpm1' >
It worked fine!!!
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
//create and fill polygon
CanvasRenderingContext2D.prototype.fillPolygon = function (pointsArray, fillColor, strokeColor) {
if (pointsArray.length <= 0) return;
this.moveTo(pointsArray[0][0], pointsArray[0][1]);
for (var i = 0; i < pointsArray.length; i++) {
this.lineTo(pointsArray[i][0], pointsArray[i][1]);
}
if (strokeColor != null && strokeColor != undefined)
this.strokeStyle = strokeColor;
if (fillColor != null && fillColor != undefined) {
this.fillStyle = fillColor;
this.fill();
}
}
//And you can use this method as
var polygonPoints = [[10,100],[20,75],[50,100],[100,100],[10,100]];
context.fillPolygon(polygonPoints, '#F00','#000');
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties
to set a default date format to all of your classes spring.jackson.date-format
.
For your date format example, you would add this line to your properties file:
spring.jackson.date-format=yyyy-MM-dd
This work for me
.select2-container--default .select2-results>.select2-results__options{
max-height: 500px !important;
}
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
Try this:
EditText et = (EditText)findViewById(R.id.inbox);
et.setSelection(et.getText().length());
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test "ABC" "DEF"
Just follow the convention being used for by project/team.
The options are the same as for the fopen function in the C standard library:
w
truncates the file, overwriting whatever was already there
a
appends to the file, adding onto whatever was already there
w+
opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file
a+
opens for appending and reading, allowing you both to append to the file and also read its contents
You can also use the Filter button to filter tables with a certain string in it. You can do the same with stored procedures and views.
You need interfaces in Java since it is statically typed and the contract between classes should be known during compilation. In JavaScript it is different. JavaScript is dynamically typed; it means that when you get the object you can just check if it has a specific method and call it.
Let me make it easy for all of you with an example.
For simplicity purpose, let's assume there are 32 elements in an array in the sorted order out of which we are searching for an element using binary search.
1 2 3 4 5 6 ... 32
Assume we are searching for 32. after the first iteration, we will be left with
17 18 19 20 .... 32
after the second iteration, we will be left with
25 26 27 28 .... 32
after the third iteration, we will be left with
29 30 31 32
after the fourth iteration, we will be left with
31 32
In the fifth iteration, we will find the value 32.
So, If we convert this into a mathematical equation, we will get
(32 X (1/25)) = 1
=> n X (2-k) = 1
=> (2k) = n
=> k log22 = log2n
=> k = log2n
Hence the proof.
$('selector').css('cursor', 'pointer'); // 'default' to revert
I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".
The normal arrow cursor is just "default".
try this one
DB::table('user')->where('name','Jhon')->get();
just remove the "=" sign . . . .because you are trying to array just the name 'jhon' . . . . . . . .I hope it's help you . .
A few others have posted answers. There are some obvious problems, like it returns false
when the Regex passes, and the ^
and $
operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).
Besides that, the issue is just a typo.
Change this...
var reWhiteSpace = new RegExp("/^\s+$/");
To this...
var reWhiteSpace = new RegExp("\\s+");
When using a regex within RegExp()
, you must do the two following things...
/
brackets.\\s
in place of \s
, etc.Full working demo from source code....
$(document).ready(function(e) { function hasWhiteSpace(s) {
var reWhiteSpace = new RegExp("\\s+");
// Check for white space
if (reWhiteSpace.test(s)) {
//alert("Please Check Your Fields For Spaces");
return 'true';
}
return 'false';
}
$('#whitespace1').html(hasWhiteSpace(' '));
$('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
strInputString = strInputString.replace(/'/g, "''");
If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray
at a certain index, you would do it using the method:
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
This method is called insertObject:atIndex:
and it is clear that an object is being inserted at a specified index.
In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray
called array
would be called as follows:
NSString *obj = @"Hello, World!";
int index = 5;
[array insertObject:obj atIndex:index];
This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.
Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber
class; this has several object creation methods, including:
+ (id)numberWithBool:(BOOL)value;
+ (id)numberWithFloat:(float)value;
+ (id)numberWithDouble:(double)value;
In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.
Reference docs of docker: https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections
There are 2 ways in configuring the docker daemon port
1) Configuring at /etc/default/docker file:
DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"
2) Configuring at /etc/docker/daemon.json:
{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}
If the docker default socket is not configured Docker will wait for infinite period.i.e
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :
Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)
The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:
# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
This error is not because that the docker is not running, but because of default docker socket is not enabled.
Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:
# netstat -tunlp | grep -i 5000
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 31661/dockerd
Applicable for Docker Version 17.04, may vary with different versions of docker.
IsisCode gives you a good solution. Another one is to position border div inside parent div. Check this example http://jsfiddle.net/A2tu9/
UPD: You can also use pseudo element :after
(:before
), in this case HTML will not be polluted with extra markup:
.my-div {
position: relative;
padding: 4px;
...
}
.my-div:after {
content: '';
position: absolute;
top: -3px;
left: -3px;
bottom: -3px;
right: -3px;
border: 1px #888 solid;
}
On Linux I would suggest,
# FILE_TO_BE_ATTACHED=abc.gz
uuencode abc.gz abc.gz > abc.gz.enc # This is optional, but good to have
# to prevent binary file corruption.
# also it make sure to get original
# file on other system, w/o worry of endianness
# Sending Mail, multiple attachments, and multiple receivers.
echo "Body Part of Mail" | mailx -s "Subject Line" -a attachment1 -a abc.gz.enc "[email protected] [email protected]"
Upon receiving mail attachment, if you have used uuencode, you would need uudecode
uudecode abc.gz.enc
# This will generate file as original with name as same as the 2nd argument for uuencode.
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
@{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = '@nonProID';
var proID = '@proID';
window.nonID = '@nonProID';
window.proID = '@proID';
</script>
I had similar requirement (to avoid this ugly ORA-31061: XDB error: special char to escaped char conversion failed. ), but had to keep the line breaks.
I tried this from an excellent comment
'[^ -~|[:space:]]'
but got this ORA-12728: invalid range in regular expression .
but it lead me to my solution:
select t.*, regexp_replace(deta, '[^[:print:]|[:space:]]', '#') from
(select '- <- strangest thing here, and I want to keep line break after
-' deta from dual ) t
displays (in my TOAD tool) as
^
=> is not in the sets (of printing [:print:]
or space |[:space:]
chars)DECLARE @nombre NVARCHAR(100)
DECLARE @tablas TABLE(nombre nvarchar(100))
INSERT INTO @tablas
SELECT t.TABLE_SCHEMA+ '.'+t.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES T
DECLARE @contador INT=0
SELECT @contador=COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHILE @contador>0
BEGIN
SELECT TOP 1 @nombre=nombre FROM @tablas
DECLARE @sql NVARCHAR(500)=''
SET @sql =@sql+'Truncate table '+@nombre
EXEC (@sql)
SELECT @sql
SET @contador=@contador-1
DELETE TOP (1) @tablas
END
You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList
the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList
aren't seen by TestMethod
.
try:
private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);
This then passes a reference to the local-variable myRef
(as declared in TestMethod
); now, if you reassign the parameter inside ChangeList
you are also reassigning the variable inside TestMethod
.
SARose's answer worked for me until I updated from Ubuntu 20.04 LTS. The slight change I made to his code makes it work on the latest Ubuntu release.
import subprocess
def find_files(file_name):
command = ['locate'+ ' ' + file_name]
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
output = output.decode()
search_results = output.split('\n')
return search_results
I use two methods for relative sizing. I have a class called Relative
with three attached properties To
, WidthPercent
and HeightPercent
which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.
The other approach is rather more cunning. Add a ViewBox
where you want relative sizes inside, then inside that, add a Grid
at width 100. Then if you add a TextBlock
with width 10 inside that, it is obviously 10% of 100.
The ViewBox
will scale the Grid
according to whatever space it has been given, so if its the only thing on the page, then the Grid
will be scaled out full width and effectively, your TextBlock
is scaled to 10% of the page.
If you don't set a height on the Grid
then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox
else it will start scaling the height as well. You can probably work around this with a Stretch
of UniformToFill
.
I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.
<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">
This will not render the form until it is initialized.
You can use lambda function, an example for 1D array:
import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)
This will give you the result:
[0, 2, 3]
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
There are multiple ways to get a string representation of a type. Switches can also be used with user types:
var user interface{}
user = User{name: "Eugene"}
// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
// Built-in types are possible (int, float64, string, etc.)
fmt.Printf("Integer: %v", v)
case User:
// User defined types work as well
fmt.Printf("It's a user: %s\n", user.(User).name)
}
// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)
// You can also use %T to get a string value
fmt.Printf("%T", user)
// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)
if userTypeAsString == "main.User" {
fmt.Printf("\nIt's definitely a user")
}
Link to a playground: https://play.golang.org/p/VDeNDUd9uK6
I needed something similar, and came up with using the :before (or :after) pseudoclasses:
#mydiv {
background-color: #fbb;
margin-top: 100px;
position: relative;
}
#mydiv:before {
content: "";
background-color: #bfb;
top: -100px;
height: 100px;
width: 100%;
position: absolute;
}
The short answer: seems like a totally reasonable approach to the asynchrony problem to me. With a couple caveats.
I had a very similar line of thought when working on a new project we just started at my job. I was a big fan of vanilla Redux's elegant system for updating the store and rerendering components in a way that stays out of the guts of a React component tree. It seemed weird to me to hook into that elegant dispatch
mechanism to handle asynchrony.
I ended up going with a really similar approach to what you have there in a library I factored out of our project, which we called react-redux-controller.
I ended up not going with the exact approach you have above for a couple reasons:
dispatch
itself via lexical scope. This limits the options for refactoring once that connect
statement gets out of hand -- and it's looking pretty unwieldy with just that one update
method. So you need some system for letting you compose those dispatcher functions if you break them up into separate modules.Take together, you have to rig up some system to allow dispatch
and the store to be injected into your dispatching functions, along with the parameters of the event. I know of three reasonable approaches to this dependency injection:
dispatch
middleware approaches, but I assume they're basically the same.connect
, rather than having to work directly with the raw, normalized store.this
context, through a variety of possible mechanisms.Update
It occurs to me that part of this conundrum is a limitation of react-redux. The first argument to connect
gets a state snapshot, but not dispatch. The second argument gets dispatch but not the state. Neither argument gets a thunk that closes over the current state, for being able to see updated state at the time of a continuation/callback.
A more permanent fix might be to look in /etc/redis/redis.conf around lines 200-250 there are settings for the rdb features, that were not a part of redis back in the 2.x days.
notably
dir ./
can be changed to
dir /home/someuser/redislogfiledirectory
or you could comment out all the save lines, and not worry about persistence. (See the comments in /etc/redis/redis.conf)
Also, don't forget
service redis-server stop
service redis-server start
I faced the same issue. To get rid of this issue, I followed the below steps and it worked for me.
Please check out Crane (I'm the author)
https://www.nuget.org/packages/Crane/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");
Also has a bunch of other features you might like.
I'm using Webmin because its a productivity gem for someone who finds command line administration a bit daunting and impenetrable.
There is a "Save and Run Now" button in the "System > Scheduled Cron Jobs > Edit Cron Job" web interface.
It displays the output of the command and is exactly what I needed.
In some cases, you might need business logic to be performed by a parent component. In the example below we have a child component that renders table row depending on the logic provided by the parent component:
@Component({
...
template: '<table-component [getRowColor]="getColor"></table-component>',
directives: [TableComponent]
})
export class ParentComponent {
// Pay attention on the way this function is declared. Using fat arrow (=>) declaration
// we can 'fixate' the context of `getColor` function
// so that it is bound to ParentComponent as if .bind(this) was used.
getColor = (row: Row) => {
return this.fancyColorService.getUserFavoriteColor(row);
}
}
@Component({...})
export class TableComponent{
// This will be bound to the ParentComponent.getColor.
// I found this way of declaration a bit safer and convenient than just raw Function declaration
@Input('getRowColor') getRowColor: (row: Row) => Color;
renderRow(){
....
// Notice that `getRowColor` function holds parent's context because of a fat arrow function used in the parent
const color = this.getRowColor(row);
renderRow(row, color);
}
}
So, I wanted to demonstrate 2 things here:
Per @osahyoun answer, I find the following as a better and efficient way to 'inherit' from Person's prototype object:
function Person(name){
this.name = name;
this.type = 'human';
}
Person.prototype.info = function(){
console.log("Name:", this.name, "Type:", this.type);
}
function Robot(name){
Person.call(this, name)
this.type = 'robot';
}
// Set Robot's prototype to Person's prototype by
// creating a new object that inherits from Person.prototype,
// and assigning it to Robot.prototype
Robot.prototype = Object.create(Person.prototype);
// Set constructor back to Robot
Robot.prototype.constructor = Robot;
Create new instances:
var person = new Person("Bob");
var robot = new Robot("Boutros");
person.info(); // Name: Bob Type: human
robot.info(); // Name: Boutros Type: robot
Now, by using Object.create:
Person.prototype.constructor !== Robot
Check also the MDN documentation.
I'm using contentEditable
to allow rich text editing in my app. I don't know how it slips through, but when an image is inserted, and then resized (by dragging the anchors on its side), it generates something like this:
<img style="width:55px;height:55px" width="100" height="100" src="pic.gif" border=0/>
(subsequent testing shown that inserted images did not contain this "rogue" style attr+param).
When rendered by the browser (IE7), the width and height in the style overrides the img width/height param (so the image is shown like how I wanted it.. resized to 55px x 55px. So everything went well so it seems.
When I output the page to a ms-word document via setting the mime type application/msword or pasting the browser rendering to msword document, all the images reverted back to its default size. I finally found out that msword is discarding the style and using the img width and height tag (which has the value of the original image size).
Took me a while to found this out. Anyway... I've coded a javascript function to traverse all tags and "transferring" the img style.width and style.height values into the img.width and img.height, then clearing both the values in style, before I proceed saving this piece of html/richtext data into the database.
cheers.
opps.. my answer is.. no. leave both attributes directly under img, rather than style.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Start a shell as hduser (from root) and run your command
sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input
[update]
Also note that the hdfs
user is the super user and has all r/w privileges.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Before you set your routes, add the code:
app.all('*', function(req, res, next) {
setTimeout(function() {
next();
}, 120000); // 120 seconds
});
Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at
<%GERONIMO_HOME%>/var/catalina/server.xml
.
The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize
still displays 2097152 (the default value)
Since at the time of installing of any module it mainly put corresponding .pm files in respective directories.
So if you want to remove module only for some testing purpose or temporarily best is to find the path where module is stored using perldoc -l <MODULE>
and then simply move the module from there to some other location.
This approach can also be tried as a more permanent solution but i am not aware of any negative consequences as i do it mainly for testing.
In case the accepted answer by Wadih didn't work for you, try echo %CD%
To split a string to an array in awk
we use the function split()
:
awk '{split($0, a, ":")}'
# ^^ ^ ^^^
# | | |
# string | delimiter
# |
# array to store the pieces
If no separator is given, it uses the FS
, which defaults to the space:
$ awk '{split($0, a); print a[2]}' <<< "a:b c:d e"
c:d
We can give a separator, for example :
:
$ awk '{split($0, a, ":"); print a[2]}' <<< "a:b c:d e"
b c
Which is equivalent to setting it through the FS
:
$ awk -F: '{split($0, a); print a[1]}' <<< "a:b c:d e"
b c
In gawk you can also provide the separator as a regexp:
$ awk '{split($0, a, ":*"); print a[2]}' <<< "a:::b c::d e" #note multiple :
b c
And even see what the delimiter was on every step by using its fourth parameter:
$ awk '{split($0, a, ":*", sep); print a[2]; print sep[1]}' <<< "a:::b c::d e"
b c
:::
Let's quote the man page of GNU awk:
split(string, array [, fieldsep [, seps ] ])
Divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array. The first piece is stored in
array[1]
, the second piece inarray[2]
, and so forth. The string value of the third argument, fieldsep, is a regexp describing where to split string (much as FS can be a regexp describing where to split input records). If fieldsep is omitted, the value of FS is used.split()
returns the number of elements created. seps is agawk
extension, withseps[i]
being the separator string betweenarray[i]
andarray[i+1]
. If fieldsep is a single space, then any leading whitespace goes intoseps[0]
and any trailing whitespace goes intoseps[n]
, where n is the return value ofsplit()
(i.e., the number of elements in array).
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
Call the toISOString()
method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
I found that User
works, that is, User.Identity.Name
or User.IsInRole("Administrator")
.
The accepted answer is too long, other answers didn't work for me. I'm gonna leave this for future purpose.
Dim sKey, bFound
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\SecurityHealth"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
on error goto 0 ' restore error trapping
end with
If bFound Then
MsgBox = "Registry Key Exist."
Else
MsgBox = "Nope, it doesn't exist."
End If
Here's the list of the Registry Tree, choose your own base on your current task.
HKCR = HKEY_CLASSES_ROOT
HKCU = HKEY_CURRENT_USER
HKLM = HKEY_LOCAL_MACHINE
HKUS = HKEY_USERS
HKCC = HKEY_CURRENT_CONFIG
I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.
byte[] byteArray;
byteArray= json.getBytes(StandardCharsets.US_ASCII);
String encoded=Base64.encodeBytes(byteArray);
userLogin(encoded);
Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html
I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:
pkg install lapack
pkg install atlas-devel #not sure this is needed, but just in case
I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)
I found this post more relevant in this scenario:
WITH upsert AS (
UPDATE spider_count SET tally=tally+1
WHERE date='today' AND spider='Googlebot'
RETURNING *
)
INSERT INTO spider_count (spider, tally)
SELECT 'Googlebot', 1
WHERE NOT EXISTS (SELECT * FROM upsert)
if you are using Resharper
fallow the steps in this pic
then write this in template editor
//#region $name$
$END$$SELECTION$
//#endregion $name$
and name it #region
as in this picture
hope this help you
Small change to sam yi's answer (for better readability):
select top 1000 TableID
into #ControlTable
from dbo.table
where StatusID = 7
declare @TableID int
while exists (select * from #ControlTable)
begin
select @TableID = (select top 1 TableID
from #ControlTable
order by TableID asc)
-- Do something with your TableID
delete #ControlTable
where TableID = @TableID
end
drop table #ControlTable
C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.
Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.
Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.
When writing C++ I'd pretty much always use the C++ ones over the the C style.
All the answers are good but what worked well for me is just using the simple function send_file
from Flask. This works well when you just need to send an html file as response when host:port/ApiName will show the output of the file in browser
@app.route('/ApiName')
def ApiFunc():
try:
return send_file('some-other-directory-than-root/your-file.extension')
except Exception as e:
logging.info(e.args[0])```
Use array_walk_recursive function for multi-denominational array.
array_walk_recursive($data, function (&$v, $k) {
if($k == 'transaction_date'){
$v = date('d/m/Y',$v);
}
});
Just want to mention that,
UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.bold)
UIFont.boldSystemFont(ofSize: 16)
They have different outcome...
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
Future viewers, I think this is the simplest solution, if your model contains a string type date ("2020-01-01 10:00:00" for example), then just write the following line to sort the data by date descending from newest to the oldest:
Collections.sort(messages, (o1, o2) -> o2.getMessageDate().compareTo(o1.getMessageDate()));
Go to Project settings --> Hooks --> (Under) Pre-receive hooks
Disable cp require issue reference in commits
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
Jackson has a class named SimpleBeanPropertyFilter that helps to filter fields during serialization and deserialization; not globally. I think that's what you wanted.
@JsonFilter("custom_serializer")
class User {
private String password;
//setter, getter..
}
Then in your code:
String[] fieldsToSkip = new String[] { "password" };
ObjectMapper mapper = new ObjectMapper();
final SimpleFilterProvider filter = new SimpleFilterProvider();
filter.addFilter("custom_serializer",
SimpleBeanPropertyFilter.serializeAllExcept(fieldsToSkip));
mapper.setFilters(filter);
String jsonStr = mapper.writeValueAsString(currentUser);
This will prevent password
field to get serialized. Also you will be able to deserialize password
fields as it is. Just make sure no filters are applied on the ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(yourJsonStr, User.class); // user object does have non-null password field
As instance you could use it:
First(making ssh connection):
while read pass port user ip files directs; do
sshpass -p$pass scp -o 'StrictHostKeyChecking no' -P $port $files $user@$ip:$directs
done <<____HERE
PASS PORT USER IP FILES DIRECTS
. . . . . .
. . . . . .
. . . . . .
PASS PORT USER IP FILES DIRECTS
____HERE
Second(executing commands):
while read pass port user ip; do
sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
COMMAND 1
.
.
.
COMMAND n
ENDSSH1
done <<____HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
____HERE
Third(executing commands):
Script=$'
#Your commands
'
while read pass port user ip; do
sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip "$Script"
done <<___HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
___HERE
Forth(using variables):
while read pass port user ip fileoutput; do
sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip fileinput=$fileinput 'bash -s'<<ENDSSH1
#Your command > $fileinput
#Your command > $fileinput
ENDSSH1
done <<____HERE
PASS PORT USER IP FILE-OUTPUT
. . . . .
. . . . .
. . . . .
PASS PORT USER IP FILE-OUTPUT
____HERE
in Swift 4.2
var nav = self.navigationController?.navigationBar
nav?.barStyle = UIBarStyle.Black
nav?.tintColor = UIColor.white
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]
Do this :
$(document).ready(function(){
$("#frm1").submit();
});
You'll need to add this to your server configuration:
AddType application/x-httpd-php .php
That is assuming you have installed PHP properly, which may not be the case since it doesn't work where it normally would immediately after installing.
It is entirely possible that you'll also have to add the php
.so/.dll file to your Apache configuration using a LoadModule
directive (usually in httpd.conf
).
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
Just like it sounds like: if the path exists, but is a file and not a directory, isdir
will return False
. Meanwhile, exists
will return True
in both cases.
You could replace "^0*(.*)"
to "$1"
with regex
you can use this . it's so easy to understand : by https://developer.android
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="Tom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
<TextView
android:text="Tim"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
<TextView
android:text="Todd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
</LinearLayout>
I had the same problem, with version 3.4.2
to run it (if you installed it with homebrew) run the process like this:
$ mongod --dbpath /usr/local/var/mongodb
from Google
An .axd file is a HTTP Handler file. There are two types of .axd files.
These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.
Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere
And ofcourse it is necessary
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id','JOIN Type');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();
this will give you result from table1,table2,table3 and you can use any type of join in the third variable of $this->db->join() function such as inner,left, right etc.
Try this for Windows:
npm uninstall -g cordova
Try this for MAC:
sudo npm uninstall -g cordova
You can also add Cordova like this:
If You Want To install the previous version of Cordova through the Node Package Manager (npm):
npm install -g [email protected]
If You Want To install the latest version of Cordova:
npm install -g cordova
Enjoy!
Imagine you have a window open on http://www.foo.com/bar/page.html
In all of them (HTML, Javascript and CSS):
opened_url = http://www.foo.com/bar/page.html
base_path = http://www.foo.com/bar/
home_path = http://www.foo.com/
/kitten.png = Home_path/kitten.png
kitten.png = Base_path/kitten.png
In HTML and Javascript, the base_path is based on the opened window. In big javascript projects you need a BASEPATH
or root
variable to store the base_path occasionally. (like this)
In CSS the opened url is the address of which your .css is stored or loaded, its not the same like javascript with current opened window in this case.
And for being more secure in absolute paths it is recommended to use //
instead of http://
for possible future migrations to https://
. In your own example, use it this way:
<img src="//www.foo.com/images/kitten.png">
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);
the error i received was:
cockpit.socket: Failed to listen on sockets: Address already in use
the fix I discovered is:
in /usr/lib/systemd/system/cockpit service i changed the line :
#ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
to:
#ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws
so as you can see i took out the argument about selinux then i ran:
systemctl daemon-reload
systemctl start cockpit.service
then I browsed to:
I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.
this is all on a fedora25 machine. the 9090 port had already
been added using firewall-cmd
Are you using smart pointers such as Boost shared_ptr
? If so, check if you are directly using the raw pointer anywhere by calling get()
. I've found this to be quite a common problem.
For example, imagine a scenario where a raw pointer is passed (maybe as a callback handler, say) to your code. You might decide to assign this to a smart pointer in order to cope with reference counting etc. Big mistake: your code doesn't own this pointer unless you take a deep copy. When your code is done with the smart pointer it will destroy it and attempt to destroy the memory it points to since it thinks that no-one else needs it, but the calling code will then try to delete it and you'll get a double free problem.
Of course, that might not be your problem here. At it's simplest here's an example which shows how it can happen. The first delete is fine but the compiler senses that it's already deleted that memory and causes a problem. That's why assigning 0 to a pointer immediately after deletion is a good idea.
int main(int argc, char* argv[])
{
char* ptr = new char[20];
delete[] ptr;
ptr = 0; // Comment me out and watch me crash and burn.
delete[] ptr;
}
Edit: changed delete
to delete[]
, as ptr is an array of char.
If you want to check or set the user name and email you can use the below command
Check user name
git config user.name
Set user name
git config user.name "your_name"
Check your email
git config user.email
Set/change your email
git config user.email "[email protected]"
List/see all configuration
git config --list
Position absolute, top:0 and bottom:0 for the sidebar and position relative for the wrapper (or container) witch content all the elements and it's done !
Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.
0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.
Where value in column containing comma delimited values search with multiple comma delimited
declare @d varchar(1000)='-11,-12,10,121'
set @d=replace(@d,',',',%'' or '',''+a+'','' like ''%,')
print @d
declare @d1 varchar(5000)=
'select * from (
select ''1,21,13,12'' as a
union
select ''11,211,131,121''
union
select ''411,211,131,1211'') as t
where '',''+a+'','' like ''%,'+@d+ ',%'''
print @d1
exec (@d1)
You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages under
https://pypi.org/pypi/{PKG_NAME}/json
Here's some Python code using only the standard library which gets all versions.
import json
import urllib2
from distutils.version import StrictVersion
def versions(package_name):
url = "https://pypi.org/pypi/%s/json" % (package_name,)
data = json.load(urllib2.urlopen(urllib2.Request(url)))
versions = data["releases"].keys()
versions.sort(key=StrictVersion)
return versions
print "\n".join(versions("scikit-image"))
That code prints (as of Feb 23rd, 2015):
0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1
When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink]
, then it should be assigned a name of the property the value of which will be the route it should navigate the user to.
So to fix your issue, replace this routerLink="['/about']"
with routerLink="/about"
in your HTML.
There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:
<nav class="main-nav>
<ul
class="main-nav__list"
ng-sticky
addClass="main-sticky-link"
[ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/">Home</a>
</li>
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/about">About us</a>
</li>
</ul>
</nav>
It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>
, either in your template provided above or in a parent component.
There's another issue with your AppRoutingModule
. You need to export the RouterModule
from there so that it is available to your AppModule
when it imports it. To fix that, export it from your AppRoutingModule
by adding it to the exports
array.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'what', component: WhatwedoComponent },
{ path: 'contacts', component: FooterComponent },
{ path: 'projects', component: ProjectsComponent},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes),
],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
The following works well for me:
$ git show --name-only --format=tformat: SHA1..SHA2
It can also be used with a single commit:
git show --name-only --format=tformat: SHA1
which is handy for use in Jenkins where you are provided with a List of changeSet SHA's, and want to iterate over them to see which files have been changed.
This is similar to a couple of the answers above, but using tformat:
rather than format:
removes the separator space between commits.
I think the most convenient way to solve this problem in 2020 is using another python package. We don't need install any other binary software.
Try this
pip install mysql-connector-python
and then
import mysql.connector_x000D_
_x000D_
mydb = mysql.connector.connect(_x000D_
host="",_x000D_
user="",_x000D_
passwd="",_x000D_
database=""_x000D_
) _x000D_
cursor = mydb.cursor( buffered=True)_x000D_
cursor.execute('show tables;')_x000D_
cursor.execute('insert into test values (null, "a",10)')_x000D_
mydb.commit()_x000D_
mydb.disconnect()
_x000D_
You can specify android:screenOrientation="portrait"
for each activity in your manifest.xml file. You cannot specify this option on the application
tag.
Other option is to do it programmatically, for example in an Activity
base class:
@Override
public void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom Application
class:
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
@Override
public void onActivityCreated(Activity a, Bundle savedInstanceState) {
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
});
}
ActivityLifecycleAdapter
is just a helper class you'll need to create which will be an empty implementation of ActivityLifecycleCallbacks
(so you don't have to override each and every methods of that interface when you simply need one of them).
I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.
Added the following to the config and it resolved the issue:
<system.net>
<defaultProxy enabled="true">
</defaultProxy>
</system.net>
If you are still looking for one, I just released mine: http://github.com/weixiyen/jquery-filedrop
Works for Firefox 3.6 right now. I decided not to do the Chrome hack for now and let Webkit catch up with FileReader() in the next versions of Safari and Chrome.
This plugin is future compatible.
FileReader() is the official standard over something like XHR.getAsBinary() which is deprecated according to mozilla.
It's also the only HTML5 desktop drag+drop plugin out there that I know of which allows you to send extra data along with the file, including data that can be calculated at the time of upload with a callback function.
brew install maven
mvn -version
Here you go !!! Now you have successfully installed maven on your mac os.
For instance you can use
update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'
You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.
I came across the same issue as well. Not sure why this is working but it indeed works: Try add ENGINE INNODB after your create query.
mysql> create table course
-> (course_id varchar(7),
-> title varchar (50),
-> dept_name varchar(20),
-> credits numeric(2,0),
-> primary key(course_id),
-> foreign key (dept_name) references department) ENGINE INNODB;
Check example link below and click on the div to get the color value in hex.
var color = '';_x000D_
$('div').click(function() {_x000D_
var x = $(this).css('backgroundColor');_x000D_
hexc(x);_x000D_
console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
delete(parts[0]);_x000D_
for (var i = 1; i <= 3; ++i) {_x000D_
parts[i] = parseInt(parts[i]).toString(16);_x000D_
if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
}_x000D_
color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
Check working example at http://jsfiddle.net/DCaQb/
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
(Explanation in more details can be found in an archived Microsoft KB article.)
Three things to know:
%1
, %2
, ...Two percent signs with any characters in between them are interpreted as a variable:
echo %myvar%
%%f
Why's that?
For example, if we execute your (simplified) command line
FOR /f %f in ('dir /b .') DO somecommand %f
in a batch file, rule 2 would try to interpret
%f in ('dir /b .') DO somecommand %
as a variable. In order to prevent that, you have to apply rule 3 and escape the %
with an second %
:
FOR /f %%f in ('dir /b .') DO somecommand %%f
The question is old but I felt the best answer hadn't been given, yet.
Is there an
UPDATE
syntax ... without specifying the column names?
You don't need to know any column names except for some unique column(s) to join on (id
in the example). Works reliably for any possible corner case I can think of.
This is specific to PostgreSQL. I am building dynamic code based on the the information_schema, in particular the table information_schema.columns
, which is defined in the SQL standard and most major RDBMS (except Oracle) have it. But a DO
statement with PL/pgSQL code executing dynamic SQL is totally non-standard PostgreSQL syntax.
DO
$do$
BEGIN
EXECUTE (
SELECT
'UPDATE b
SET (' || string_agg( quote_ident(column_name), ',') || ')
= (' || string_agg('a.' || quote_ident(column_name), ',') || ')
FROM a
WHERE b.id = 123
AND a.id = b.id'
FROM information_schema.columns
WHERE table_name = 'a' -- table name, case sensitive
AND table_schema = 'public' -- schema name, case sensitive
AND column_name <> 'id' -- all columns except id
);
END
$do$;
Assuming a matching column in b
for every column in a
, but not the other way round. b
can have additional columns.
WHERE b.id = 123
is optional, to update a selected row.
Related answers with more explanation:
You still need to know the list of column names that both tables share. With a syntax shortcut for updating multiple columns - shorter than what other answers suggested so far in any case.
UPDATE b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM a
WHERE b.id = 123 -- optional, to update only selected row
AND a.id = b.id;
This syntax was introduced with Postgres 8.2 in 2006, long before the question was asked. Details in the manual.
Related:
B
If all columns of A
are defined NOT NULL
(but not necessarily B
),
and you know the column names of B
(but not necessarily A
).
UPDATE b
SET (column1, column2, column3, column4)
= (COALESCE(ab.column1, b.column1)
, COALESCE(ab.column2, b.column2)
, COALESCE(ab.column3, b.column3)
, COALESCE(ab.column4, b.column4)
)
FROM (
SELECT *
FROM a
NATURAL LEFT JOIN b -- append missing columns
WHERE b.id IS NULL -- only if anything actually changes
AND a.id = 123 -- optional, to update only selected row
) ab
WHERE b.id = ab.id;
The NATURAL LEFT JOIN
joins a row from b
where all columns of the same name hold same values. We don't need an update in this case (nothing changes) and can eliminate those rows early in the process (WHERE b.id IS NULL
).
We still need to find a matching row, so b.id = ab.id
in the outer query.
db<>fiddle here
Old sqlfiddle.
This is standard SQL except for the FROM
clause.
It works no matter which of the columns are actually present in A
, but the query cannot distinguish between actual NULL values and missing columns in A
, so it is only reliable if all columns in A
are defined NOT NULL
.
There are multiple possible variations, depending on what you know about both tables.
you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-
inline-elements :- <img style="vertical-align:middle" ...>
<span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>
block-elements :- <td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
see the demo:- http://jsfiddle.net/Ewfkk/2/
CSV isn't quite that simple. Depending on the limits of the data you have, you might have to worry about quoted values (which may contain commas and newlines) and escaping quotes.
So if your data are restricted enough can get away with simple comma-splitting fine, shell script can do that easily. If, on the other hand, you need to parse CSV ‘properly’, bash would not be my first choice. Instead I'd look at a higher-level scripting language, for example Python with a csv.reader.
The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.
I usually create a libs
folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.
(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)
PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...
Should work.
Here's a working example:
Excerpt:
function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
If you can't seem to use some of the newer functions, here's something I whipped up. Probably more than you need, and I'm sure there are better ways, but it's easy to read, so it should do the job:
function get_age($date, $units='years')
{
$modifier = date('n') - date('n', strtotime($date)) ? 1 : (date('j') - date('j', strtotime($date)) ? 1 : 0);
$seconds = (time()-strtotime($date));
$years = (date('Y')-date('Y', strtotime($date))-$modifier);
switch($units)
{
case 'seconds':
return $seconds;
case 'minutes':
return round($seconds/60);
case 'hours':
return round($seconds/60/60);
case 'days':
return round($seconds/60/60/24);
case 'months':
return ($years*12+date('n'));
case 'decades':
return ($years/10);
case 'centuries':
return ($years/100);
case 'years':
default:
return $years;
}
}
Example Use:
echo 'I am '.get_age('September 19th, 1984', 'days').' days old';
Hope this helps.
resource.setrlimit
must also be used to increase the stack size and prevent segfault
The Linux kernel limits the stack of processes.
Python stores local variables on the stack of the interpreter, and so recursion takes up stack space of the interpreter.
If the Python interpreter tries to go over the stack limit, the Linux kernel makes it segmentation fault.
The stack limit size is controlled with the getrlimit
and setrlimit
system calls.
Python offers access to those system calls through the resource
module.
sys.setrecursionlimit
mentioned e.g. at https://stackoverflow.com/a/3323013/895245 only increases the limit that the Python interpreter self imposes on its own stack size, but it does not touch the limit imposed by the Linux kernel on the Python process.
Example program:
main.py
import resource
import sys
print resource.getrlimit(resource.RLIMIT_STACK)
print sys.getrecursionlimit()
print
# Will segfault without this line.
resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
sys.setrecursionlimit(0x100000)
def f(i):
print i
sys.stdout.flush()
f(i + 1)
f(0)
Of course, if you keep increasing setrlimit
, your RAM will eventually run out, which will either slow your computer to a halt due to swap madness, or kill Python via the OOM Killer.
From bash, you can see and set the stack limit (in kb) with:
ulimit -s
ulimit -s 10000
The default value for me is 8Mb.
See also:
Tested on Ubuntu 16.10, Python 2.7.12.