Just for reference, here is a list of all the available properties for a printer ManagementObject.
usage: printer.Properties["PropName"].Value
Although you need a pair of parentheses to print in Python 3, you no longer need a space after print
, because it's a function. So that's only a single extra character.
If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print
and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print
shortcut in Python 3.
Python 2:
>>> p = print
File "<stdin>", line 1
p = print
^
SyntaxError: invalid syntax
Python 3:
>>> p = print
>>> p('hello')
hello
It'll make your code less readable, but you'll save those few characters every time you print something.
Another option without sed
, awk
, perl
, etc
strings $file > $output
strings - print the strings of printable characters in files.
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
As the best anwser have writed using XMLHttpResponse
except window.open
, and I make the abstracts-anwser as a instance.
The main Js file is download.js
Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:
static {
try {
... your init code here
} catch (Throwable t) {
LOG.error("Failure during static initialization", t);
throw t;
}
}
I encountered this error with an Azure DevOps Services (MS-hosted) build pipeline on a TFVC repo.
In my case, I was working within a branch and had accidentally added the reference from the package folder in trunk instead of from the branch. Once I added the reference from within the branch, it started compiling successfully.
I.e., while working on \branch-beta\sierra.csproj, I accidentally referenced \trunk\packages\delta.dll. Obviously, I needed to reference \branch-beta\packages\delta.dll instead. The mixup occurred because the path is not prominently displayed in the Add Reference window and I didn’t check carefully enough.
Another ordinary simple way this is good if there are few options in select box
<select name="job_status">
<option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}} value="unemployed">Unemployed</option>
<option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>
</select>
my choice was to add a td
between the two td
tags and set the width
to 25px
. It can be more or less to your liking. This may be cheesy but it is simple and it works.
Just right click on the name you want to change (this could be namespace or whatever else) and select Refactor->Rename...
Enter new name, leave location as [Global Namespace], check preview if you want and you're done!
I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.
Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)
Set column max width using:
pd.set_option('max_colwidth', 800)
This particular statement sets max width to 800px, per column.
I have managed to do it with the following css combination:
text-align: justify;
text-align-last: justify;
text-justify: inter-word;
Two ways to do that..
Option 1:
1. Go to "Start" -> "Run".
2. Write "CMD" and press on "Enter" key.
3. Write the command "net statistics server" and press on "Enter" key.
4. The line that start with "Statistics since …" provides the time that the server was up from.
The command "net stats srv" can be use instead.
Option 2:
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher
http://support.microsoft.com/kb/232243
Hope it helped you!!
I found the answer in pure sed supplied by this question (admittedly, posted after this question was posted). This does exactly what you asked, solely in sed:
result=\`echo "$pid" | sed '/./ { s/pid:\ //g; }'\``
The dot in sed '/./
) is whatever you want to match. Your question is exactly what I was attempting to, except in my case I wanted to match a specific line in a file and then uncomment it. In my case it was:
# Uncomment a line (edit the file in-place):
sed -i '/#\ COMMENTED_LINE_TO_MATCH/ { s/#\ //g; }' /path/to/target/file
The -i
after sed
is to edit the file in place (remove this switch if you want to test your matching expression prior to editing the file).
(I posted this because I wanted to do this entirely with sed as this question asked and none of the previous answered solved that problem.)
You can limit the scope of a playbook by changing the hosts header in its plays without relying on your special host label ‘local’ in your inventory. Localhost does not need a special line in inventories.
- name: run on all except local
hosts: all:!local
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
With Swift 5, you can choose one of the two following Playground code samples in order to animate your UILabel
's text changes with some cross dissolve animation.
UIView
's transition(with:duration:options:animations:completion:)
class methodimport UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
let animation = {
self.label.text = self.label.text == "Car" ? "Plane" : "Car"
}
UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve, animations: animation, completion: nil)
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
CATransition
and CALayer
's add(_:forKey:)
methodimport UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
let animation = CATransition()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
// animation.type = CATransitionType.fade // default is fade
animation.duration = 2
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
label.layer.add(animation, forKey: nil) // The special key kCATransition is automatically used for transition animations
label.text = label.text == "Car" ? "Plane" : "Car"
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
I am adding it so that someone in a similar situation might find it helpful.
So, even after multiDexEnabled = true
I was getting the same error. I had no duplicate libraries. None of the above solutions worked. Upon reading the error log, I found OutOfMemError
issue to be the primary reason and thought of changing the heap size
somehow. Hence, this -
dexOptions {
preDexLibraries = false
javaMaxHeapSize "4g"
}
Where "4g" means HeapSize
of 4 GB. And it worked! I hope it does for you too.
Here is what I did and it worked perfectly for what I was looking to do:
Dim StatusDate As String
StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")
If StatusDate = " " Then
MessageBox.Show("You must enter a Status date to continue.")
Exit Sub
ElseIf StatusDate = "" Then
Exit Sub
End If
This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""
From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.
I prefer to do this in one line of code.
my_dict = {} my_dict[some_key] = my_dict.get(some_key, 0) + 1
Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.
Install it by running
python setup.py install
Better yet, you can download from github. Install git via apt-get install git
and then follow this steps:
git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install
I was looking for the same thing for a quick operation and found this question. I needed both 32-bit and 64-bit versions.
This is an older version but the links are from the Microsoft servers, it should be safe. The link for 32-bit version is also in a previous answer but the version number i get on the install is different, maybe the same link is updated with a newer version since 2013.
Cheksums are generated both locally and on VirusTotal, they match.
Debugging Tools for Windows (x64) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi (SHA-256:2e491bb98850abf9b9d2627185b57e048ba9b2410d68303698ac68c2daad9e5d)
Debugging Tools for Windows (x86) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi (SHA-256:5a0f43281e51405408a043e2f94dd51782ef29671307d3538cfdff5b0e69d115)
I tested the 64 bit debugger with a 64 bit program that was compiled some years ago (~2012) and it works. Test is done on Windows 10 Pro 64 bit (v2004 Build 19041.207).
git reset --hard HEAD^
Use the above command to revert merge changes.
EXP (export) and IMP (import) are the two tools you need. It's is better to try to run these on the command line and on the same machine.
It can be run from remote, you just need to setup you TNSNAMES.ORA
correctly and install all the developer tools with the same version as the database. Without knowing the error message you are experiencing then I can't help you to get exp/imp to work.
The command to export a single user:
exp userid=dba/dbapassword OWNER=username DIRECT=Y FILE=filename.dmp
This will create the export dump file.
To import the dump file into a different user schema, first create the newuser in SQLPLUS:
SQL> create user newuser identified by 'password' quota unlimited users;
Then import the data:
imp userid=dba/dbapassword FILE=filename.dmp FROMUSER=username TOUSER=newusername
If there is a lot of data then investigate increasing the BUFFERS
or look into expdp/impdp
Most common errors for exp and imp are setup. Check your PATH
includes $ORACLE_HOME/bin
, check $ORACLE_HOME
is set correctly and check $ORACLE_SID
is set
Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.
(Or create your own console.log() which just returns false.)
Folks, use strncpy(), strncat(), or snprintf().
Exceeding your buffer space will trash whatever else follows in memory!
(And remember to allow space for the trailing null '\0' character!)
@JustinCave - The "when value_error" replacement for "when others" is a nice refinement to your approach above. This slight additional tweak, while conceptually the same, removes the requirement for the definition of and consequent memory allocation to your l_num variable:
function validNumber(vSomeValue IN varchar2)
return varchar2 DETERMINISTIC PARALLEL_ENABLE
is
begin
return case when abs(vSomeValue) >= 0 then 'T' end;
exception
when value_error then
return 'F';
end;
Just a note also to anyone preferring to emulate Oracle number format logic using the "riskier" REGEXP approach, please don't forget to consider NLS_NUMERIC_CHARACTERS and NLS_TERRITORY.
I just animated the <li>
element instead of the whole container:
<style>
.menu {
border: solid;
}
.menu ul li {
height: 0px;
transition: height 0.3s;
overflow: hidden;
}
button:hover ~ .wrapper .menu ul li,
button:focus ~ .wrapper .menu ul li,
.menu:hover ul li {
height: 20px;
}
</style>
<button>Button</button>
<div class="wrapper">
<div class="menu">
<ul>
<li>menuitem</li>
<li>menuitem</li>
<li>menuitem</li>
<li>menuitem</li>
<li>menuitem</li>
<li>menuitem</li>
</ul>
</div>
</div>
you can add ul: margin 0;
to have 0 height.
You override __hash__
if you want special hash-semantics, and __cmp__
or __eq__
in order to make your class usable as a key. Objects who compare equal need to have the same hash value.
Python expects __hash__
to return an integer, returning Banana()
is not recommended :)
User defined classes have __hash__
by default that calls id(self)
, as you noted.
There is some extra tips from the documentation.:
Classes which inherit a
__hash__()
method from a parent class but change the meaning of__cmp__()
or__eq__()
such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting__hash__ = None
in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raise TypeError).
Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp
If that's not an option for any reason, you could try giving the list items classes:
<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>
Then in your css:
li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/
If you're importing a third-party module 'foo'
that doesn't provide any typings, either in the library itself, or in the @types/foo
package (generated from the DefinitelyTyped repository), then you can make this error go away by declaring the module in a file with a .d.ts
extension. TypeScript looks for .d.ts
files in the same places that it will look for normal .ts
files: as specified under "files", "include", and "exclude" in the tsconfig.json
.
// foo.d.ts
declare module 'foo';
Then when you import foo
it'll just be typed as any
.
Alternatively, if you want to roll your own typings you can do that too:
// foo.d.ts
declare module 'foo' {
export function getRandomNumber(): number
}
Then this will compile correctly:
import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number
You don't have to provide full typings for the module, just enough for the bits that you're actually using (and want proper typings for), so it's particularly easy to do if you're using a fairly small amount of API.
On the other hand, if you don't care about the typings of external libraries and want all libraries without typings to be imported as any
, you can add this to a file with a .d.ts
extension:
declare module '*';
The benefit (and downside) of this is that you can import absolutely anything and TS will compile.
Building off of ngoozeff
's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:
cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
&>/dev/null
sets the command’s stdout
and stderr
to /dev/null
instead of inheriting them from the parent process. &
makes the shell run the command in the background. disown
removes the “current” job, last one stopped or put in the background, from under the shell’s job control.In some shells you can also use &!
instead of & disown
; they both have the same effect. Bash doesn’t support &!
, though.
Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}"
rather than "${cmd}"
:
cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;
If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.
Here's a function for it:
#!/bin/bash
# Run a command in the background.
_evalBg() {
eval "$@" &>/dev/null & disown;
}
cmd="google-chrome";
_evalBg "${cmd}";
This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :
function debugToConsole($msg) {
echo "<script>console.log(".json_encode($msg).")</script>";
}
Edit : Added json_encode
to the echo
statement. This will prevent your script from breaking if there are quotes in your $msg
variable.
If you want the file from a particular commit (any branch) , say 06f8251f
git checkout 06f8251f path_to_file
for example , in windows:
git checkout 06f8251f C:\A\B\C\D\file.h
One note is that you can also use Boost.Assign:
using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope
void something()
{
map<int,int> my_map = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
}
we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.
The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.
df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
@implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
@end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
Super Key : Super key is a set of one or more attributes whose values identify tuple in the relation uniquely.
Candidate Key : Candidate key can be defined as a minimal subset of super key. In some cases , candidate key can not alone since there is alone one attribute is the minimal subset. Example,
Employee(id, ssn, name, addrress)
Here Candidate key is (id, ssn) because we can easily identify the tuple using either id or ssn . Althrough, minimal subset of super key is either id or ssn. but both of them can be considered as candidate key.
Primary Key : Primary key is a one of the candidate key.
Example : Student(Id, Name, Dept, Result)
Here
Super Key : {Id, Id+Name, Id+Name+Dept} because super key is set of attributes .
Candidate Key : Id because Id alone is the minimal subset of super key.
Primary Key : Id because Id is one of the candidate key
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
The constructor is called only once, so you can safely do what you want, however the disadvantage of calling methods from within the constructor, rather than directly, is that you don't get direct feedback if the method fails. This gets more difficult the more methods you call.
One solution is to provide methods that you can call to query the 'health' of the object once it's been constructed. For example the method isConfigOK()
can be used to see if the config read operation was OK.
Another solution is to throw exceptions in the constructor upon failure, but it really depends on how 'fatal' these failures are.
class A
{
Map <String,String> config = null;
public A()
{
readConfig();
}
protected boolean readConfig()
{
...
}
public boolean isConfigOK()
{
// Check config here
return true;
}
};
Try
git checkout <commit hash>
git checkout -b new_branch
The commit should only exist once in your tree, not in two separate branches.
This allows you to check out that specific commit and name it what you will.
You can use:
if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
{
//do code here
}
or
if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
{
//do code here
}
Need to do normal
forever start script.js
to start, and to check console/error logs use
forever logs
this will print list of all logs being stored by forever
and then you can use tail -f /path/to/logs/file.log
and this will print live logs to your window. hit ctrl+z to stop logs print.
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):
=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
column_name | data_type
--------------------+-----------
id | integer
default_printer_id | integer
master_host_enable | boolean
(3 rows)
Slack has a cool way of making tabs small viewport friendly on some of their admin pages. I made something similar using bootstrap. It's kind of a tabs ? dropdown.
Demo: http://jsbin.com/nowuyi/1
Here's what it looks like on a big viewport:
Here's how it looks collapsed on a small viewport:
Here's how it looks expanded on a small viewport:
the HTML is exactly the same as default bootstrap tabs.
There is a small JS snippet, which requires jquery (and inserts two span elements into the DOM):
$.fn.responsiveTabs = function() {
this.addClass('responsive-tabs');
this.append($('<span class="glyphicon glyphicon-triangle-bottom"></span>'));
this.append($('<span class="glyphicon glyphicon-triangle-top"></span>'));
this.on('click', 'li.active > a, span.glyphicon', function() {
this.toggleClass('open');
}.bind(this));
this.on('click', 'li:not(.active) > a', function() {
this.removeClass('open');
}.bind(this));
};
$('.nav.nav-tabs').responsiveTabs();
And then there is a lot of css (less):
@xs: 768px;
.responsive-tabs.nav-tabs {
position: relative;
z-index: 10;
height: 42px;
overflow: visible;
border-bottom: none;
@media(min-width: @xs) {
border-bottom: 1px solid #ddd;
}
span.glyphicon {
position: absolute;
top: 14px;
right: 22px;
&.glyphicon-triangle-top {
display: none;
}
@media(min-width: @xs) {
display: none;
}
}
> li {
display: none;
float: none;
text-align: center;
&:last-of-type > a {
margin-right: 0;
}
> a {
margin-right: 0;
background: #fff;
border: 1px solid #DDDDDD;
@media(min-width: @xs) {
margin-right: 4px;
}
}
&.active {
display: block;
a {
@media(min-width: @xs) {
border-bottom-color: transparent;
}
border: 1px solid #DDDDDD;
border-radius: 2px;
}
}
@media(min-width: @xs) {
display: block;
float: left;
}
}
&.open {
span.glyphicon {
&.glyphicon-triangle-top {
display: block;
@media(min-width: @xs) {
display: none;
}
}
&.glyphicon-triangle-bottom {
display: none;
}
}
> li {
display: block;
a {
border-radius: 0;
}
&:first-of-type a {
border-radius: 2px 2px 0 0;
}
&:last-of-type a {
border-radius: 0 0 2px 2px;
}
}
}
}
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
Even easier, just CSS can resolve the problem:
input[type="text"], input[type="password"], textarea, select {
width: 200px;
border: 1px solid;
border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
background: #FFF;
padding: 8px 5px;
font: 16px Arial, Tahoma, Helvetica, sans-serif;
-moz-box-shadow: 0 0 5px #C0C0C0;
-moz-border-radius: 5px;
-webkit-box-shadow: 0 0 5px #C0C0C0;
-webkit-border-radius: 5px;
box-shadow: 0 0 5px #C0C0C0;
border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus {
border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
outline: none;
-moz-box-shadow: 0 0 10px #B6D5F7;
-webkit-box-shadow: 0 0 10px #B6D5F7;
box-shadow: 0 0 10px #B6D5F7;
}
You can, the question in my mind is more should you. Right from the beginning, I'll say that there is no hard and fast answer. Do the right thing for your current situation.
To me inheritance implies an 'is-a' relationship. Imagine a dog class, which can be extended by more specialized sub types (Alsatian, Poodle, etc). In this case making the dog class abstract may be the right thing to do since sub-types are dogs. Now let's imagine that dogs need a collar. In this case inheritance doesn't make sense: it's nonsense to have a 'is-a' relationship between dogs and collars. This is definitely a 'has-a' relationship, collar is a collaborating object. Making collar abstract just so that dogs can have one doesn't make sense.
I often find that abstract classes with no abstract methods are really expressing a 'has-a' relationship. In these cases I usually find that the code can be better factored without using inheritance. I also find that abstract classes with no abstract method are often a code smell and at the very least should lead to questions being raised in a code review.
Again, this is entirely subjective. There may well be situations when an abstract class with no abstract methods makes sense, it's entirely up to interpretation and justification. Make the best decision for whatever you're working on.
You may try this one
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextAppearance(R.style.Lato_Bold);
} else {
textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
}
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
Depends on what your target browsers are. In newer ones it's as simple as:
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0 0 5px #fff;
For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
You can create a function for it:
typedef struct {
int id;
char name;
} employee;
void set_iv(employee *em);
int main(){
employee em0; set_iv(&em0);
}
void set_iv(employee *em){
(*em).id = 0;
(*em).name = "none";
}
Weak entity exists to solve the multi-valued attributes problem.
There are two types of multi-valued attributes. One is the simply many values for an objects such as a "hobby" as an attribute for a student. The student can have many different hobbies. If we leave the hobbies in the student entity set, "hobby" would not be unique any more. We create a separate entity set as hobby. Then we link the hobby and the student as we need. The hobby entity set is now an associative entity set. As to whether it is weak or not, we need to check whether each entity has enough unique identifiers to identify it. In many opinion, a hobby name can be enough to identify it.
The other type of multi-valued attribute problem does need a weak entity to fix it. Let's say an item entity set in a grocery inventory system. Is the item a category item or the actually item? It is an important question, because a customer can buy the same item at one time and at a certain amount, but he can also buy the same item at a different time with a different amount. Can you see it the same item but of different objects. The item now is a multi-valued attribute. We solve it by first separate the category item with the actual item. The two are now different entity sets. Category item has descriptive attributes of the item, just like the item you usually think of. Actual item can not have descriptive attributes any more because we can not have redundant problem. Actual item can only have date time and amount of the item. You can link them as you need. Now, let's talk about whether one is a weak entity of the other. The descriptive attributes are more than enough to identify each entity in the category item entity set. The actual item only has date time and amount. Even if we pull out all the attributes in a record, we still cannot identify the entity. Think about it is just time and amount. The actual item entity set is a weak entity set. We identify each entity in the set with the help of duplicate prime key from the category item entity set.
Another important aspect that influences the class name returned from String(describing: type(of: self))
is Access Control.
Consider the following example, based on Swift 3.1.1, Xcode 8.3.3 (July 2017)
func printClassNames() {
let className1 = SystemCall<String>().getClassName()
print(className1) // prints: "SystemCall<String>"
let className2 = DemoSystemCall().getClassName()
print(className2) // prints: "DemoSystemCall"
// private class example
let className3 = PrivateDemoSystemCall().getClassName()
print(className3) // prints: "(PrivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)"
// fileprivate class example
let className4 = FileprivateDemoSystemCall().getClassName()
print(className4) // prints: "(FileprivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)"
}
class SystemCall<T> {
func getClassName() -> String {
return String(describing: type(of: self))
}
}
class DemoSystemCall: SystemCall<String> { }
private class PrivateDemoSystemCall: SystemCall<String> { }
fileprivate class FileprivateDemoSystemCall: SystemCall<String> { }
As you can see, all classes in this example have different levels of access control which influence their String
representation. In case the classes have private
or fileprivate
access control levels, Swift seems to append some kind of identifier related to the "nesting" class of the class in question.
The result for both PrivateDemoSystemCall
and FileprivateDemoSystemCall
is that the same identifier is appended because they both are nested in the same parent class.
I have not yet found a way to get rid of that, other than some hacky replace or regex function.
Just my 2 cents.
If you would like to replace but still keeping the style of previous str. It is possible.
For example: highlight the string "test asdasd TEST asd tEst asdasd".
sentence = "test asdasd TEST asd tEst asdasd"
result = re.sub(
'(test)',
r'<b>\1</b>', # \1 here indicates first matching group.
sentence,
flags=re.IGNORECASE)
test asdasd TEST asd tEst asdasd
In Bootstrap, the default width of modal-dialog
is 600px
. But you can explicitly change its width. For instance, if you would like to maximize its width to the value of your choice, 800px
for instance, you do as following:
.modal-dialog {
width: 800px;
margin: 30px auto;
}
Note: This change sets to all modal dialog you use in your application. Also, my suggestion is it is best to have your own CSS rules defined and not to touch the core of the framework.
If you only want it to be set for specific modal dialog, use your own catchy class name as modal-800
whose width is set to 800px
, as following:
HTML
<div class="modal">
<div class="modal-dialog modal-800">
<div class="modal-content">
</div>
</div>
</div>
CSS
.modal-dialog.modal-800 {
width: 800px;
margin: 30px auto;
}
Likewise, you can have class name as based on the width size like modal-700
whose width is 700px
.
Hope it's helpful!
I wanted to support apps pre api 23 and instead of using checkSelfPermission
I used a try / catch
try {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException e) {
dialogGPS(this.getContext()); // lets the user know there is a problem with the gps
}
attachedCompanyIDs is one big string, so mysql try to find company in this its cast to integer
when you use where in
so if comapnyid = 1 :
companyID IN ('1,2,3')
this is return true
but if the number 1 is not in the first place
companyID IN ('2,3,1')
its return false
Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.
Format the picture and in the Properties tab select "Move but don't size with cells"
Now you can sort the data table by any column and the pictures will stay with the respective data.
This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627
I had to do this. this is a bit of hackery. not suggested.
but i found this very helpful
I made extension and struct
ViewController Extension + Struct
import UIKit
struct viewGlobal{
static var bottomConstraint : NSLayoutConstraint = NSLayoutConstraint()
}
extension UIViewController{ //keyboardHandler
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func listenerKeyboard(bottomConstraint: NSLayoutConstraint) {
viewGlobal.bottomConstraint = bottomConstraint
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
//Dismiss Keyboard
@objc func dismissKeyboard() {
view.endEditing(true)
}
@objc func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = keyboardHeight
}
}
@objc func keyboardWillHide(notification:NSNotification) {
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = 0
}
}
}
Usage:
get most bottom constraint
@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // default 0
call the function inside viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
listenerKeyboard(bottomConstraint: bottomConstraint)
// Do any additional setup after loading the view.
}
Hope this help.
-you keyboard will now auto close when user tap outside of textfield and
-it will push all view to above keyboard when keyboard appear.
-you could also used dismissKeyboard() when ever you need it
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
Quick & Dirty: I know it's not the most elegant way, but I usually just added a zero to it and test the result. like so:
function isInteger {
[ $(($1+0)) != 0 ] && echo "$1 is a number" || echo "$1 is not a number"
}
x=1; isInteger $x
x="1"; isInteger $x
x="joe"; isInteger $x
x=0x16 ; isInteger $x
x=-32674; isInteger $x
$(($1+0)) will return 0 or bomb if $1 is NOT an integer. for Example:
function zipIt { # quick zip - unless the 1st parameter is a number
ERROR="not a valid number. "
if [ $(($1+0)) != 0 ] ; then # isInteger($1)
echo " backing up files changed in the last $1 days."
OUT="zipIt-$1-day.tgz"
find . -mtime -$1 -type f -print0 | xargs -0 tar cvzf $OUT
return 1
fi
showError $ERROR
}
NOTE: I guess I never thought to check for floats or mixed types that will make the entire script bomb... in my case, I didn't want it go any further. I'm gonna play around with mrucci's solution and Duffy's regex - they seem the most robust within the bash framework...
In our case it turned out that the error happened because we have a custom filter
in our application which does HttpServletResponse sendRedirect()
to other url.
For some reason, the redirection is not closing the keep-alive
status of the connection, hence the timeout exception.
We checked with Tomcat Docs and when we disabled the maxKeepAliveRequests
by setting it's value to 1
and the error stopped showing up.
For now we do not have the actual solution to the error.
You need to declare the content within <span class="class_name"></span>
. After it the line will be break.
\A
means line feed character.
.class_name::after {
content: "\A";
white-space: pre;
}
If your method is void and you want to check for an exception, you could use expected
:
https://weblogs.java.net/blog/johnsmart/archive/2009/09/27/testing-exceptions-junit-47
The easiest way of doing this will be to use wifi of course. You will need to determine if your wifi base acts as a hub or a switch. If it acts as a hub then just connect your windows pc to it and wireshark should be able to see all the traffic from the iPhone. If it is a switch then your easiest bet will be to buy a cheap hub and connect the wan side of your wifi base to the hub and then connect your windows pc running wireshark to the hub as well. At that point wireshark will be able to see all the traffic as it passes over the hub.
Within your BS4 project, if you are able to compile SASS code, you can take advantage of creating a mixin to manage the color scheme of tooltips from any direction.
Here's one of many ways in which you can implement this:
Create a list and loop over it to cover all 4 possible directions
//define a color
$m-color-blue: #004c97;
//create a mixin with parameters and default value
@mixin m-tooltip-color-direction($name:'.mtootltip', $color:$m-color-blue) {
//reference your custom class name
#{$name} {
.tooltip-inner {
background-color: $color;
}
//create a list of possible directions
$directions: top bottom left right;
//loop through the list
@each $direction in $directions {
&.bs-tooltip-#{$direction} .arrow:before,
.bs-tooltip-auto[x-placement^="$direction"] .arrow:before {
border-#{$direction}-color: $color !important;
}
}
}
}
Within your main .scss file call your mixin like so:
@include m-tooltip-color-direction('.mtooltip', $m-color-blue);
Finally, add a BS4 tooltip to your layout, and give it a custom class for flexibility. This BS4 resource talks about using template as an option. We'll be using that to add our custom class.
The following example adds a tooltip on an info icon badge:
<span class="badge badge-pill badge-primary" data-toggle="tooltip" data-placement="right" data-html="true" data-template="<div class='tooltip mtooltip' role='tooltip'><div class='arrow'></div><div class='tooltip-inner'></div></div>" title="<h1 class='text-white'>Tooltip</h1> on bottom">i</span>
With this setup you can adjust the class name, color and direction of your tooltip without touching your original mixin. How cool is that :)
Hope this helps!
A couple of things wrong here.
Do you really want to open and close the connection for every single log entry?
Shouldn't you be using SqlCommand
instead of SqlDataAdapter
?
The data adapter (or SqlCommand
) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).
I highly recommend a C# / SQL Server tutorial.
This solved it for me
AppRegistry.registerComponent('main', () => App);
So my index.js
file
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('main', () => App);
And my package.json
file:
"dependencies": {
"react": "^16.13.1",
"react-dom": "~16.9.0",
"react-native": "~0.61.5"
},
As DOC says, you can pass data to the handler as next:
// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
// access element's id where click occur
alert( event.target.id );
}
For people not wanting a complicated answer, I used Ng-If to solve this for something similar:
<div style="text-align: center;">
<a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
<span ng-if="ctrl.something == null">I'm just text</span>
</div>
Using the selectedOptions
property:
var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
It works in all browsers except Internet Explorer.
If you use dplyr
package you can do:
library(dplyr)
filter(df, aged <= laclen)
vim -c 'execute "silent !echo " . &fileencoding | q' {filename}
aliased somewhere in my bash configuration as
alias vic="vim -c 'execute \"silent \!echo \" . &fileencoding | q'"
so I just type
vic {filename}
On my vanilla OSX Yosemite, it yields more precise results than "file -I":
$ file -I pdfs/udocument0.pdf
pdfs/udocument0.pdf: application/pdf; charset=binary
$ vic pdfs/udocument0.pdf
latin1
$
$ file -I pdfs/t0.pdf
pdfs/t0.pdf: application/pdf; charset=us-ascii
$ vic pdfs/t0.pdf
utf-8
Since this keeps coming up in search results for making git and github work with SSH on Windows (and because I didn't need anything from the guides above), I'm adding the following, simple solution.
(Microsoft says they are working on adding SSH to Visual Studio, and GitHub for Windows still doesn't support SSH...)
1. I installed "git for Windows" (which includes ssh and a bash shell)
https://git-scm.com/download/win
2. From the included bash shell (which, for me, was installed at: C:\Program Files\Git\git-bash.exe
)
cd
to the root level of where you want your repo saved (something like: C:\code\github\
), and
Type:
eval $(ssh-agent -s) && ssh-add "C:\Users\YOURNAMEHERE\.ssh\github_rsa"
3. Type: (the SSH link from the repo)
git clone [email protected]:RepoName/Project.git
In a somewhat related way I was trying to add a remote tracking branch to an existing branch, but did not have access to that remote repository on the system where I wanted to add that remote tracking branch on (because I frequently export a copy of this repo via sneakernet to another system that has the access to push to that remote). I found that there was no way to force adding a remote branch on the local that hadn't been fetched yet (so local did not know that the branch existed on the remote and I would get the error: the requested upstream branch 'origin/remotebranchname' does not exist
).
In the end I managed to add the new, previously unknown remote branch (without fetching) by adding a new head file at .git/refs/remotes/origin/remotebranchname
and then copying the ref (eyeballing was quickest, lame as it was ;-) from the system with access to the origin repo to the workstation (with the local repo where I was adding the remote branch on).
Once that was done, I could then use git branch --set-upstream-to=origin/remotebranchname
If you write HTML into javascript anywhere, it will think the HTML is written in javascript. The best way to include HTML in JavaScript is to write the HTML code on the page. The browser can't display HTML tags, so the browser will recognize the HTML and write this code in HTML.
document.write("<p>Hello World!</p>");
Though if you would like to write HTML on a function, GetElementById
is the best:
function functionName() {
document.getElementById(" the id of the HTML element to be written in ").innerHTML = "whatever you want to say"
}
Hope this helps!
See this CodePen https://codepen.io/ella301/pen/vYLNmVg which I created. I used 3 CSS functions min, max and calc to make sure the left and right paddings are fluid between minimum 20px and maximum 120px.
padding: 20px max(min(120px, calc((100% - 1198px) / 2)), 20px);
Hope it helps!
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
See this answer: Source
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source
This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.
It seems to have the System's timezone to be set is possible indeed.
Get the OS local time zone from the shell. In psql:
=> \! date +%Z
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here
Extract and convert all Excel worksheets into CSV files using PowerShell
is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.
Once the Excel files have been converted to CSV the data import is much less complicated.
The following worked for me (Windows 7):
oradim -shutdown -sid enter_sid_here
oradim -startup -sid enter_sid_here
(with enter_sid_here
replaced by the SID)
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
#include <math.h>
double round(double x);
float roundf(float x);
Don't forget to link with -lm. See also ceil(), floor() and trunc().
This is how I would write using more functional way
. Here is the code:
new List<Money>()
{
new Money() { Amount = 10, Type = "US"},
new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
Use the "form" attribute, if you want to save your markup:
<form method="GET" id="my_form"></form>
<table>
<tr>
<td>
<input type="text" name="company" form="my_form" />
<button type="button" form="my_form">ok</button>
</td>
</tr>
</table>
(*Form fields outside of the < form > tag)
No.
But how about:
$a="test";
if("test"==$a)
{
if ($someOtherCondition)
{
echo "yes";
}
}
echo "finish";
It's the equivalent of a space character, so strip it
print(string.strip()) # no more xa0
I use these two commands and I can see the files to change.
First executing git fetch, it gives output like this (part of output):
... 72f8433..c8af041 develop -> origin/develop ...
This operation gives us two commit IDs, first is the old one, and second will be the new.
Then compare these two commits using git diff
git diff 72f8433..c8af041 | grep "diff --git"
This command will list the files that will be updated:
diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php
diff --git a/app/view/yyyy.php b/app/view/yyyy.php
For example app/controller/xxxx.php and app/view/yyyy.php will be updated.
Comparing two commits using git diff prints all updated files with changed lines, but with grep it searches and gets only the lines contains diff --git from output.
I thought up a rather elegant solution (IMHO), so I can't resist posting it:
from bisect import bisect_left
class Interpolate(object):
def __init__(self, x_list, y_list):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
x_list = self.x_list = map(float, x_list)
y_list = self.y_list = map(float, y_list)
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
self.slopes = [(y2 - y1)/(x2 - x1) for x1, x2, y1, y2 in intervals]
def __getitem__(self, x):
i = bisect_left(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
I map to float
so that integer division (python <= 2.7) won't kick in and ruin things if x1
, x2
, y1
and y2
are all integers for some iterval.
In __getitem__
I'm taking advantage of the fact that self.x_list is sorted in ascending order by using bisect_left
to (very) quickly find the index of the largest element smaller than x
in self.x_list
.
Use the class like this:
i = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
# Get the interpolated value at x = 4:
y = i[4]
I've not dealt with the border conditions at all here, for simplicity. As it is, i[x]
for x < 1
will work as if the line from (2.5, 4) to (1, 2) had been extended to minus infinity, while i[x]
for x == 1
or x > 6
will raise an IndexError
. Better would be to raise an IndexError in all cases, but this is left as an exercise for the reader. :)
I did solved using this jquery for Github
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469
In your example problem is passed table name pattern in getTables function of DatabaseMetaData.
Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.
DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()
From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.
public class DBUtility {
private static final String[] TYPES = {"TABLE", "VIEW"};
public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
try {
DatabaseMetaData meta = jdbcConnection.getMetaData();
ResultSet rs = null;
try {
if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
} else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
|| (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
rs = meta.getTables(
StringHelper.toUpperCase(catalog),
StringHelper.toUpperCase(schema),
StringHelper.toUpperCase(tableNamePattern),
TYPES
);
}
else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
|| (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
rs = meta.getTables(
StringHelper.toLowerCase( catalog ),
StringHelper.toLowerCase(schema),
StringHelper.toLowerCase(tableNamePattern),
TYPES
);
}
else {
rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
}
while ( rs.next() ) {
String tableName = rs.getString("TABLE_NAME");
System.out.println("table = " + tableName);
}
}
finally {
if (rs!=null) rs.close();
}
}
catch (SQLException sqlException) {
// TODO
sqlException.printStackTrace();
}
}
public static void main(String[] args) {
Connection jdbcConnection;
try {
jdbcConnection = DriverManager.getConnection("", "", "");
getTableMetadata(jdbcConnection, "tbl%", null, null, false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the $("body").append(r)
statement should be within the test
function, also there was misplaced "
in the test
method
function test() {
var r=$('<input/>').attr({
type: "button",
id: "field",
value: 'new'
});
$("body").append(r);
}
Demo: Fiddle
Update
In that case try a more jQuery-ish solution
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
$('#mybutton').one('click', function(){
var r=$('<input/>').attr({
type: "button",
id: "field",
value: 'new'
});
$("body").append(r);
})
})
</script>
</head>
<body>
<button id="mybutton">Insert after</button>
</body>
</html>
Demo: Plunker
May be the easy one to see the source:
In Android studio 2.3, Build -> Analyze APK -> Select the apk that you want to decompile
.
You will see it's source code.
Link for reference:
https://medium.com/google-developers/making-the-most-of-the-apk-analyzer-c066cb871ea2
I think you're using the best method, though you could optimize it to:
$("<div/>");
I'm surprised to find my solution wasn't listed here.
For me, I have an LG G3. The phone must be connected using LG's driver. I went to
Device Manager > uninstall MTP Driver
and immediately adb worked without 1 sec literally.
You can use casting:
<?php
$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);
$text = (string)$xml->child;
$text will be 'Hello World'
>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
You can shorten this with:
>>> c = (a < 3).astype(int)
for and mac OS user you can use Network Link Conditioner which could be downloaded from apple. set it as a AP on mac and any divices could connected it.
you can either use facebook open source tools ATC http://facebook.github.io/augmented-traffic-control/
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
You can use env package to manage your environment variables per project:
.env
file under the project directory and put all of your
variables there.require('dotenv').config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
This is a textbook case for a constructor function:
var myArray = [];
function myElement(id, value){
this.id = id
this.value = value
}
myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))
java.lang.String.split(String regex)
is what you are looking for.
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
My 2 cents on @K_Anas answer. I performed a simple test on finish() method. Listed important callback methods in activity life cycle
What I mean to say is that counterparts of the methods along with any methods in between are called when finish() is executed.
eg:
onCreate() counter part is onDestroy()
onStart() counter part is onStop()
onPause() counter part is onResume()
You can do something like this:
function writeFile(i){
var i = i || 0;
var fileName = 'a_' + i + '.jpg';
fs.exists(fileName, function (exists) {
if(exists){
writeFile(++i);
} else {
fs.writeFile(fileName);
}
});
}
=IIF(Fields!ADPAction.Value.ToString().ToUpper().Contains("FAIL"),"Red","White")
Also need to convert to upper case for comparision is binary test.
angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));
now for orientation of circular values to keep angle between 0 and 359 can be:
angle = angle + Math.ceil( -angle / 360 ) * 360
U can also use :
var query =
from t1 in myTABLE1List
join t2 in myTABLE1List
on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
join t3 in myTABLE1List
on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }
foreach (DataRow dr in ds.Tables[0].Rows)
{
//your code here
}
For a GOOD and definite solution see the Setting up Permissions
section in Installing and Configuring Symfony
section :
Setting up Permissions
One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.
- Use the same user for the CLI and the web server
In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).
- Using ACL on a system that supports chmod +a
Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ rm -rf app/cache/* $ rm -rf app/logs/* $ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs $ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
- Using ACL on a system that does not support chmod +a
Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
For Symfony 3 it would be:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
If this doesn't work, try adding -n option.
- Without using ACL
If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:
umask(0002); // This will let the permissions be 0775 // or umask(0000); // This will let the permissions be 0777
Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.
source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
int n = Integer.parseInt(m.group());
// append n to list
}
// convert list to array, etc
You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.
When my root view controller is embedded in a navigation controller:
UINavigationController * navigationController = (UINavigationController *)[[[[UIApplication sharedApplication] windows] firstObject] rootViewController];
RootViewController * rootVC = (RootViewController *)[[navigationController viewControllers] firstObject];
Remember that keyWindow
is deprecated.
I am not sure how this happened but I started to get this error in my internal submit form pages. So when ever I submit something I'm getting this error. But the problem is this website is almost working 5-6 years. I don't remember I made an important change.
None of the solutions worked for me.
I have setup a machine key with the Microsoft script and copied into my web.config
I have executed asp.net regiis script.
aspnet_regiis -ga "IIS APPPOOL\My App Pool"
Also tried to add this code into the page:
enableViewStateMac="false"
still no luck.
Any other idea to solve this issue?
UPDATE:
Finally I solved the issue. I had integrated my angular 4 component into my asp.net website. So I had added base href into my master page. So I removed that code and it is working fine now.
<base href="/" />
1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(_access);
// do work here, with exclusive access
}
Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.
Having Clause may come prior/before the group by clause.
Example: select * FROM test_std; ROLL_NO SNAME DOB TEACH
1 John 27-AUG-18 Wills
2 Knit 27-AUG-18 Prestion
3 Perl 27-AUG-18 Wills
4 Ohrm 27-AUG-18 Woods
5 Smith 27-AUG-18 Charmy
6 Jony 27-AUG-18 Wills
Warner 20-NOV-18 Wills
Marsh 12-NOV-18 Langer
FINCH 18-OCT-18 Langer
9 rows selected.
select teach, count() count from test_std having count() > 1 group by TEACH ;
TEACH COUNT
Langer 2 Wills 4
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping
as a meta-annotation. So:
Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:
@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)
Yes, there is such a way. You can create a meta annotation like following:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
@AliasFor(annotation = RequestMapping.class, attribute = "value")
String[] value() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "method")
RequestMethod[] method() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "params")
String[] params() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "headers")
String[] headers() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "consumes")
String[] consumes() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "produces")
String[] produces() default {};
}
Then you can use the default settings or even override them as you want:
@JsonRequestMapping(method = POST)
public String defaultSettings() {
return "Default settings";
}
@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
return json;
}
You can read more about AliasFor
in spring's javadoc and github wiki.
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
You need to look at upgrading your OS and Java. Java 5.0 is EOL but if you cannot update to Java 6, you could use the latest patch level 22!
32-bit Windows is limited to ~ 1.3 GB so you are doing well to se the maximum to 1.8. Note: this is a problem with continous memory, and as your system runs its memory space can get fragmented so it does not suprise me you have this problem.
A 64-bit OS, doesn't have this problem as it has much more virtual space, you don't even have to upgrade to a 64-bit version of java to take advantage of this.
BTW, in my experience, 32-bit Java 5.0 can be faster than 64-bit Java 5.0. It wasn't until many years later that Java 6 update 10 was faster for 64-bit.
The scalar formatter supports collecting the exponents. The docs are as follows:
class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter
Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.
your technique would be:
from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3)) # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)
To get the exponent displayed in the format x10^5
, instantiate the ScalarFormatter with useMathText=True
.
You could also use:
xfmt.set_useOffset(10000)
To get a result like this:
Run this:
Rails.application.eager_load!
Then
ActiveRecord::Base.descendants
To return a list of models/tables
table.classname td {
font-size: 90%;
}
worked for me. thanks.
CSS 3 introduces the background-size property, but support is not universal.
Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.
Another solution is you could use a background image to mimic the look of a left border
You might need to tweak for IE (as per usual) but it's worth a shot if that's the design you are going for.
Or you can do this without using Delay.
set /a "counter=0"
-> your for loop here
do (
statement1
statement2
call :increaseby1
)
:increaseby1
set /a "counter+=1"
Your group statement will group by group ID. For example, if you then write:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement>
which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
A repo may seem corrupted if you mix different git
versions.
Local repositories touched by new git versions aren't backwards-compatible with old git versions. New git repos look corrupted to old git versions (in my case git 2.28 broke repo for git 2.11).
Updating old git version may solve the problem.
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)
should do it for you. But I prefer ggplot2
and would suggest that for better graphics in R.
If you mean to change default directory for "Node.js command prompt", when you launch it, then (Windows case)
change the default path in the row which looks like
if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
with your path. It could be for example
if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"
if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:
cd c:/MyDirectory/
For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Keep in mind that you'll need a timeout on your JSONP request to catch failures.
Fastest way to do this is using "SELECT INTO" command e.g.
SELECT * INTO #TempTableName
FROM....
This will create a new table, you don't have to create it in advance.
If you are using MySQL, you can use order by FIELD(id, ...)
approach:
Company.findAll({
where: {id : {$in : companyIds}},
order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})
Keep in mind, it might be slow. But should be faster, than manual sorting with JS.
Bad idea when you know the field will be in a set range- 5 to 10 character for example. I think I'd only use max if I wasn't sure what the length would be. For example a telephone number would never be more than a certain number of characters.
Can you honestly say you are that uncertain about the approximate length requirements for every field in your table?
I do get your point though- there are some fields I'd certainly consider using varchar(max).
Interestingly the MSDN docs sum it up pretty well:
Use varchar when the sizes of the column data entries vary considerably. Use varchar(max) when the sizes of the column data entries vary considerably, and the size might exceed 8,000 bytes.
Are you thinking about something like this?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
(Have been studying these, a lot)
Candidate keys - A minimal column combination required to uniquely identify a table row.
Compound keys - 2 or more columns.
Sources:
https://en.wikipedia.org/wiki/Superkey
https://en.wikipedia.org/wiki/Candidate_key
https://en.wikipedia.org/wiki/Primary_key
https://en.wikipedia.org/wiki/Compound_key
use get
instead of load
// ...
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User) session.get(User.class, user_id);
} catch (Exception e) {
// ...
Calling .isoformat()
on a date
object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html
Above link is to create Python script for checking connectivity. You can use similar method and use:
ping -w 1 -c 1 "IP Address"
Command to create bash script.
Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.
CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.
If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.
I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.
Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?
In the latest and greatest Hibernate, I was able to resolve the dependency by including the hibernate-jpa-2.0-api-1.0.0.Final.jar within lib/jpa directory. I didn't find the ejb-persistence jar in the most recent download.
You have a JSON Lines format text file. You need to parse your file line by line:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.
Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.
If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.
Open the CSV file with a decent text editor like Notepad++ and add the following text in the first line:
sep=,
Now open it with excel again.
This will set the separator as a comma, or you can change it to whatever you need.
In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.
Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.
- we have added the
/js/**
pattern to the ResourceHandler, lets include thefoo.js
resource located in thewebapp/js/
directory- we have added the
/resources/static/**
pattern to the ResourceHandler, lets include thefoo.html
resource located in thewebapp/resources/
directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
registry.addResourceHandler("/resources/static/**")
.addResourceLocations("/resources/");
registry
.addResourceHandler("/js/**")
.addResourceLocations("/js/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new GzipResourceResolver())
.addResolver(new PathResourceResolver());
}
}
XML Configuration
<mvc:annotation-driven />
<mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
cache-period="60"/>
Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.
spring.mvc.static-path-pattern=/resources/static/**
#!/bin/bash
kernel="2.6.39";
distro="xyz";
cat > /etc/myconfig.conf << EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL
this does what you want.
When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
...
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)
The problem is that Tomcat can't find com.mysql.jdbc.Driver
. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib
directory).
allow from all will not work along with Require local. Instead, try Require ip xxx.xxx.xxx.xx
For Example:
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
Require ip 10.0.0.1
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
It is a duplicate of this question, with an answer that contains a time measurement of the different methods.
Conclusion: Use [void]
or > $null
.
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
unique random number from 0 to 9
int sum = 0;
int[] hue = new int[10];
for (int i = 0; i < 10; i++)
{
int m;
do
{
m = rand.Next(0, 10);
} while (hue.Contains(m) && sum != 45);
if (!hue.Contains(m))
{
hue[i] = m;
sum = sum + m;
}
}
You could possibly surround the span with another span, then simply test if the width of the original/inner span is greater than that of the new/outer span. Note that I say possibly -- it is roughly based on my situation where I had a span
inside of a td
so I don't actually know that if it will work with a span
inside of a span
.
Here though is my code for others who may find themselves in a position similar to mine; I'm copying/pasting it without modification even though it is in an Angular context, I don't think that detracts from the readability and the essential concept. I coded it as a service method because I needed to apply it in more than one place. The selector I've been passing in has been a class selector that will match multiple instances.
CaseService.applyTooltip = function(selector) {
angular.element(selector).on('mouseenter', function(){
var td = $(this)
var span = td.find('span');
if (!span.attr('tooltip-computed')) {
//compute just once
span.attr('tooltip-computed','1');
if (span.width() > td.width()){
span.attr('data-toggle','tooltip');
span.attr('data-placement','right');
span.attr('title', span.html());
}
}
});
}
Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99
.
public static class SocketExtensions
{
private const int BytesPerLong = 4; // 32 / 8
private const int BitsPerByte = 8;
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException)
{
return false;
}
}
/// <summary>
/// Sets the keep-alive interval for the socket.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="time">Time between two keep alive "pings".</param>
/// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
/// <returns>If the keep alive infos were succefully modified.</returns>
public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
{
try
{
// Array to hold input values.
var input = new[]
{
(time == 0 || interval == 0) ? 0UL : 1UL, // on or off
time,
interval
};
// Pack input into byte struct.
byte[] inValue = new byte[3 * BytesPerLong];
for (int i = 0; i < input.Length; i++)
{
inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
}
// Create bytestruct for result (bytes pending on server socket).
byte[] outValue = BitConverter.GetBytes(0);
// Write SIO_VALS to Socket IOControl.
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
}
catch (SocketException)
{
return false;
}
return true;
}
}
There's an experimental CSS property called text-stroke, supported on some browsers behind a -webkit prefix.
h1 {_x000D_
-webkit-text-stroke: 2px black; /* width and color */_x000D_
_x000D_
font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
Another possible trick would be to use four shadows, one pixel each on all directions, using property text-shadow
:
h1 {_x000D_
/* 1 pixel black shadow to left, top, right and bottom */_x000D_
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;_x000D_
_x000D_
font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
But it would get blurred for more than 1 pixel thickness.
df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1
Step-by-step explanation (from inner to outer):
df['ids']
selects the ids
column of the data frame (technically, the object df['ids']
is of type pandas.Series
)df['ids'].str
allows us to apply vectorized string methods (e.g., lower
, contains
) to the Seriesdf['ids'].str.contains('ball')
checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True
or False
about the existence of a 'ball' substring.df[df['ids'].str.contains('ball')]
applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.na = False
removes NA / NaN values from consideration; otherwise a ValueError may be returned.This should work in MySql
SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);
You wrote:
var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);
Why not this?
var styleNode = document.createElement("style");
document.head.appendChild(styleNode);
Henceforward you can append CSS rules easily to the HTML code:
styleNode.innerHTML = "h1 { background: red; }\n";
styleNode.innerHTML += "h2 { background: green; }\n";
...or directly to the DOM:
styleNode.sheet.insertRule("h1 { background: red; }");
styleNode.sheet.insertRule("h2 { background: green; }");
I expect this to work everywhere except archaic browsers.
Definitely works in Chrome in year 2019.
I had the same problem, and finally I found that I forgot to add the selenium-server-standalone-version.jar. I had only added the client jar, selenium-java-version.jar.
Another alternative:
No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.
So you can do this with Animation.REVERSE like this:
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);
then onAnimationEnd:
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//TODO: Run when animation start
}
@Override
public void onAnimationEnd(Animation animation) {
//TODO: Run when animation end
}
@Override
public void onAnimationRepeat(Animation animation) {
//TODO: Run when animation repeat
}
});
Try updating gradle dependency to 2.4. For that you need to go to
File -> Project Structure -> Project -> Gradle version
.
There you need to change from 2.2.1 to 2.4. Wait for new gradle version to be downloaded.
And you are ready to go.
If you are using jupiter and none of the answers work, consider verifying it is setup correctly:
test {
useJUnitPlatform()
outputs.upToDateWhen { false }
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}
And then try the accepted answers
Alternatively, If you are using Apache then you can use .htaccess
file to enforce your URLs to use https
prefix. On Laravel 5.4, I added the following lines to my .htaccess
file and it worked for me.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath
so that you could do something like this:
>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'
Rails provides a solution to this: shallow nesting.
I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.
In case the host
part is omitted it defaults to the wildcard symbol %
, allowing all hosts.
CREATE USER 'service-api';
GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'
SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'
I solved this question this way.
<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>
$scope.openTab = function() {
$scope.url = 'www.google.com';
}
As others have said, you can install a password cache helper. I mostly just wanted to post the link for other platforms, and not just Mac. I'm running a Linux server and this was helpful: Caching your GitHub password in Git
For Mac:
git credential-osxkeychain
Windows:
git config --global credential.helper wincred
Linux:
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)
You just need another layer in your php array:
$post_data = array(
'item' => array(
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
)
);
echo json_encode($post_data);
This is a very interesting bug. (In my opinion, it is a bug anyway) Nice find!
Regarding how to set it, I would recommend Camilo Martin's answer. But as to why, I'd like to explain this a bit if you guys don't mind.
In the CSS specs I found:
'padding'
Percentages: refer to width of containing block
… which is weird, but okay.
So, with a parent width: 210px
and a child padding-top: 50%
, I get a calculated/computed value of padding-top: 96.5px
– which is not the expected 105px
.
That is because in Windows (I'm not sure about other OSs), the size of common scrollbars is per default 17px × 100%
(or 100% × 17px
for horizontal bars). Those 17px
are substracted before calculating the 50%
, hence 50% of 193px = 96.5px
.
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
Php will evaluate what you wrote between the [] brackets.
$foo = array('eins', 'zwei', 'apples', 'oranges');
var_dump($foo[3-1]);
Will produce string(6) "apples"
, because it returns $foo[2].
If you want that as a string, put inverted commas around it.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.
(\s|\(|\.|,|^)bqr(\s|,|\)|$)
I had this problem and it was solved by following the code below
var _path=MyFile.FileName;
using (var stream = new FileStream
(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
// Your Code! ;
}
void DisplayBinary(unsigned int n)
{
int l = sizeof(n) * 8;
for (int i = l - 1 ; i >= 0; i--) {
printf("%x", (n & (1 << i)) >> i);
}
}
we can use \b as a word boundary and then; \b\d+\b
To expand on Konrad's comment:
As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined;
Because of this, functional code is generally easier to parallelize. Since there are (generally) no side effects of the functions, and they (generally) just act on their arguments, a lot of concurrency issues go away.
Functional programming is also used when you need to be capable of proving your code is correct. This is much harder to do with procedural programming (not easy with functional, but still easier).
Disclaimer: I haven't used functional programming in years, and only recently started looking at it again, so I might not be completely correct here. :)
If anyone doesn't understand how Array.sort()
works with integers, read this answer.
Alphabetical order:
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
const myArray = [104, 140000, 99];
myArray.sort();
console.log(myArray); // output is [104, 140000, 99]
Ascending order with array.sort(compareFunction)
:
const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
return a - b;
});
console.log(myArray); // output is [99, 104, 140000]
Explanation from w3schools:
compareFunction
defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.Example:
When comparing 40 and 100, the sort() method calls the compare function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
The sort function will sort 40 as a value lower than 100.
Descending order with array.sort(compareFunction)
:
const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
return b - a;
});
console.log(myArray); // output is [140000, 104, 99]
This time we calculated with b - a
(i.e., 100-40) which returns a positive value.
int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);
this code gives the output as b=3669 only you check it clearly.
With gawk, you can use the match
function to capture parenthesized groups.
gawk 'match($0, pattern, ary) {print ary[1]}'
example:
echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}'
outputs cd
.
Note the specific use of gawk which implements the feature in question.
For a portable alternative you can achieve similar results with match()
and substr
.
example:
echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'
outputs cd
.
In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).
See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)
Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.
span.bold(This name can be anything do not include parenthesis) { font-weight: bold; }
It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.
Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.
With SugarJS, you can do:
[1,2,3,4].last() // => 4
That means, your example does work out of the box:
var array = [1,2,3,4];
var lastEl = array.last(); // => 4