You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx
But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends
http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx
Your code also seems a bit strange, like you are nesting lists?
From a script (one that works):
CREATE DATABASE Northwind
ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
GO
obviously update the path:
C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA
To where your .mdf and .ldf reside.
This one
if [[ ! $(cat /etc/passwd | grep "sysa") ]]
Then echo " something"
exit 2
fi
@Adam Just add a function using onClick="getId()"
function getId(){console.log(this.event.target.id)}
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
Since the usage of CSS Grid is increasing, I would like to suggest align-self
to the element that is inside a grid container.
align-self
can contain any of the values: end
, self-end
, flex-end
for the following example.
#parent {_x000D_
display: grid;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
align-self: end;_x000D_
}_x000D_
_x000D_
/* Extra Styling for Snippet */_x000D_
_x000D_
#parent {_x000D_
height: 150px;_x000D_
background: #5548B0;_x000D_
color: #fff;_x000D_
padding: 10px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
background: #6A67CE;_x000D_
text-align: center;_x000D_
vertical-align: middle;_x000D_
line-height: 50px;_x000D_
}
_x000D_
<div id="parent">_x000D_
<!-- Other elements here -->_x000D_
<div id="child1">_x000D_
1_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
No, there is no way to do this with git show
. But it would certainly be nice sometimes, and it would probably be relatively easy to implement in the git source code (after all, you just have to tell it to not trim out what it thinks is extraneous output), so the patch to do so would probably be accepted by the git maintainers.
Be careful what you wish for, though; merging a branch with a one-line change that was forked three months ago will still have a huge diff versus the mainline, and so such a full diff would be almost completely unhelpful. That's why git doesn't show it.
My IIS 7.5 does not understand tag in web.config In VS 2010 it is underline that tag also. Check your config file accurate to find all underlined tags. I put it in the comment and error goes away.
The thing is you need to check whether the thread is running or not !?
Field:
private boolean runningThread = false;
In the thread:
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) Math.floor(speed));
if (!runningThread) {
return;
}
yourWork();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
If you want to stop the thread you should make the below field
private boolean runningThread = false;
Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf
returns a view of the string as a List
.
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
You want to pass the function object hi
to your loop()
function, not the result of a call to hi()
(which is None
since hi()
doesn't return anything).
So try this:
>>> loop(hi, 5)
hi
hi
hi
hi
hi
Perhaps this will help you understand better:
>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>
That is the HTML code. Anyone can use this:
<div class="card-header">Contact Information</div>
<div class="card-body" formArrayName="funds">
<div class="row">
<div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row">
<div class="form-group col-6">
<label>Type of Contact</label>
<select class="form-control" formControlName="fundName" type="text">
<option value="01">Balance Fund</option>
<option value="02">Equity Fund</option>
</select>
</div>
<div class="form-group col-12">
<label>Allocation</label>
<input class="form-control" formControlName="allocation" type="number">
<span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched &&
getContactsFormGroup(i).controls['allocation'].hasError('required')">
Allocation % is required! </span>
</div>
<div class="form-group col-12 text-right">
<button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>
Gnome terminal defaults to ControlShiftv
OSX terminal defaults to Commandv. You can also use CommandControlv to paste the text in escaped form.
Windows 7 terminal defaults to CtrlShiftInsert
Try the following
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];_x000D_
_x000D_
var myTotal = 0; // Variable to hold your total_x000D_
_x000D_
for(var i = 0, len = myData.length; i < len; i++) {_x000D_
myTotal += myData[i][1]; // Iterate over your first array and then grab the second element add the values up_x000D_
}_x000D_
_x000D_
document.write(myTotal); // 22 in this instance
_x000D_
the solution is configure the gmail preferences, access to no secure application
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.
You need to go to the GitHub page for your forked repository, and click on the “Settings” button.
Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.
From there, select placeholder (where placeholder is the dummy name for your new default branch).
Confirm that you want to change your default branch.
Now you can do (from the command line):
git push origin :master
Or, since 2012, you can delete that same branch directly on GitHub:
That was announced in Sept. 2013, a year after I initially wrote that answer.
For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.
Note: for BitBucket, Tum reports in the comments:
About the same for Bitbucket
Repo -> Settings -> Repository details -> Main branch
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningEDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
https://adoptopenjdk.net currently supports all distributions of JDK from version 8 onwards. For example https://adoptopenjdk.net/releases.html#x64_win
Here's an example of how I was able to use JDK version 8 with sdkmanager and much more: https://travis-ci.com/mmcc007/screenshots/builds/109365628
For JDK 9 (and I think 10, and possibly 11, but not 12 and beyond), the following should work to get sdkmanager working:
export SDKMANAGER_OPTS="--add-modules java.se.ee"
sdkmanager --list
<script type="text/javascript">
function myfunction()
{
var IDSes= "10200";
'<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
'<%Session["IDSes"] = "' + IDSes+ '"; %>';
alert('<%=Session["IDSes"] %>');
}
</script>
The string has a substring method that returns the string at the specified position.
String name="123456789";
System.out.println(name.substring(0,1));
If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.
On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:
You can do it without telling the full Acrobat path, like this:
Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();
If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:
myProcess.StartInfo.FileName = "Acrobat.exe";
You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.
Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows
For getting each node in the URI, you can use function explode()
to $_SERVER['REQUEST_URI']. If you want to get strings without knowing if it is passed or not. you may use the function I defined myself to get query parameters from $_REQUEST (as it works both for POST and GET params).
function getv($key, $default = '', $data_type = '')
{
$param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);
if (!is_array($param) && $data_type == 'int') {
$param = intval($param);
}
return $param;
}
There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
wget from a linux box might also be a good option as there are switches to spider and change it's output.
EDIT: wget is also available on Windows: http://gnuwin32.sourceforge.net/packages/wget.htm
You can create a symbolic link with a shorter directory.
First open command line for example by Shift + RightClick
in your desired folder with a shorter path (you may have to run it as administrator).
Then type with relative or absolute paths:
mklink ShortPath\To\YourLinkedSolution C:\Path\To\Your\Solution /D
And then start the Solution from the shorter path. The advantage here is: You don't have to move anything.
You can use _.omit()
for emitting the key from a JSON array if you have fewer objects:
_.forEach(data, (d) => {
_.omit(d, ['keyToEmit1', 'keyToEmit2'])
});
If you have more objects, you can use the reverse of it which is _.pick()
:
_.forEach(data, (d) => {
_.pick(d, ['keyToPick1', 'keyToPick2'])
});
Give this a go:
var distinct_list
= data.DATA.map(function (d) {return d[x];}).filter((v, i, a) => a.indexOf(v) === i)
This code works for me:
<?php
$date = "21.12.2015";
$newDate = date("d.m.Y",strtotime($date."+2 day"));
echo $newDate; // print 23.12.2015
?>
this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
using namespace std;
template <typename T, typename U>
struct CompareByGetter {
U (T::*getter)() const;
CompareByGetter(U (T::*getter)() const) : getter(getter) {};
bool operator()(const T &lhs, const T &rhs) {
(lhs.*getter)() < (rhs.*getter)();
}
};
template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
return CompareByGetter<T,U>(getter);
}
//// sort_by
template <typename T, typename U>
struct CompareByMember {
U T::*field;
CompareByMember(U T::*f) : field(f) {}
bool operator()(const T &lhs, const T &rhs) {
return lhs.*field < rhs.*field;
}
};
template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
return CompareByMember<T,U>(f);
}
template <typename T, typename U>
struct CompareByFunction {
function<U(T)> f;
CompareByFunction(function<U(T)> f) : f(f) {}
bool operator()(const T& a, const T& b) const {
return f(a) < f(b);
}
};
template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
CompareByFunction<T,U> cmp{f};
return cmp;
}
struct mystruct {
double x,y,z;
string name;
double length() const {
return sqrt( x*x + y*y + z*z );
}
};
ostream& operator<< (ostream& os, const mystruct& ms) {
return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}
template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
os << "[";
for (auto it = begin(v); it != end(v); ++it) {
if ( it != begin(v) ) {
os << " ";
}
os << *it;
}
os << "]";
return os;
}
void sorting() {
vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };
function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};
cout << "unsorted " << vec1 << endl;
sort(begin(vec1), end(vec1), by(&mystruct::x) );
cout << "sort_by x " << vec1 << endl;
sort(begin(vec1), end(vec1), by(&mystruct::length));
cout << "sort_by len " << vec1 << endl;
sort(begin(vec1), end(vec1), by(f) );
cout << "sort_by name " << vec1 << endl;
}
JavaScript is a dynamic language. You could just add it to the object itself.
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
Also, because all v3 objects extend MVCObject()
. You can use:
marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
An enhanced for
loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.
As you've discovered above, you can use a combination of window.onbeforeunload
and $locationChangeStart
to message the user. In addition, you can utilize ngForm.$dirty
to only message the user when they have made changes.
I've written an angularjs directive that you can apply to any form that will automatically watch for changes and message the user if they reload the page or navigate away. @see https://github.com/facultymatt/angular-unsavedChanges
Hopefully you find this directive useful!
If you save color code in the colors.xml which is under the values folder,then you should call the following:
root.setBackgroundColor(getResources().getColor(R.color.name));
name
means you declare in the <color/>
tag.
Invoking an overridable method in the constructor allows subclasses to subvert the code, so you can't guarantee that it works anymore. That's why you get a warning.
In your example, what happens if a subclass overrides getTitle()
and returns null ?
To "fix" this, you can use a factory method instead of a constructor, it's a common pattern of objects instanciation.
Try this if you have array and add objects to it.
$product_details = array();
foreach ($products_in_store as $key => $objects) {
$product_details[$key] = new stdClass(); //the magic
$product_details[$key]->product_id = $objects->id;
//see new object member created on the fly without warning.
}
This sends ARRAY of Objects for later use~!
Improving / Adding more functionality to Ali's answer from earlier, I created a util method in Typescript that suited my needs for this issue. This version returns rotation in degrees that you might also need for your project.
ImageUtils.ts
/**
* Based on StackOverflow answer: https://stackoverflow.com/a/32490603
*
* @param imageFile The image file to inspect
* @param onRotationFound callback when the rotation is discovered. Will return 0 if if it fails, otherwise 0, 90, 180, or 270
*/
export function getOrientation(imageFile: File, onRotationFound: (rotationInDegrees: number) => void) {
const reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
if (!event.target) {
return;
}
const innerFile = event.target as FileReader;
const view = new DataView(innerFile.result as ArrayBuffer);
if (view.getUint16(0, false) !== 0xffd8) {
return onRotationFound(convertRotationToDegrees(-2));
}
const length = view.byteLength;
let offset = 2;
while (offset < length) {
if (view.getUint16(offset + 2, false) <= 8) {
return onRotationFound(convertRotationToDegrees(-1));
}
const marker = view.getUint16(offset, false);
offset += 2;
if (marker === 0xffe1) {
if (view.getUint32((offset += 2), false) !== 0x45786966) {
return onRotationFound(convertRotationToDegrees(-1));
}
const little = view.getUint16((offset += 6), false) === 0x4949;
offset += view.getUint32(offset + 4, little);
const tags = view.getUint16(offset, little);
offset += 2;
for (let i = 0; i < tags; i++) {
if (view.getUint16(offset + i * 12, little) === 0x0112) {
return onRotationFound(convertRotationToDegrees(view.getUint16(offset + i * 12 + 8, little)));
}
}
// tslint:disable-next-line:no-bitwise
} else if ((marker & 0xff00) !== 0xff00) {
break;
} else {
offset += view.getUint16(offset, false);
}
}
return onRotationFound(convertRotationToDegrees(-1));
};
reader.readAsArrayBuffer(imageFile);
}
/**
* Based off snippet here: https://github.com/mosch/react-avatar-editor/issues/123#issuecomment-354896008
* @param rotation converts the int into a degrees rotation.
*/
function convertRotationToDegrees(rotation: number): number {
let rotationInDegrees = 0;
switch (rotation) {
case 8:
rotationInDegrees = 270;
break;
case 6:
rotationInDegrees = 90;
break;
case 3:
rotationInDegrees = 180;
break;
default:
rotationInDegrees = 0;
}
return rotationInDegrees;
}
Usage:
import { getOrientation } from './ImageUtils';
...
onDrop = (pics: any) => {
getOrientation(pics[0], rotationInDegrees => {
this.setState({ image: pics[0], rotate: rotationInDegrees });
});
};
Since you want the trailing string from the input, you can use %n
(number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.
const char *input = "19 cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);
outputs:
cool kid is 19 years old
In Rails 3
Adding Rails.env = ActiveSupport::StringInquirer.new('production')
into the application.rb and rails s
will work same as rails server -e production
module BlacklistAdmin
class Application < Rails::Application
config.encoding = "utf-8"
Rails.env = ActiveSupport::StringInquirer.new('production')
config.filter_parameters += [:password]
end
end
The below snippet examines EAX using GDB.
(gdb) info register eax
eax 0xaa55 43605
(gdb) info register ax
ax 0xaa55 -21931
(gdb) info register ah
ah 0xaa -86
(gdb) info register al
al 0x55 85
The solution is to run an NTP client , just run the command as below
#ntpdate 172.16.12.100
172.16.12.100 is the ntp server
javac -cp "jar_path/*" $(find . -name '*.java')
(I prefer not to use xargs because it can split them up and run javac multiple times, each with a subset of java files, some of which may import other ones not specified on the same javac command line)
If you have an App.java entrypoint, freaker's way with -sourcepath is best. It compiles every other java file it needs, following the import-dependencies. eg:
javac -cp "jar_path/*" -sourcepath src/ src/com/companyname/modulename/App.java
You can also specify a target class-file dir: -d target/
.
I am using ng-class for adding style :-
ng-class="column.label=='Description' ? 'tableStyle':
column.label == 'Markdown Type' ? 'Mtype' :
column.label == 'Coupon Number' ? 'couponNur' : ''
"
Using ternary operator along with ng-class directives in angular.js for giving style. Then define the style for class in .css or .scss file. Eg :-
.Mtype{
width: 90px !important;
min-width: 90px !important;
max-width: 90px !important;
}
.tableStyle{
width: 129px !important;
min-width: 129px !important;
max-width: 129px !important;
}
.couponNur{
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
}
I had the same issue and none of the other answers worked. It seems to occur frequently when you connect to the device using the wifi mode (running command 'adb tcpip 5555'). I found this solution, its sort of a workaround but it does work.
This process is a little lengthy but its the only one that has worked everytime for me.
Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:
C: \ Python27;
The (27) is example referring to version 2.7, add as per your version.
Path to system path:
Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.
Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).
Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.
To run the script enter:
C: \ User \ X \ MyScripts> python ScriptName.py
You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).
I wrote a small module that can do this straight from Python, getuser.py. Usage:
import getuser
print(getuser.lookup_username())
It works on both Windows and *nix (the latter uses the pwd
module as described in the other answers).
I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20
The support library android-support-v4.jar
is causing this conflict, just delete the library under /libs
folder of your project, don´t be scared, the library is already contained in the library appcompat_v7
, clean and build your project, and your project will work like a charm!
Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:
import matplotlib.pyplot as plt
plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})
for i, ax in enumerate(f.axes):
ax.grid('on', linestyle='--')
ax.set_xticklabels([])
ax.set_yticklabels([])
plt.show()
plt.close()
Resulting in:
Old question but I had similar issue and I solved it by adding
extern void* memset(void*, int, size_t);
or just
extern void* memset();
at the top of translation unit ( *.c file ).
Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:
exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'
This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.
You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.
Make sure you've set your locale settings right before running the script from the shell, e.g.
$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8
Docs: man locale
, man setlocale
.
Use sub query e.g:
SELECT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1 GROUP BY field1,field2
OR
SELECT DISTINCT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1
Watch out for case sensitivity. If you have a file
/Content/bootstrap.css
and you redirect in your Bundle.config to
.Include("~/Content/Bootstrap.css")
it will not load the css.
Try using cmake itself. In the build directory, run:
cmake --build .
use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath
@Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
2)use JDBC-based Driver it is usually used if you don't consider connection pool:
@Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ImageButtonFixedIconSize">
<attr name="imageButton_icon" format="reference" />
<attr name="imageButton_iconWidth" format="dimension" />
<attr name="imageButton_iconHeight" format="dimension" />
</declare-styleable>
</resources>
Widget class is quite simple (the key point is padding calculations in onLayout method):
class ImageButtonFixedIconSize
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {
private lateinit var icon: Drawable
@Px
private var iconWidth: Int = 0
@Px
private var iconHeight: Int = 0
init {
scaleType = ScaleType.FIT_XY
attrs?.let { retrieveAttributes(it) }
}
/**
*
*/
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
val width = right - left
val height = bottom - top
val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0
setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
setImageDrawable(icon)
super.onLayout(changed, left, top, right, bottom)
}
/**
*
*/
private fun retrieveAttributes(attrs: AttributeSet) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)
icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!
iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()
typedArray.recycle()
}
}
And at last you should use your widget like this:
<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
android:layout_width="90dp"
android:layout_height="63dp"
app:imageButton_icon="@drawable/ic_backspace"
app:imageButton_iconWidth="20dp"
app:imageButton_iconHeight="15dp"
android:id="@+id/backspaceButton"
tools:ignore="ContentDescription"
/>
The best solution for me was to upgrade from node-mongodb 1.x to 2.x.
I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:
var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();
I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.
I combined some of the answers and added a way to scale the stress to all available cpus:
#!/bin/bash
function infinite_loop {
while [ 1 ] ; do
# Force some computation even if it is useless to actually work the CPU
echo $((13**99)) 1>/dev/null 2>&1
done
}
# Either use environment variables for DURATION, or define them here
NUM_CPU=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
PIDS=()
for i in `seq ${NUM_CPU}` ;
do
# Put an infinite loop on each CPU
infinite_loop &
PIDS+=("$!")
done
# Wait DURATION seconds then stop the loops and quit
sleep ${DURATION}
# Parent kills its children
for pid in "${PIDS[@]}"
do
kill $pid
done
Try just =COUNTIF(A2:A51,"iPad")
You can find more information about which services it affects on the Microsoft docs.
h2.text-left{
position:relative;
top:50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}
Explanation:
The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.
Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.
A possible fix for multiple lines would be to use a percentage slightly less than 50%.
An alternative approach would be to "emulate" bold text via text-shadow. This has the bonus (/malus, depending on your case) to work also on font icons.
nav li a:hover {
text-decoration: none;
text-shadow: 0 0 1px; /* "bold" */
}
Kinda hacky, although it saves you from duplicating text (which is useful if it is a lot, as it was in my case).
I know I am too late to answer this question. I am not sure does my method still working on low iOS versions (< 5.0):
NSString *platform = [UIDevice currentDevice].model;
NSLog(@"[UIDevice currentDevice].model: %@",platform);
NSLog(@"[UIDevice currentDevice].description: %@",[UIDevice currentDevice].description);
NSLog(@"[UIDevice currentDevice].localizedModel: %@",[UIDevice currentDevice].localizedModel);
NSLog(@"[UIDevice currentDevice].name: %@",[UIDevice currentDevice].name);
NSLog(@"[UIDevice currentDevice].systemVersion: %@",[UIDevice currentDevice].systemVersion);
NSLog(@"[UIDevice currentDevice].systemName: %@",[UIDevice currentDevice].systemName);
You can get these results:
[UIDevice currentDevice].model: iPhone
[UIDevice currentDevice].description: <UIDevice: 0x1cd75c70>
[UIDevice currentDevice].localizedModel: iPhone
[UIDevice currentDevice].name: Someones-iPhone002
[UIDevice currentDevice].systemVersion: 6.1.3
[UIDevice currentDevice].systemName: iPhone OS
I know this question is super old, but I want to offer 2 options that are more efficient:
1st off, the extension method posted by Paul Walls is good but can be made more efficient by using the StringBuilder class, which is like the string data type but made especially for situations where you will be changing string values more than once. Here is a version I made of the extension method using StringBuilder:
public static string ReplaceChars(this string s, char[] separators, char newVal)
{
StringBuilder sb = new StringBuilder(s);
foreach (var c in separators) { sb.Replace(c, newVal); }
return sb.ToString();
}
I ran this operation 100,000 times and using StringBuilder took 73ms compared to 81ms using string. So the difference is typically negligible, unless you're running many operations or using a huge string.
Secondly, here is a 1 liner loop you can use:
foreach (char c in separators) { s = s.Replace(c, '\n'); }
I personally think this is the best option. It is highly efficient and doesn't require writing an extension method. In my testing this ran the 100k iterations in only 63ms, making it the most efficient. Here is an example in context:
string s = "this;is,\ra\t\n\n\ntest";
char[] separators = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
foreach (char c in separators) { s = s.Replace(c, '\n'); }
Credit to Paul Walls for the first 2 lines in this example.
for the above question this solution works.
just change the path to where your executable file is located.
import sys, string, os
os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')
os.system("C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\flowwork.exe")
'''import sys, string, os
os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')
os.system(r"C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\pdftopng.exe test1.pdf rootimage")'''
Here test1.pdf rootimage is for my code .
create your XML which is shown in dialog here it is activity_no_title_dialog
final Dialog dialog1 = new Dialog(context);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.activity_no_title_dialog);
dialog1.show();
Move back or forward a full word with alt-. Move back or forward a file in your history with cmd-alt-. Switch between interface and implementation with cmd-alt-.
Jump to the next error in the list of build errors with cmd-=. Display the multiple Find panel with cmd-shift-f. Toggle full editor visibility with cmd-shift-e.
Jump to the Project tab with cmd-0, to the build tab with cmd-shift-b and to the debug tab with cmd-shift-y (same as the key commands for the action, with shift added).
Or Joiner from Google Guava.
Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response
to this.responseText
.
A straightforward answer to this is to first tortoise svn from following link.
while installation turn on CLI option, so that it can be used from command line interface.
copy the git hub sub directory link.
Example
https://github.com/tensorflow/models/tree/master/research/deeplab
replace tree/master with trunk
and do
svn checkout https://github.com/tensorflow/models/trunk/research/deeplab
files will be downloaded to the deeplab folder in the current directory.
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
Late to the game, but you can also use a localisation file
DataTable provides a .json
localized file, which contains the key sEmptyTable
and the corresponding localized message.
For example, just download the localized json file on the above link, then initialize your Datatable
like that :
$('#example').dataTable( {
"language": {
"url": "path/to/your/json/file.json"
}
});
IMHO, that's a lot cleaner, because your localized content is located in an external file.
This syntax works for DataTables 1.10.16, I didn't test on previous versions.
No.
localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want.
That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.
All branches are stored in .git/refs
All local branches are stored in .git/refs/heads
All remote branches are stored in .git/refs/remotes
The
git fetch
command downloads commits, files, and refs from a remote repository into your local repo. Fetching is what you do when you want to see what everybody else has been working on.
So when you do git fetch
all the files, commits, and refs are downloaded in
this directory .git/refs/remotes
You can switch to these branches to see the changes.
Also, you can merge them if you want.
git pull
just downloads these changes and also merges them to the current branch.
Example
If you want see the work of remote branch dev/jd/feature/auth
, you just need to do
git fetch origin dev/jd/feature/auth
to see the changes or work progress do,
git checkout dev/jd/feature/auth
But, If you also want to fetch and merge them in the current branch do,
git pull origin dev/jd/feature/auth
If you do git fetch origin branch_name
, it will fetch the branch, now you can switch to this branch you want and see the changes. Your local master or other local branches won't be affected. But git pull origin branch_name
will fetch the branch and will also merge to the current branch.
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
Its boils down to this: math.h
is from C
and was created over 10 years ago. In math.h, due to its primitive nature, the abs()
function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs()
.
When C++ was created it took math.h
and made it cmath
. cmath
is essentially math.h but improved for C++. It improved things like having to distinguish between fabs()
and abs, and just made abs()
for both doubles and integer types.
In summary either:
Use math.h and use abs()
for integers, fabs()
for doubles
or
use cmath and just have abs for everything (easier and recommended)
Hope this helps anyone who is having the same problem!
--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;
-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
V_OUT_1 NUMBER;
V_OUT_2 VARCHAR2(200);
BEGIN
--your stored procedure name
schema.package.procedure(
--declaration for in and out parameter
V_OUT_1 => V_OUT_1,
V_OUT_2 => V_OUT_2
);
V_OUT_1 := V_OUT_1;
V_OUT_2 := V_OUT_2;
-- console output, no need to open DBMS OUTPUT seperatly
-- also no need to print each output on seperat line
DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;
An UserControl has a Destructor, why don't you use that?
~MyWpfControl()
{
// Dispose of any Disposable items here
}
Hash === @some_var #=> return Boolean
this can also be used with case statement
case @some_var
when Hash
...
when Array
...
end
Using JQuery you do this:
var imgWidth = $("#imgIDWhatever").width();
#!/bin/bash
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
git branch --track ${branch#remotes/origin/} $branch
done
These code will pull all remote branches code to local repo.
Something like this:
select
*
from sales
where salesDate >= '11/11/2010'
AND salesDate < (Convert(datetime, '11/11/2010') + 1)
when you click anywhere in the explorer tree and start typing something on the keyboard, the search keyword appears in the top right corner of the screen : ("module.ts")
And when you hover over the keyword with the mouse cursor, you can click on "Enable Filter on Type" to filter tree with your search !
You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.
if (this.combo1.SelectedItem == MY_OBJECT)
{
// do stuff
}
You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character:
You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character:
char c = (char)65;
char c = Convert.ToChar(65);
Also, ASCII.GetString
decodes a range of bytes from a byte array into a string:
string s = Encoding.ASCII.GetString(new byte[]{ 65 });
Keep in mind that, ASCIIEncoding
does not provide error detection. Any byte greater than hexadecimal 0x7F is decoded as the Unicode question mark ("?").
What's not mentioned here is that option 1 allows you arbitrarily deep nesting of lists.
This shouldn't matter if you control the content/css, but if you're making a rich text editor it comes in handy.
For example, gmail, inbox, and evernote all allow creating lists like this:
With option 2 you cannot due that (you'll have an extra list item), with option 1, you can.
import urllib2
try:
fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
data = fileHandle.read()
fileHandle.close()
except urllib2.URLError, e:
print 'you got an error with the code', e
Use ECMAScript 2015's Template String Literals, if applicable.
There is no direct way to do it, as per ECMAScript 5 specifications, but ECMAScript 6 has template strings, which were also known as quasi-literals during the drafting of the spec. Use them like this:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
You can use any valid JavaScript expression inside the {}
. For example:
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
The other important thing is, you don't have to worry about multi-line strings anymore. You can write them simply as
> `foo
... bar`
'foo\n bar'
Note: I used io.js v2.4.0 to evaluate all the template strings shown above. You can also use the latest Chrome to test the above shown examples.
Note: ES6 Specifications are now finalized, but have yet to be implemented by all major browsers.
According to the Mozilla Developer Network pages, this will be implemented for basic support starting in the following versions: Firefox 34, Chrome 41, Internet Explorer 12. If you're an Opera, Safari, or Internet Explorer user and are curious about this now, this test bed can be used to play around until everyone gets support for this.
This is how to load/use a local html with relative references.
Use the below given code. It should work like a charm.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
[webview loadRequest:[NSURLRequest requestWithURL:url]];
Now all your relative links(like img/.gif, js/.js) in the html should get resolved.
Swift 3
if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}
You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line
spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.
MODULE B/ spring-moduleB.xml
import resource="classpath:spring-moduleA.xml"/>
<bean id="helloBeanB" class="basic.HelloWorldB">
<property name="name" value="BMVNPrj" />
</bean>
To start the shell-script 'file.sh':
sh file.sh
bash file.sh
Another option is set executable permission using chmod command:
chmod +x file.sh
Now run .sh file as follows:
./file.sh
bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)
Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:
ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);
Detailed discussion here.
Try BufferedReader.readLine()
instead of all this complication. It will recognize all possible line terminators.
The match between .val('Bruce jones')
and value="Bruce Jones"
is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase()
on both.
Use curl
instead of file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
Just in case anybody else runs into a similar issue: I found taking the class "fade" off of the modal will prevent this backdrop from sticking to the screen even after the modal is hidden. It appears to be a bug in the bootstrap.js for modals.
Another (while keeping the fade effects) would be to replace the call to jQueryElement.modal with your own custom javascript that adds the "in" class, sets display: block, and add a backdrop when showing, then to perform the opposite operations when you want to hide the modal.
Simply removing fade was sufficient for my project.
Copied and pasted date column to Notepad and back.
I had a same problem with scrolling in chrome. So i removed this lines of codes from my style file.
html{height:100%;}
body{height:100%;}
Now i can play with scroll and it works:
var pos = 500;
$("html,body").animate({ scrollTop: pos }, "slow");
This MSDN blog post describes three separate ways of extracting a DLL from the GAC. A useful summary of the methods so far given.
Same thing happened to me, and I also tried to terminate secondary process from task manager. Do not do that. It is not a solution, but rather a hack which may cause issues later. In my case, I was not even able to uninstall Visual Studio. I tried both web installation and ISO, same issue.
Here is how it worked finally. I restored my Windows 7 to earliest restore point as possible, when there was nothing installed, so I was sure that there would be no conflicts between the different tools (Java, Android API, etc.)
I started the installation of Visual Studio 2015 Community Release Candidate at 10 p.m. At 7 a.m., it was working on Android API 19-21. A hour later, it was finally preparing Visual Studio.
This means that all you need to do is to actually wait 8 to 9 hours. Don't terminate the secondary installer at risk of breaking your Visual Studio; just wait.
I would use lambda
function on a Series
of a DataFrame
like this:
f = lambda x: 0 if x>100 else 1
df['my_column'] = df['my_column'].map(f)
I do not assert that this is an efficient way, but it works fine.
I had the same issue and I fixed it as below.
npm install --save-dev yarn
npm install --save-dev jest-cli
"jest-coverage": "yarn run jest -- --coverage"
After you write the tests, run the command npm run jest-coverage
. This will create a coverage folder in the root directory. /coverage/icov-report/index.html has the HTML view of the code coverage.
It's specified in the function type. When you have a function pointer, it's assumed to be cdecl if not explicitly stdcall. This means that if you get a stdcall pointer and a cdecl pointer, you can't exchange them. The two function types can call each other without issues, it's just getting one type when you expect the other. As for speed, they both perform the same roles, just in a very slightly different place, it's really irrelevant.
Here are examples of listing files by pattern powered by Java 7 nio globbing and Java 8 lambdas:
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
Paths.get(".."), "Test?/sample*.txt")) {
dirStream.forEach(path -> System.out.println(path));
}
or
PathMatcher pathMatcher = FileSystems.getDefault()
.getPathMatcher("regex:Test./sample\\w+\\.txt");
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
new File("..").toPath(), pathMatcher::matches)) {
dirStream.forEach(path -> System.out.println(path));
}
If you just want the difference in years, there's:
SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable
Or do you want fractional years as well?
SELECT (date1 - date2) / 365.242199 FROM mytable
365.242199 is 1 year in days, according to Google.
If you think less code means more efficient, so using construct function is better. You also can use code like:
Person p=new Person(){
Name='abc',
Age=15
}
string1=" This is Test String to strip leading space"
print string1
print string1.lstrip()
string2="This is Test String to strip trailing space "
print string2
print string2.rstrip()
string3=" This is Test String to strip leading and trailing space "
print string3
print string3.strip()
string4=" This is Test String to test all the spaces "
print string4
print string4.replace(" ", "")
apply
takes a function to apply to each value, not the series, and accepts kwargs.
So, the values do not have the .size()
method.
Perhaps this would work:
from pandas import *
d = {"my_label": Series(['A','B','A','C','D','D','E'])}
df = DataFrame(d)
def as_perc(value, total):
return value/float(total)
def get_count(values):
return len(values)
grouped_count = df.groupby("my_label").my_label.agg(get_count)
data = grouped_count.apply(as_perc, total=df.my_label.count())
The .agg()
method here takes a function that is applied to all values of the groupby object.
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
The UUID is used for uniquely identifying information. It identifies a particular service provided by a Bluetooth device. The standard defines a basic BASE_UUID: 00000000-0000-1000-8000-00805F9B34FB
.
Devices such as healthcare sensors can provide a service, substituting the first eight digits with a predefined code. For example, a device that offers an RFCOMM connection uses the short code: 0x0003
So, an Android phone can connect to a device and then use the Service Discovery Protocol (SDP) to find out what services it provides (UUID).
In many cases, you don't need to use these fixed UUIDs. In the case your are creating a chat application, for example, one Android phone interacts with another Android phone that uses the same application and hence the same UUID.
So, you can set an arbitrary UUID for your application using, for example, one of the many random UUID generators on the web (for example).
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
Probably you didn't provide an argument on the command line. In that case, sys.argv
only contains one value, but it would have to have two in order to provide values for both user_name
and script
.
You can use the following snippet code:
#include<stdio.h>
int main(int argc, char *argv[]){
unsigned int i;
printf("decimal hexadecimal\n");
for (i = 0; i <= 256; i+=16)
printf("%04d 0x%04X\n", i, i);
return 0;
}
It prints both decimal and hexadecimal numbers in 4 places with zero padding.
i also just got this error message by using the wrong syntax in an if
clause
else if
(syntax error: unexpected end of file) elif
(correct syntax)i debugged it by commenting bits out until it worked
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
rpm -qa openssl
yum clean all && yum update "openssl*"
lsof -n | grep ssl | grep DEL
cd /usr/src
wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
tar -zxf openssl-1.0.1g.tar.gz
cd openssl-1.0.1g
./config --prefix=/usr --openssldir=/usr/local/openssl shared
./config
make
make test
make install
cd /usr/src
rm -rf openssl-1.0.1g.tar.gz
rm -rf openssl-1.0.1g
and
openssl version
On a MAC, you need to use nm *.o | c++filt
, as there is no -C
option in nm
.
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
or try this code:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
return false;
}
});
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if your on the last day of the month.
for example Feb 28 or march 31.
Here is an example of how i would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
imo this insures accuracy
here is another example i Do not like that can work for you but not as clean that dose the above
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So Im going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number dose not change once a year but then gets fixed 6 months later i don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() i have thought this through and now thoroughly hate Date. So this is my new Approach
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
now we have our Official Valid international Date Object clearly written out at Zulu meridian. Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
SQL Server recognizes 'TRUE'
and 'FALSE'
as bit
values. So, use a bit
data type!
declare @var bit
set @var = 'true'
print @var
That returns 1
.
Getting an ECONNREFUSED errno means that your kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end. What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:
# This is Python > 2.5 code
import errno, time
for attempt in range(MAXIMUM_NUMBER_OF_ATTEMPTS):
try:
# your urllib call here
except EnvironmentError as exc: # replace " as " with ", " for Python<2.6
if exc.errno == errno.ECONNREFUSED:
time.sleep(A_COUPLE_OF_SECONDS)
else:
raise # re-raise otherwise
else: # we tried, and we had no failure, so
break
else: # we never broke out of the for loop
raise RuntimeError("maximum number of unsuccessful attempts reached")
Replace the two all-caps constants with your favourite numbers.
For those who have trouble with the accepted solution, there is another way to exclude resource from shaded jar with DontIncludeResourceTransformer:
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>BC1024KE.DSA</resource>
</transformer>
</transformers>
From Shade 3.0, this transformer accepts a list of resources. Before that you just need to use multiple transformer each with one resource.
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
If you have a double/float/floating point number and want to see if it's an integer.
public boolean isDoubleInt(double d)
{
//select a "tolerance range" for being an integer
double TOLERANCE = 1E-5;
//do not use (int)d, due to weird floating point conversions!
return Math.abs(Math.floor(d) - d) < TOLERANCE;
}
If you have a string and want to see if it's an integer. Preferably, don't throw out the Integer.valueOf()
result:
public boolean isStringInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
If you want to see if something is an Integer object (and hence wraps an int
):
public boolean isObjectInteger(Object o)
{
return o instanceof Integer;
}
Answer is you can't explicitly but you should be freeing memory in your routines.
Some tips though to help memory
I would recommend checking the memory usage after performing the routine again and again you may have a memory leak.
One instance where using a try-catch might be appropriate is when using a forEach loop. It is synchronous but at the same time you cannot just use a return statement in the inner scope. Instead a try and catch approach can be used to return an Error object in the appropriate scope. Consider:
function processArray() {
try {
[1, 2, 3].forEach(function() { throw new Error('exception'); });
} catch (e) {
return e;
}
}
It is a combination of the approaches described by @balupton above.
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
it turns out that with python 2.5.2, del l[:]
is slightly slower than l[:] = []
by 1.1 usec.
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2
Had the same error because I forgot to send a correct header a first
header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';
JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.
Since Javascripts objects consists of key/value
pairs its very easy to use and access JSON that way.
So if we have an object:
var myObj = {
foo: 'bar',
base: 'ball',
deep: {
java: 'script'
}
};
We can convert that into a string by calling window.JSON.stringify(myObj);
with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}"
.
The other way around, we would call window.JSON.parse("a json string like the above");
.
JSON.parse()
returns a javascript object/array on success.
alert(myObj.deep.java); // 'script'
window.JSON
is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.
update: Just saw the reference to call_user_func_array
in your post. that's different. use getattr
to get the function object and then call it with your arguments
class A(object):
def method1(self, a, b, c):
# foo
method = A.method1
method
is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1
with one of the two decorators discussed below, pass it an instance of A
as the first argument or access the method on an instance of A
.
a = A()
method = a.method1
method(1, 2)
You have three options for doing this
A
to call method1
(using two possible forms)classmethod
decorator to method1
: you will no longer be able to reference self
in method1
but you will get passed a cls
instance in it's place which is A
in this case.staticmethod
decorator to method1
: you will no longer be able to reference self
, or cls
in staticmethod1
but you can hardcode references to A
into it, though obviously, these references will be inherited by all subclasses of A
unless they specifically override method1
and do not call super
.Some examples:
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b
@staticmethod
def method2(a, b):
return a + b
@classmethod
def method3(cls, a, b):
return cls.method2(a, b)
t = Test1() # same as doing it in another class
Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one
Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class
Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)
Note that in the same way that the name of the self
variable is entirely up to you, so is the name of the cls
variable but those are the customary values.
Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.
.nvmrc
If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc
file:
echo v10.15.1 > .nvmrc
This does not take effect automatically on cd
, which is sane: the user must then do a:
nvm use
and now that version of node will be used for the current shell.
You can list the versions of node that you have with:
nvm list
.nvmrc
is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc
How to automatically select that node version on cd
was asked at: Automatically switch to correct version of Node based on project
Tested with NVM 0.33.11.
Hoisted from the comments
2020 comment: rather than using regex, we now have
URLSearchParams
, which does all of this for us, so no custom code, let alone regex, are necessary anymore.
Browser support is listed here https://caniuse.com/#feat=urlsearchparams
I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec()
:
function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};
if (typeof url == "undefined") url = document.location.href;
while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
return params;
}
var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");
result
is an object:
{ f: "q" geocode: "" hl: "de" ie: "UTF8" iwloc: "addr" ll: "50.116616,8.680573" q: "Frankfurt am Main" sll: "50.106047,8.679886" source: "s_q" spn: "0.35972,0.833588" sspn: "0.370369,0.833588" z: "11" }
The regex breaks down as follows:
(?: # non-capturing group \?|& # "?" or "&" (?:amp;)? # (allow "&", for wrongly HTML-encoded URLs) ) # end non-capturing group ( # group 1 [^=]+ # any character except "=", "&" or "#"; at least once ) # end group 1 - this will be the parameter's name (?: # non-capturing group =? # an "=", optional ( # group 2 [^]* # any character except "&" or "#"; any number of times ) # end group 2 - this will be the parameter's value ) # end non-capturing group
Because os.path.abspath = os.path.dirname + os.path.basename
does not hold. we rather have
os.path.dirname(filename) + os.path.basename(filename) == filename
Both dirname()
and basename()
only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.
To get the dirname of the absolute path, use
os.path.dirname(os.path.abspath(__file__))
FatJar can help you in this case.
In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects
This is useful if your final exported jar includes other external jars.
If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.
After Ganymede, you have:
**just copy paste this code and run you can see the textbox disabled **
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>.container{float:left;width:200px;height:25px;position:relative;}
.container input{float:left;width:200px;height:25px;}
.overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;}
</style>
</head>
<body>
<div class="container">
<input type="text" value="[email protected]" />
<div class="overlay">
</div>
</div>
</body>
</html>
For systemd style init scripts it's really easy. You just add a User= in the [Service] section.
Here is an init script I use for qbittorrent-nox on CentOS 7:
[Unit]
Description=qbittorrent torrent server
[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort
[Install]
WantedBy=multi-user.target
nothing special
let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)
Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":
javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType
The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.
1. Change the inspection level
Current PyCharm versions allows you to change the type of static code analysis it performs, and also features a Power/CPU Saving feature (Click on the icon at the bottom right, next to the lock):
2. Change indexed directories
Exclude directories from being indexed which are set in the project paths but not actually required to be searched and indexed. Press ALT+CTRL+S
and search for project
.
3. Do memory sweeps
There is another interesting feature:
Go into the settings (File/Settings) and search for memory. In IDE Settings>Appearance
-> tick Show memory indicator
. A memory bar will be shown at the bottom right corner (see the picture below). Click this bar to run a garbage collection / memory sweep.
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.
Just to add my 2 cents, I'd write my own PHP Script:
http://php.net/manual/en/function.mail.php
There are lots of ways to do the attachment in the examples on that page.
This answer could be really late, but its useful.
You can play youtube videos in the app itself using android-youtube-player.
Some code snippets:
To play a youtube video that has a video id in the url, you simply call the OpenYouTubePlayerActivity
intent
Intent intent = new Intent(null, Uri.parse("ytv://"+v), this,
OpenYouTubePlayerActivity.class);
startActivity(intent);
where v is the video id.
Add the following permissions in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
and also declare this activity in the manifest file:
<activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>
Further information can be obtained from the first portions of this code file.
Hope that helps anyone!
My question is whether or not there are situations in which
sys.stdout.write()
is preferable to
If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:
def myfunc(outfile=None):
if outfile is None:
out = sys.stdout
else:
out = open(outfile, 'w')
try:
# do some stuff
out.write(mytext + '\n')
# ...
finally:
if outfile is not None:
out.close()
It does mean you can't use the with open(outfile, 'w') as out:
pattern, but sometimes it is worth it.
While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.
If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.
Using if ( list.get(index) == null ) will not work either, as get() throws an exception instead of returning null.
Try this:
try {
list.get( index );
} catch ( IndexOutOfBoundsException e ) {
list.add( index, new Object() );
}
Here a new entry is added if the index does not exist. You can alter it to do something different.
You could use screen
, detach and reattach
Well, you have to set your dialog's height and width before to show this ( dialog.show() )
so, do something like this:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
Using Microsoft SQL Server Management Studio you can create Linked Server
. First make connection to current (local) server, then go to Server Objects
> Linked Servers
> context menu > New Linked Server
. In window New Linked Server
you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).
And further you can select data from linked server:
select * from [linked_server_name].[database].[schema].[table]
`pip -v` or `pip --v`
However note, if you are using macos catelina which has the zsh (z shell) it might give you a whole bunch of things, so the best option is to try install the version or start as -- pip3
var top = ($('#bottom').position().top) + ($('#bottom').height());
I developed CLI tool for it.You can just type "rndcli".and select device
You just need to have an existing file, open the context menu on your folder , and then choose Add
=> Existing item...
If you have the file already placed within your project structure, but it is not yet included, you can do so by making them visible in the solution explorer
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with ()
brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
Another workaround is to use grep -o
with a little regex magic to get three chars followed by the end of line:
$ foo=1234567890
$ echo $foo | grep -o ...$
890
To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep
with this regex:
$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd
You can also use different ranges, such as 5,10
to get the last five to ten chars.
just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea
. You can use it for textbox also.
While I agree with the most voted answer, here is another way to keep all rows except the first:
dat <- tail(dat, -1)
This can also be accomplished using Hadley Wickham's dplyr
package.
dat <- dat %>% slice(-1)
You are importing from package "sub". start.py
is not itself in a package even if there is a __init__.py
present.
You would need to start your program from one directory over parent.py
:
./start.py
./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py
With start.py
:
import pkg.sub.relative
Now pkg is the top level package and your relative import should work.
If you want to stick with your current layout you can just use import parent
. Because you use start.py
to launch your interpreter, the directory where start.py
is located is in your python path. parent.py
lives there as a separate module.
You can also safely delete the top level __init__.py
, if you don't import anything into a script further up the directory tree.
In java8, I would use the Instant
class which is already in UTC and is convenient to work with.
import java.time.Instant;
Instant ins = Instant.now();
long ts = ins.toEpochMilli();
Instant ins2 = Instant.ofEpochMilli(ts)
Alternatively, you can use the following:
import java.time.*;
Instant ins = Instant.now();
OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));
Back to Instant
Instant ins4 = Instant.from(odt);
Definition:
JOINS are way to query the data that combined together from multiple tables simultaneously.
Concern to RDBMS there are 5-types of joins:
Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.
Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN
Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.
Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.
Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.
As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.
INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.
OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.
2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.
2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.
2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.
CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.
Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.
1.1: INNER-JOIN: Equi-join implementation
SELECT *
FROM Table1 A
INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;
1.2: INNER-JOIN: Natural-JOIN implementation
Select A.*, B.Col1, B.Col2 --But no B.ForeignKeyColumn in Select
FROM Table1 A
INNER JOIN Table2 B On A.Pk = B.Fk;
1.3: INNER-JOIN with NON-Equi-join implementation
Select *
FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;
1.4: INNER-JOIN with SELF-JOIN
Select *
FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;
2.1: OUTER JOIN (full outer join)
Select *
FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;
2.2: LEFT JOIN
Select *
FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;
2.3: RIGHT JOIN
Select *
FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;
3.1: CROSS JOIN
Select *
FROM TableA CROSS JOIN TableB;
3.2: CROSS JOIN-Self JOIN
Select *
FROM Table1 A1 CROSS JOIN Table1 A2;
//OR//
Select *
FROM Table1 A1,Table1 A2;
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
var l = str.length, lc = 0, chunks = [], c = 0, chunkSize = 2;
for (; lc < l; c++) {
chunks[c] = str.slice(lc, lc += chunkSize);
}
To iterate over an object which has a json format like below
{
"mango": { "color": "orange", "taste": "sweet" }
"lemon": { "color": "yellow", "taste": "sour" }
}
Assign it to a variable
let rawData = { "mang":{...}, "lemon": {...} }
Create a empty array(s) for holding the values(or keys)
let dataValues = []; //For values
let dataKeys = []; //For keys
Loop over the keys and add the values(and keys) to variables
for(let key in rawData) { //Pay attention to the 'in'
dataValues.push(rawData[key]);
dataKeys.push(key);
}
Now you have an array of keys and values which you can use in *ngFor or a for loop
for(let d of dataValues) {
console.log("Data Values",d);
}
<tr *ngFor='let data of dataValues'> ..... </tr>
It's really surprising to me that the redirection methods in ProcessBuilder
don't accept an OutputStream
, only File
. Yet another proof of forced boilerplate code that Java forces you to write.
That said, let's look at a list of comprehensive options:
inheritIO
will do the job.redirect*(file)
.InputStream
in a separate thread. See the answers that use a Runnable
or CompletableFuture
. You can also adapt the code below to do this.PrintWriter
, that may or may not be the stdout (very useful for testing), you can do the following:static int execute(List<String> args, PrintWriter out) {
ProcessBuilder builder = new ProcessBuilder()
.command(args)
.redirectErrorStream(true);
Process process = null;
boolean complete = false;
try {
process = builder.start();
redirectOut(process.getInputStream(), out)
.orTimeout(TIMEOUT, TimeUnit.SECONDS);
complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
LOG.warn("Thread was interrupted", e);
} finally {
if (process != null && !complete) {
LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
process = process.destroyForcibly();
}
}
return process != null ? process.exitValue() : 1;
}
private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
return CompletableFuture.runAsync(() -> {
try (
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
) {
bufferedReader.lines()
.forEach(out::println);
} catch (IOException e) {
LOG.error("Failed to redirect process output", e);
}
});
}
Advantages of the code above over the other answers thus far:
redirectErrorStream(true)
redirects the error stream to the output stream, so that we only have to bother with one.CompletableFuture.runAsync
runs from the ForkJoinPool
. Note that this code doesn't block by calling get
or join
on the CompletableFuture
but sets a timeout instead on its completion (Java 9+). There's no need for CompletableFuture.supplyAsync
because there's nothing really to return from the method redirectOut
.BufferedReader.lines
is simpler than using a while
loop.Use an empty object literal isn't necessary here, you can use null or undefined:
$scope.items = null;
In this way, ng-show
should keep working, and in your controller you can just do:
if ($scope.items) {
// items have value
} else {
// items is still null
}
And in your $http
callbacks, you do the following:
$http.get(..., function(data) {
$scope.items = {
data: data,
// other stuff
};
});
For me I removed whole data
folder from xampp\mysql\
and pasted data
folder of previous one here which solved my problem...
When you have two or more (in the example below there're three) elements in the string, then you can use comma to separate these items:
date, time, event_name = ev.get_text(separator='@').split("@")
After this line of code, the three variables will have values from three parts of the variable ev
So, if the variable ev contains this string and we apply separator '@':
Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL
Then, after split operation the variable
I used this statement and it worked for me:
setListAdapter(null)
This one calls a default constructor that does nothing in a class extends BaseAdapter.
The solution is to open project structure window. [by press command+; on mac ox s. i don't what's the key shortcut for other platforms. you should be able to find it under "File" menu.] and click "Modules" under "Project settings" section, then your project is revealed, finally mark the generated R.java as Sources.
I am using Intellij idea 14.0 CE. The generated R.java is located at build/generated/source/r/debug/com/example/xxx
Really not easy to find for the first time.
The problem is this block:
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
When the StreamReader
is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream
is closed. When the StreamWriter
gets closed, it tries to flush everything to the MemoryStream
, but it is closed.
You should consider not putting the StreamReader
in a using block.
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
One should always replace like this:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/
If you define your array in properties file like:
base.module.elementToSearch=1,2,3,4,5,6
You can load such array in your Java class like this:
@Value("${base.module.elementToSearch}")
private String[] elementToSearch;
What is Stack? A stack is a type of data structure -- a means of storing information in a computer. When a new object is entered in a stack, it is placed on top of all the previously entered objects. In other words, the stack data structure is just like a stack of cards, papers, credit card mailings, or any other real-world objects you can think of. When removing an object from a stack, the one on top gets removed first. This method is referred to as LIFO (last in, first out).
The term "stack" can also be short for a network protocol stack. In networking, connections between computers are made through a series of smaller connections. These connections, or layers, act like the stack data structure, in that they are built and disposed of in the same way.
Use the below:
var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regEx);
If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing
I don't know if you'd have to restart visual studio, but seems unlikely. HTH
You might not believe it, but YAML can do multi-line keys too:
?
>
multi
line
key
:
value
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Veverke mentioned that it is possible to disable generation of binding redirects by setting AutoGEneratedBindingRedirects to false. Not sure if it's a new thing since this question was posted, but there is an "Skip applying binding redirects" option in Tools/Options/Nuget Packet Manager, which can be toggled. By default it is off, meaning the redirects will be applied. However if you do this, you will have to manage any necessary binding redirects manually.
UPDATE:
Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here
Using ActionBarActivity:
In Eclipse:
1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.
2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).
3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)
4- Check whether ActionBarActivity is properly imported.
import android.support.v7.app.ActionBarActivity;
In Android Studio
Just add compile dependencies to app's build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
These do the same thing:
window.location.assign(url);
window.location = url;
window.location.href = url;
They simply navigate to the new URL. The replace
method on the other hand navigates to the URL without adding a new record to the history.
So, what you have read in those many forums is not correct. The assign
method does add a new record to the history.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that
mod_proxy
considers a backend as failed only when the transport layer connection to that backend fails. Unlessfailonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a
balancer
here, so thetimeout
parameter relates to thebalancer
(like the two others). However for abalancer
, thetimeout
parameter is not a connection timeout (like the one used withBalancerMember
), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).
So, a proper configuration is done like this
timeout
at the BalanceMember
level: <Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
Turns out I, like @Grey Black, had to actually install v62.1 of icu4c. Nothing else worked.
However, brew switch icu4c 62.1
only works if you have installed 62.1 in the past. If you haven't there's more legwork involved. Homebrew does not make it easy to install previous versions of formulae.
Here's how I did it:
git -C $(brew --repo homebrew/core) fetch --unshallow
brew log icu4c
to track down a commit that references 62.1; 575eb4b
does the trick.cd $(brew --repo homebrew/core)
git checkout 575eb4b -- Formula/icu4c.rb
brew uninstall --ignore-dependencies icu4c
brew install icu4c
You should now have the correct version of the dependency! Now just to...git reset && git checkout .
Cleanup your modified recipe.brew pin icu4c
Pin the dependency to prevent it from being accidentally upgraded in the futureIf you decide you do want to upgrade it at some point, make sure to run brew unpin icu4c
The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.
Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
On your UserManager
, first call GeneratePasswordResetTokenAsync. Once the user has verified his identity (for example by receiving the token in an email), pass the token to ResetPasswordAsync.
1.Check your server status.
2.Check the port status.
For example 3306 netstat -nupl|grep 3306
.
3.Check your firewalls. For example add 3306
vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:
Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:
Fill in the form, click next and then you automatically go to this page:
Choose to add existing files and you go to this page:
You use those commands and you upload the existing files to Bitbucket. After that, the files are online.
try this one:
<table style="border:1px solid">
<tr>
<td style="min-width:50px">one</td>
<td style="min-width:100px">two</td>
</tr>
</table>
_x000D_