For windows or one using google colab, you can try this
!pip install pymysql
import pymysql
Moore's answer doesn't work, and the page here:
Specifying the Selection Color, Content Alignment, and Background Color for items in a ListBox
explains why it cannot work.
If your listview only contains basic text, the simplest way to solve the problem is by using transparent brushes.
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#00000000"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#00000000"/>
</Style.Resources>
</Style>
</Window.Resources>
This will produce undesirable results if the listview's cells are holding controls such as comboboxes, since it also changes their color. To solve this problem, you must redefine the control's template.
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border SnapsToDevicePixels="True"
x:Name="Bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<GridViewRowPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Columns="{TemplateBinding GridView.ColumnCollection}"
Content="{TemplateBinding Content}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled"
Value="False">
<Setter Property="Foreground"
Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
Resolved the issue... you need to add the ssh public key to your github account.
ssh-keygen
~/.ssh/id_rsa
)~/.ssh/id_rsa.pub
) to github account git clone
. It works!
Initial status (public key not added to git hub account)
foo@bn18-251:~$ rm -rf test foo@bn18-251:~$ ls foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... Permission denied (publickey). fatal: The remote end hung up unexpectedly foo@bn18-251:~$
Now, add the public key ~/.ssh/id_rsa.pub
to the github account (I used cat ~/.ssh/id_rsa.pub
)
foo@bn18-251:~$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/foo/.ssh/id_rsa): Created directory '/home/foo/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/foo/.ssh/id_rsa. Your public key has been saved in /home/foo/.ssh/id_rsa.pub. The key fingerprint is: xxxxx The key's randomart image is: +--[ RSA 2048]----+ xxxxx +-----------------+ foo@bn18-251:~$ cat ./.ssh/id_rsa.pub xxxxx foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... The authenticity of host 'github.com (207.97.227.239)' can't be established. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts. Enter passphrase for key '/home/foo/.ssh/id_rsa': warning: You appear to have cloned an empty repository. foo@bn18-251:~$ ls test foo@bn18-251:~/test$ git status # On branch master # # Initial commit # nothing to commit (create/copy files and use "git add" to track)
Just add the following-
class="modal show"
Working Example-
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal show" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
During an interview, I was asked to reverse a string without using any variables or native methods. This is my favorite implementation:
function reverseString(str) {
return str === '' ? '' : reverseString(str.slice(1)) + str[0];
}
Click Insert ->Object->Create from file ->Browse.
Once the file is selected choose the "Change icon" option and you will be able to rename the file and change the icon if you wish.
Hope this helps!
Hadoop comes with a useful program called distcp
for copying large amounts of data to and from Hadoop Filesystems in parallel. The canonical use case for distcp is for transferring data between two HDFS clusters.
If the clusters are running identical versions of hadoop, then the hdfs scheme is appropriate to use.
$ hadoop distcp hdfs://namenode1/foo hdfs://namenode2/bar
The data in /foo
directory of namenode1 will be copied to /bar directory of namenode2. If the /bar
directory does not exist, it will create it. Also we can mention multiple source paths.
Similar to rsync
command, distcp command by default will skip the files that already exist. We can also use -overwrite
option to overwrite the existing files in destination directory. The option -update
will only update the files that have changed.
$ hadoop distcp -update hdfs://namenode1/foo hdfs://namenode2/bar/foo
distcp
can also be implemented as a MapReduce job where the work of copying is done by the maps that run in parallel across the cluster. There will be no reducers.
If trying to copy data between two HDFS clusters that are running different versions, the copy will process will fail, since the RPC systems are incompatible. In that case we need to use the read-only HTTP based HFTP filesystems to read from the source. Here the job has to run on destination cluster.
$ hadoop distcp hftp://namenode1:50070/foo hdfs://namenode2/bar
50070 is the default port number for namenode's embedded web server.
instead of body
type a list of elements you want.
As of 1.10.5, simply include
'orderable: false'
in columnDefs and target your column with
'targets: [0,1]'
Table should like like:
var table = $('#data-tables').DataTable({
columnDefs: [{
targets: [0],
orderable: false
}]
});
Give the #under
a negative z-index
, e.g. -1
This happens because the z-index
property is ignored in position: static;
, which happens to be the default value; so in the CSS code you wrote, z-index
is 1
for both elements no matter how high you set it in #over
.
By giving #under
a negative value, it will be behind any z-index: 1;
element, i.e. #over
.
You may want to read this document in matplotlib
's documentation, titled:
Web application is better in performance as you are publishing a precompiled code, the code is 100% compiled successfully.
Meanwhile web site is better in maintainability as you can change the code easily and the changes will take effect immediately without any build, in this case the page is going to be compiled when it is called for the first time which means it might cause compilation error or crashes in your page whenever it is being called. Each one has its own pros and cons
Check the difference here, it is helpful to understand more about both.
Use this
select * from (
SELECT ARIDNR,LIEFNR,row_number() over
(partition by ARIDNR order by ARIDNR) as RowNum) a
where a.RowNum >1
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
If a value in YAML begins with a curly brace ({
), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:
Quote the whole command:
- command: "{{ item }} chdir=/src/package/"
with_items:
- ./configure
- /usr/bin/make
- /usr/bin/make install
or change the order of the arguments:
- command: chdir=/src/package/ {{ item }}
with_items:
- ./configure
- /usr/bin/make
- /usr/bin/make install
Thanks for @RamondelaFuente alternative suggestion.
If your code can sensibly be written as a case statement, this is pretty decent:
case mybool
when TrueClass, FalseClass
puts "It's a bool!"
else
puts "It's something else!"
end
If you're talking about ASP.NET MVC then you should have a controller method that returns the following:
return Redirect("http://www.google.com");
Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug
An unsigned APK is generated for each case (for debug or testing)
NOTE: On Windows, replace gradle executable for gradlew.bat
in Javascript.
var myObject = { "name" : "john" };
// { "name" : "john" };
myObject.gender = "male";
// { "name" : "john", "gender":"male"};
user@host> g++ hw.cpp
user@host> ./a.out
To lessen the impact on code readabilty, I'd suggest:
v = 1d* s/t;
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
In Chrome 72 (2019-02-09) I've discovered that the :in-range
attribute is applied to empty date
inputs, for some reason!
So this works for me: (I added the :not([max]):not([min])
selectors to avoid breaking date inputs that do have a range applied to them:
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
Screenshot:
Here's a runnable sample:
window.addEventListener( 'DOMContentLoaded', onLoad );_x000D_
_x000D_
function onLoad() {_x000D_
_x000D_
document.getElementById( 'date4' ).value = "2019-02-09";_x000D_
_x000D_
document.getElementById( 'date5' ).value = null;_x000D_
_x000D_
}
_x000D_
label {_x000D_
display: block;_x000D_
margin: 1em;_x000D_
}_x000D_
_x000D_
input[type=date]:not([max]):not([min]):in-range {_x000D_
color: blue;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" id="date1" />_x000D_
Without HTML value=""_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="date" id="date2" value="2019-02-09" />_x000D_
With HTML value=""_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="date" id="date3" />_x000D_
Without HTML value="" but modified by user_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="date" id="date4" />_x000D_
Without HTML value="" but set by script_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
<input type="date" id="date5" value="2019-02-09" />_x000D_
With HTML value="" but cleared by script_x000D_
</label>
_x000D_
Jeff Atwood has a post on this here: http://www.codinghorror.com/blog/archives/000229.html
He eventually went with Edit Pad Pro, because "Based on my prior usage history, I felt that EditPad Pro was the best fit: it's quite fast on large text files, has best-of-breed regex support, and it doesn't pretend to be an IDE."
Please use the below mentioned URL to encrypt string using AES excryption with
key and IV values.
Have you tried sc.exe
?
C:\> for /f "tokens=2*" %a in ('sc query audiosrv ^| findstr STATE') do echo %b
4 RUNNING
C:\> for /f "tokens=2*" %a in ('sc query sharedaccess ^| findstr STATE') do echo %b
1 STOPPED
Note that inside a batch file you'd double each percent sign.
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
The other option is .cxx
where the x
is supposed to be a plus rotated 45°.
Windows, Mac and Linux all support .c++
so we should just use that.
By using FusedLocationProviderApi which is the latest API and the best among the available possibilities to get location in Android. add this in build.gradle file
dependencies {
compile 'com.google.android.gms:play-services:6.5.87'
}
you can get full source code by this url http://javapapers.com/android/android-location-fused-provider/
You can do this easily with the KoGrid plugin for KnockoutJS.
<script type="text/javascript">
$(function () {
window.viewModel = {
myObsArray: ko.observableArray([
{ id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
{ id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
{ id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
{ id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
])
};
ko.applyBindings(viewModel);
});
</script>
<div data-bind="koGrid: { data: myObsArray }">
Please check if you are were passing method as POST
instead as GET
.
if so you will get same error as a you posted above.
$http({
method: 'GET',
The request entity's media type 'text/plain' is not supported for this resource.
I know this is an old question, but I just wanted to post this bit of code as I could not find a simple gem to do just this task for me.
module QueryParams
def self.encode(value, key = nil)
case value
when Hash then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
when nil then ''
else
"#{key}=#{CGI.escape(value.to_s)}"
end
end
private
def self.append_key(root_key, key)
root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
end
end
Rolled up as gem here: https://github.com/simen/queryparams
In jquery you could try this $("#select_id>option:selected").text()
What about injecting the class attribute after the class definition?
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
def method(self):
ret = Klass.stat_func()
return ret
Klass._ANS = Klass.stat_func() # inject the class attribute with static method value
There's an extention to FPDF called UFDPF http://acko.net/blog/ufpdf-unicode-utf-8-extension-for-fpdf/
But, imho, it's better to use mpdf if you're it's possible for you to change class.
In addition to @James Iry's solution, it is also possible to accomplish this using a fold. I suspect that this solution is slightly faster than the tuple method (fewer garbage objects are created):
val list = List("this", "maps", "string", "to", "length")
val map = list.foldLeft(Map[String, Int]()) { (m, s) => m(s) = s.length }
setx path "%PATH%; C:\Program Files (x86)\Microsoft Office\root\Office16" /m
This should do the appending to the System Environment Variable Path without any extras added, and keeping the original intact without any loss of data. I have used this command to correct the issue that McAfee's Web Control does to Microsoft's Outlook desktop client.
The quotations are used in the path value because command line sees spaces as a delimiter, and will attempt to execute next value in the command line. The quotations override this behavior and handles everything inside the quotations as a string.
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
Intent takePhoto = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(takePhoto, CAMERA_PIC_REQUEST)
and set
CAMERA_PIC_REQUEST= 1 or 0
Developers are often confused by what a callback is because of the name of the damned thing.
A callback function is a function which is:
A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.
Maybe a better name would be a "call after" function.
This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.
Pseudocode:
// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
printout("The number you provided is: " + number);
}
// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
printout("I have finished printing numbers.");
}
// Driver method
funct event() {
printANumber(6, printFinishMessage);
}
Result if you called event():
The number you provided is: 6
I have finished printing numbers.
The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.
Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.
Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).
In your main layout set your ListView
gravity to right:
android:layout_gravity="right"
Also in your code :
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
}
else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
hope it works :)
If the database link option is not available, another route you could take is to link the tables via ODBC to something such as MS Access or Crystal reports and do the join there.
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Similar answer to iHulk's one, but in Swift
Add a file named UIView.swift in your project (or just paste this in any file) :
import UIKit
@IBDesignable extension UIView {
@IBInspectable var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
guard let color = layer.borderColor else {
return nil
}
return UIColor(cgColor: color)
}
}
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
}
Then this will be available in Interface Builder for every button, imageView, label, etc. in the Utilities Panel > Attributes Inspector :
Note: the border will only appear at runtime.
If for whatever reason the power goes or the Visual Studio IDE crashes it can cause this problem inside your bin/debug bin/release...
Just delete the content and recompile (from personal experience when my toe hit the reset button!)
Here is how I made a script that could take either command line inputs or have a text file redirected.
if ($#ARGV < 1) {
@ARGV = ();
@ARGV = <>;
chomp(@ARGV);
}
This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.
WARNING
If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.
I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
As long as volumes are associated with a container(either running or not), they cannot be removed.
You have to run
docker inspect <container-id>/<container-name>
on each of the running/non-running containers where this volume might have been mounted onto.
If the volume is mounted onto any one of the containers, you should see it in the Mounts section of the inspect command output. Something like this :-
"Mounts": [
{
"Type": "volume",
"Name": "user1",
"Source": "/var/lib/docker/volumes/user1/_data",
"Destination": "/opt",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
After figuring out the responsible container(s), use :-
docker rm -f container-1 container-2 ...container-n
in case of running containers
docker rm container-1 container-2 ...container-n
in case of non-running containers
to completely remove the containers from the host machine.
Then try removing the volume using the command :-
docker volume remove <volume-name/volume-id>
Both John Conde's and ryeballar's answers are correct and will work.
If you want to get too geeky:
John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center
and it has to decide whether to add/remove left
), when clearly only one is needed.
Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)
So, you can do the following as an alternative:
ng-class="{true:'center',false:'left'}[page.isSelected(1)]"
For Angular 6.1+ , you can use default pipe keyvalue
( Do review and upvote also ) :
<ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
For the previous version :
One simple solution to this is convert map to array : Array.from
Component Side :
map = new Map<String, String>();
constructor(){
this.map.set("sss","sss");
this.map.set("aaa","sss");
this.map.set("sass","sss");
this.map.set("xxx","sss");
this.map.set("ss","sss");
this.map.forEach((value: string, key: string) => {
console.log(key, value);
});
}
getKeys(map){
return Array.from(map.keys());
}
Template Side :
<ul>
<li *ngFor="let recipient of getKeys(map)">
{{recipient}}
</li>
</ul>
I solved this exception by changing the target sdk
version from 19 onwards kitkat version AndroidManifest.xml.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
I would like to specify something. If someone want to get the whole url with path like I need, can use:
var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
Java EE 5 favors the use of annotations over XML configuration. For example, in EJB3 the transaction attributes on an EJB method are specified using annotations. They even use annotations to mark POJOs as EJBs and to specify particular methods as lifecycle methods instead of requiring that implementation of an interface.
char_seen = []
for char in string:
if char not in char_seen:
char_seen.append(char)
print(''.join(char_seen))
This will preserve the order in which alphabets are coming,
output will be
abcd
You can adjust the pane title by setting the pane border in the tmux.conf for example like this:
###############
# pane border #
###############
set -g pane-border-status bottom
#colors for pane borders
setw -g pane-border-style fg=green,bg=black
setw -g pane-active-border-style fg=colour118,bg=black
setw -g automatic-rename off
setw -g pane-border-format ' #{pane_index} #{pane_title} : #{pane_current_path} '
# active pane normal, other shaded out?
setw -g window-style fg=colour28,bg=colour16
setw -g window-active-style fg=colour46,bg=colour16
Where pane_index, pane_title and pane_current_path are variables provided by tmux itself.
After reloading the config or starting a new tmux session, you can then set the title of the current pane like this:
tmux select-pane -T "fancy pane title";
#or
tmux select-pane -t paneIndexInteger -T "fancy pane title";
If all panes have some processes running, so you can't use the command line, you can also type the commands after pressing the prefix bind (C-b by default) and a colon (:) without having "tmux" in the front of the command:
select-pane -T "fancy pane title"
#or:
select-pane -t paneIndexInteger -T "fancy pane title"
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
The best solution is toString
(as stated above):
function getRealObjectType(obj: {}): string {
return Object.prototype.toString.call(obj).match(/\[\w+ (\w+)\]/)[1].toLowerCase();
}
FAIR WARNING: toString
considers NaN
a number
so you must manually safeguard later with Number.isNaN(value)
.
The other solution suggested, using Object.getPrototypeOf
fails with null
and undefined
For a CSS-only solution, try using the checkbox hack. Basically, the idea is to use a checkbox and assign different styles based on whether the box is checked or not used the :checked
pseudo selector. The checkbox can be hidden, if need be, by attaching it to a label
.
link to dabblet (not mine): http://dabblet.com/gist/1506530
link to CSS Tricks article: http://css-tricks.com/the-checkbox-hack/
Try using TempData
:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
@if (TempData["notice"] != null) {
<p>@TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array
template simply generates a struct
containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
Filter using wildcards:
Get-ChildItem -Filter CopyForBuild* -Include *.bat,*.cmd -Exclude *.old.cmd,*.old.bat -Recurse
Filtering using a regular expression:
Get-ChildItem -Path "V:\Myfolder" -Recurse
| Where-Object { $_.Name -match '\ACopyForBuild\.[(bat)|(cmd)]\Z' }
You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
Two options available at bellow site:
OPTION 1: using UIWindow (tried and work perfectly)
// create graphics context with screen size
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
// grab reference to our window
UIWindow *window = [UIApplication sharedApplication].keyWindow;
// transfer content into our context
[window.layer renderInContext:ctx];
UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
OPTION 2: using UIView
// grab reference to the view you'd like to capture
UIView *wholeScreen = self.splitViewController.view;
// define the size and grab a UIImage from it
UIGraphicsBeginImageContextWithOptions(wholeScreen.bounds.size, wholeScreen.opaque, 0.0);
[wholeScreen.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
For retina screen (as DenNukem answer)
// grab reference to our window
UIWindow *window = [UIApplication sharedApplication].keyWindow;
// create graphics context with screen size
CGRect screenRect = [[UIScreen mainScreen] bounds];
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(screenRect.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
}
for more detail: http://pinkstone.co.uk/how-to-take-a-screeshot-in-ios-programmatically/
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.
As simple as that
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
byte[] bytesArray = new byte[byteBuffer.remaining()];
byteBuffer.get(bytesArray, 0, bytesArray.length);
return bytesArray;
}
Here is an example for toggling bold, underline, and italics.
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( ActiveControl is RichTextBox r )
{
if ( keyData == ( Keys.Control | Keys.B ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.U ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.I ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
return true;
}
}
return base.ProcessCmdKey( ref msg, keyData );
}
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
The git will ignore the files matched .gitignore pattern after you add it to .gitignore.
But the files already existed in repository will be still in.
use git rm files_ignored; git commit -m 'rm no use files'
to delete ignored files.
Make's substitutions feature is nice and helped me to write
%.i: src/%.c $(INCLUDE)
gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@
You might find this useful, because it asks make
to check for changes in include folders too
In mvc 4 you can easily do it like following using TextBoxFor
..
@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })
So, you don't need to use any data annotation in model or view model class
One follow up to this. I had installed SQL Server 2014 with only Windows Authentication. After enabling Mixed Mode, I couldn't log in with a SQL user and got the same error message as the original poster. I verified that named pipes were enabled but still couldn't log in after several restarts. Using 127.0.0.1 instead of the hostname allowed me to log in, but interestingly, required a password reset prompt on first login:
Once I reset the password the account worked. What's odd, is I specifically disabled password policy and expiration.
You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.
Well that's pretty easy actually with GCD. A typical workflow would be something like this:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
// Perform async operation
// Call your method/function here
// Example:
// NSString *result = [anObject calculateSomething];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI
// Example:
// self.myLabel.text = result;
});
});
For more on GCD you can take a look into Apple's documentation here
As some have mentioned a possible way is using git interactive staging. This is great when you have files with different extensions
$ git add -i
staged unstaged path
1: unchanged +0/-1 TODO
2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
*** Commands ***
1: status 2: update 3: revert 4: add untracked
5: patch 6: diff 7: quit 8: help
What now>
If you press 2
then enter
you will get a list of available files to be added:
What now> 2
staged unstaged path
1: unchanged +0/-1 TODO
2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
Update>>
Now you just have to insert the number of the files you want to add, so if we wanted to add TODO
and index.html
we would type 1,2
Update>> 1,2
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
3: unchanged +5/-1 lib/simplegit.rb
Update>>
You see the *
before the number? that means that the file was added.
Now imagine that you have 7 files and you want to add them all except the 7th? Sure we could type 1,2,3,4,5,6
but imagine instead of 7 we have 16, that would be quite cumbersome, the good thing we don't need to type them all because we can use ranges,by typing 1-6
Update>> 1-6
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
* 4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
7: unchanged +5/-1 file7.html
Update>>
We can even use multiple ranges, so if we want from 1 to 3 and from 5 to 7 we type 1-3, 5-7
:
Update>> 1-3, 5-7
staged unstaged path
* 1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
* 7: unchanged +5/-1 file7.html
Update>>
We can also use this to unstage files, if we type -number
, so if we wanted to unstage file number 1 we would type -1
:
Update>> -1
staged unstaged path
1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
* 5: unchanged +5/-1 file5.html
* 6: unchanged +5/-1 file6.html
* 7: unchanged +5/-1 file7.html
Update>>
And as you can imagine we can also unstage a range of files, so if we type -range
all the files on that range would be unstaged. If we wanted to unstage all the files from 5 to 7 we would type -5-7
:
Update>> -5-7
staged unstaged path
1: unchanged +0/-1 TODO
* 2: unchanged +1/-1 index.html
* 3: unchanged +5/-1 lib/simplegit.rb
4: unchanged +5/-1 file4.html
5: unchanged +5/-1 file5.html
6: unchanged +5/-1 file6.html
7: unchanged +5/-1 file7.html
Update>>
To add a new parameter for ex: newParam
to the current Request
Object, you can do:
$newParam = "paramvalue";
$request->request->add(['newParam' => $newParam]);
After adding the new parameter, you would be able to see this newly added parameter to the Request object by:
dd($request);//prints the contents of the Request object
make sure that your hardware keyboard is enable while creating your AVD
-launch the emulator -install your app -launch your app -make sure that your Num lock is on -Press '7' &'9' from your num pad to change your orientation landscape to portrait & portrait to landscape.
Here is an overly complicated version of what you are asking:
class MyTuple : Tuple<int, int>
{
public MyTuple(int one, int two)
:base(one, two)
{
}
public int OrderGroupId { get{ return this.Item1; } }
public int OrderTypeId { get{ return this.Item2; } }
}
Why not just make a class?
The sample below just does what you need programatically. I have used a fixed size of (140,398).
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(140, 398);
layoutParams.setMargins(24, 0, 24, 0);
layout.addView(button,layoutParams);
If after installing the lombok intellij plugin
and enabling annotation processing, if your getter and setters are still not recognised in intellij, do check if the plugin
version is compatible with the intellij
version you use.
It is listed under the Downloads section:
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();
HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};
HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
for (var i = 0; i < this.myListeners.length; i++) {
this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
};
delete this.myListeners;
};
};
The ability to search commits has recently been added to GitHub.
To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master
), or the "Issues" tab to see pull requests containing the commit.
To be more explicit you can add the hash:
prefix to the search, but it's not really necessary.
There is also a REST API (at the time of writing it is still in preview).
Try like this...
<script>
function getPaging(str) {
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
or unobtrusively
$(function() {
$("li").on("click",function() {
showLoader();
$("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
});
});
using just
<li id="1">1</li>
<li id="2">2</li>
I've found the following function and regex useful for word counts, especially in dealing with single vs. double hyphens, where the former generally should not count as a word break, eg, well-known, hi-fi; whereas double hyphen is a punctuation delimiter that is not bounded by white-space--such as for parenthetical remarks.
txt <- "Don't you think e-mail is one word--and not two!" #10 words
words <- function(txt) {
length(attributes(gregexpr("(\\w|\\w\\-\\w|\\w\\'\\w)+",txt)[[1]])$match.length)
}
words(txt) #10 words
Stringi is a useful package. But it over-counts words in this example due to hyphen.
stringi::stri_count_words(txt) #11 words
The latest way to do this with ES2016 JavaScript
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.
whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
Swift 3 / Designable in Interface builder / Separate horizontal & vertical insects / usable out of the box
@IBDesignable
class TextFieldWithPadding: UITextField {
@IBInspectable var horizontalInset: CGFloat = 0
@IBInspectable var verticalInset: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset , dy: verticalInset)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}
}
usage:
&
It does matter, for example - there is a thing called character expansion
var s1 = "Strasse";
var s2 = "Straße";
s1.Equals(s2, StringComparison.Ordinal); //false
s1.Equals(s2, StringComparison.InvariantCulture); //true
With InvariantCulture
the ß character gets expanded to ss.
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is one way which I like because it makes the input fill out the whole container. The trick is the "font-size: 100px", and it need to go with the "overflow: hidden" and the relative position.
<div id="upload-file-container" >
<input type="file" />
</div>
#upload-file-container {
width: 200px;
height: 50px;
position: relative;
border: dashed 1px black;
overflow: hidden;
}
#upload-file-container input[type="file"]
{
margin: 0;
opacity: 0;
font-size: 100px;
}
The Transact-SQL control-of-flow language keywords are:
BEGIN
...END
BREAK
CONTINUE
GOTO
label
IF
...ELSE
RETURN
THROW
TRY
...CATCH
WAITFOR
WHILE
Simple and fast:
find . -mindepth 1 -maxdepth 1 -type d | parallel du -s | sort -n
*requires GNU Parallel.
Use Keystore Explorer gui - http://keystore-explorer.sourceforge.net/ - allows you to extract the private key from a .jks in various formats.
Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.
If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):
static class MutableInt {
int value = 1;
void inc() { ++value; }
int get() { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt>();
MutableInt value = map.get(key);
if (value == null) {
value = new MutableInt();
map.put(key, value);
} else {
value.inc();
}
If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned GNU Trove.
By the way, a good search term for this subject is "histogram".
char *p = "String"; means pointer to a string type variable.
char p3[5] = "String"
; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:
char p3[7]= "String";
Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:
Install the Android SDK:
sudo port install android
Run the SDK manager:
sh /opt/local/share/java/android-sdk-macosx/tools/android
As @brismuth suggested, uncheck everything but Android SDK Platform-tools
(optional)
Install the packages, accepting licenses. Close the SDK Manager.
Add platform-tools
to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools
. E.g., for bash:
echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
Refresh your bash profile (or restart your terminal/shell):
source ~/.bash_profile
Start using adb:
adb devices
This happens to me occasionally, usually it's just a simple oversight. Just pay attention to details, simple typos, etc. For example when copy/pasting import statements, like this:
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).attr('href', 'http://stackoverflow.com')
Building on the above, if anyone needs to handle errors in the write/read streams, I used this version. Note the stream.read()
in case of a write error, it's required so we can finish reading and trigger close
on the read stream.
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
if (err) callback(err, filename);
else {
var stream = request(uri);
stream.pipe(
fs.createWriteStream(filename)
.on('error', function(err){
callback(error, filename);
stream.read();
})
)
.on('close', function() {
callback(null, filename);
});
}
});
};
string result = System.Text.Encoding.UTF8.GetString(byteArray);
javac doesn't actively prohibit this, but it does have a limitation that pretty much means that you'd never want to refer to a top-level class from another file unless it has the same name as the file it's in.
Suppose you have two files, Foo.java and Bar.java.
Foo.java contains:
Bar.java contains:
Let's also say that all of the classes are in the same package (and the files are in the same directory).
What happens if Foo.java refers to Baz but not Bar and we try to compile Foo.java? The compilation fails with an error like this:
Foo.java:2: cannot find symbol
symbol : class Baz
location: class Foo
private Baz baz;
^
1 error
This makes sense if you think about it. If Foo.java refers to Baz, but there is no Baz.java (or Baz.class), how can javac know what source file to look in?
If you instead tell javac to compile Foo.java and Bar.java at the same time, or even if you had previously compiled Bar.java (leaving the Baz.class where javac can find it) then this error goes away. This makes your build process feel very unreliable and flaky, however.
Because the actual limitation, which is more like "don't refer to a top-level class from another file unless it has the same name as the file it's in or you're also referring to a class that's in that same file that's named the same thing as the file" is kind of hard to follow, people usually go with the much more straightforward (though stricter) convention of just putting one top-level class in each file. This is also better if you ever change your mind about whether a class should be public or not.
Sometimes there really is a good reason why everybody does something in a particular way.
You've almost got it. Tell jquery you want to load only the script:
$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html script");
});
That is because you are not fully qualifying your cells object. Try this
With Worksheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
Notice the DOT before Cells?
Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'
. My bad, I had a $instance::method()
that should have been $instance->method()
. Silly me.
The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.
So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.
If anybody can expand on why that is, please do.
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
I haven't tried specifically getting the VM settings, but there is a wealth of information in the JMX utilities specifically the MXBean utilities. This would be where I would start. Hopefully you find something there to help you.
The sun website has a bunch on the technology:
http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};
But it's rather unportable.
Put it in a div tag seems to be the only way to FORCE that:
<div style="vertical-align: middle"><div><input ... /></div></div>
May be other tags like span works as like div do.
In case I just want to know how many unique factor levels exist in the data, I use:
length(unique(df$factorcolumn))
If you are still looking for further more customization,
Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/
Thanks
All above answers are mainly based on use of virtualenv. I just have fresh installation of anaconda3 and don't have any virtualenv installed in it. So, I have found a better alternative to it without wondering about creating virtualenv.
If you have many pip and python version installed in linux, then first run below command to list all installed pip paths.
whereis pip
You will get something like this as output.
pip: /usr/bin/pip
/home/prabhakar/anaconda3/bin/pip
/usr/share/man/man1/pip.1.gz
Copy the path of pip which you want to use to install your package and paste it after sudo replacing /home/prabhakar/anaconda3/bin/pip
in below command.
sudo
/home/prabhakar/anaconda3/bin/pip
install<package-name>
This worked pretty well for me. If you have any problem installing, please comment.
Check out
bucket.get_key(
key_name,
headers=None,
version_id=None,
response_headers=None,
validate=True
)
Check to see if a particular key exists within the bucket. This method uses a HEAD request to check for the existence of the key. Returns: An instance of a Key object or None
from Boto S3 Docs
You can just call bucket.get_key(keyname) and check if the returned object is None.
Make sure you have DESERIALIZED objects like DATE/DATETIME etc. If you are directly sending JSON without deserializing it then it can cause this problem.
I use this quite often in hard realtime systems that have fairly insane update rates (50kilosamples/sec) As a result I typically precompute the scalars.
To compute a moving average of N samples: scalar1 = 1/N; scalar2 = 1 - scalar1; // or (1 - 1/N) then:
Average = currentSample*scalar1 + Average*scalar2;
Example: Sliding average of 10 elements
double scalar1 = 1.0/10.0; // 0.1
double scalar2 = 1.0 - scalar1; // 0.9
bool first_sample = true;
double average=0.0;
while(someCondition)
{
double newSample = getSample();
if(first_sample)
{
// everybody forgets the initial condition *sigh*
average = newSample;
first_sample = false;
}
else
{
average = (sample*scalar1) + (average*scalar2);
}
}
Note: this is just a practical implementation of the answer given by steveha above. Sometimes it's easier to understand a concrete example.
You need to create the element.
input = jQuery('<input name="myname">');
and then append it to the form.
jQuery('#formID').append(input);
to remove an input you use the remove functionality.
jQuery('#inputid').remove();
This is the basic idea, you may have feildsets that you append it too instead, or maybe append it after a specific element, but this is how to build anything dynamically really.
Try this:
$("#autoship_option option[selected]").removeAttr("selected");
Have a look at this example taken from the spring MVC showcase, this is the link to the source code:
@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {
@Test
public void readString() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
webAppContextSetup(this.wac).build()
.perform(fileUpload("/fileupload").file(file))
.andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
}
}
Are you missing a function declaration?
void ac_search(uint num_patterns, uint pattern_length, const char *patterns,
uint num_records, uint record_length, const char *records, int *matches, Node* trie);
Add it just before your implementation of ac_benchmark_search.
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance()
calls, after you have decided what exactly you mean with "the same day".
And yes, Joda Time's LocalDate
would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).
From what you've told us it does appear to be a false positive in valgrind. The new
syntax with ()
should value-initialize the object, assuming it is POD.
Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?
Alternately perhaps your compiler doesn't actually value-initialize POD structures.
In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.
type normal division first and then type shift + S->d
This is not a solution to the complete problem but oracle has good detailed documentation on how to use this keytool. This explains how to
https://docs.oracle.com/cd/E54932_01/doc.705/e54936/cssg_create_ssl_cert.htm#CSVSG178
There is some other program listening on port 80, usual suspects are
Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.
Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)
C:\Users\vinko>netstat -ao -p tcp
Conexiones activas
Proto Dirección local Dirección remota Estado PID
TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388
TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168
TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168
TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168
TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168
TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4
TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388
TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388
TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388
If you want to Disable Skype from listening on port 80 and 443, you can follow the link http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/
Look into xcopy, which will recursively copy files and subdirectories.
There are examples, 2/3 down the page. Of particular use is:
To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:
xcopy a: b: /s /e
The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo
which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval
which is way too heavy and hacky.
The proper way to do this is to put the top level stuff in a function and use a local
with bash's dynamic scoping rule. Example:
func1()
{
ret_val=hi
}
func2()
{
ret_val=bye
}
func3()
{
local ret_val=nothing
echo $ret_val
func1
echo $ret_val
func2
echo $ret_val
}
func3
This outputs
nothing
hi
bye
Dynamic scoping means that ret_val
points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):
Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.
For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout
/stderr
, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.
So instead of writing your script like this:
top-level code
bunch of functions
more top-level code
write it like this:
# define your main, containing all top-level code
main()
bunch of functions
# call main
main
where main()
declares ret_val
as local
and all other functions return values via ret_val
.
See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.
Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n
.
According to the Documentation :
MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message
Here MailAddressCollection has a in built method called
public void Add(string addresses)
1. Summary:
Add a list of email addresses to the collection.
2. Parameters:
addresses:
*The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
*email addresses must be separated with a comma character (",").
Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma
In your case :
simply replace all the ; with ,
Msg.To.Add(toEmail.replace(";", ","));
For reference :
SELECT SUBSTR(TRIM(rtp.role),1,12) AS ROLE
, SUBSTR(rp.grantee,1,16) AS GRANTEE
, SUBSTR(TRIM(rtp.privilege),1,12) AS PRIVILEGE
, SUBSTR(TRIM(rtp.owner),1,12) AS OWNER
, SUBSTR(TRIM(rtp.table_name),1,28) AS TABLE_NAME
, SUBSTR(TRIM(rtp.column_name),1,20) AS COLUMN_NAME
, SUBSTR(rtp.common,1,4) AS COMMON
, SUBSTR(rtp.grantable,1,4) AS GRANTABLE
, SUBSTR(rp.default_role,1,16) AS DEFAULT_ROLE
, SUBSTR(rp.admin_option,1,4) AS ADMIN_OPTION
FROM role_tab_privs rtp
LEFT JOIN dba_role_privs rp
ON (rtp.role = rp.granted_role)
WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
ORDER BY 1
, 2
, 3
, 4
;
SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.
In simple:
Git - is local repository.
GitHub - is central repository.
Use media queries to separate each browser:
/* IE6/7 uses media, */
@media, {
.dude { color: green; }
.gal { color: red; }
}
/* IE8 uses \0 */
@media all\0 {
.dude { color: brown; }
.gal { color: orange; }
}
/* IE9 uses \9 */
@media all and (monochrome:0) {
.dude { color: yellow\9; }
.gal { color: blue\9; }
}
/* IE10 and IE11 both use -ms-high-contrast */
@media all and (-ms-high-contrast:none)
{
.foo { color: green } /* IE10 */
*::-ms-backdrop, .foo { color: red } /* IE11 */
}
References
Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>
. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx">
The resulting contents are :
Component1.html
<nav>
<a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
<router-outlet></router-outlet>
Component2.html
<a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ... </a>
<a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]"> In Two...Go to 4 ...</a>
<router-outlet name="nameThree"></router-outlet>
<router-outlet name="nameFour"></router-outlet>
The '/two'
represents the parent component and ['three']
and ['four']
represents the link to the respective children of component2
. Component3.html and Component4.html are the same as in the question.
router.module.ts
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree'
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
}
]
},];
You have to use ==
to compare (or even ===
, if you want to compare types). A single =
is for assignment.
if (one == 'rock' && two == 'rock') {
console.log('Tie! Try again!');
}
To format code in-line within your text, use the '`' character to surround your code. Usually located to the left of the '1' key on your keyboard.
Example:
`printf("Hello World");`
Same delimiter as Stack Exchange!
I'm using mongojs, and i have this example:
db.users.findOne({'_id': db.ObjectId(user_id) }, function(err, user) {
if(err == null && user != null){
user._id.toHexString(); // I convert the objectId Using toHexString function.
}
})
I hope this help.
I hit the same problem with "Visual Studio 2013".
LNK1104: cannot open file 'debug\****.exe
It resolved after closing and re-starting Visual studio.
Query :
$sqlQuery = "UPDATE
update_table
SET
set_name = 'value'
WHERE
where_name = 'name'
LIMIT 1;";
PHP function:
function updateAndGetId($sqlQuery)
{
mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
return mysql_insert_id();
}
It's work for me ;)
Using the accepted answer to create an alias
oops = "!f(){ \
git add -A; \
if [ \"$1\" == '' ]; then \
git commit --amend --no-edit; \
else \
git commit --amend \"$@\"; \
fi;\
}; f"
then you can do
git oops
and it will add everything, and amend using the same message
or
git oops -m "new message"
to amend replacing the message
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
A simple "FOR" can be used in a single line to use an "or" condition:
FOR %%a in (item1 item2 ...) DO IF {condition_involving_%%a} {execute_command}
Applied to your case:
FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE
A comment pointed out that {execute_command}
may be encountered twice. To avoid this, you can use a goto after the first encounter.
FOR %%a in (1 2) DO IF %var%==%%a (
ECHO TRUE
goto :continue
)
:continue
If you think there's a possibility that {execute_command}
might be executed twice and you don't want that, you can just add && goto :eof
:
FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE && goto :eof
Much simpler, and still on a single line.
You need to use the AND function for the multiple conditions:
=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))
Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.
In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem
$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root 37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root 2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root 88 Jan 18 17:34 nss.cfg
So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)
$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts
I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.
regards lellis
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
FirePHP can be useful as well.
Using JQuery you can disable scrolling bar with this code :
$('body').on({
'mousewheel': function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
}
});
Also you can enable it again with this code :
$('body').unbind('mousewheel');
Except that it will not work if your user name and database name are differents. It sounds like an SQLDeveloper bug and i can't find any workaroud
Maybe there are some bugs in Oracle SQL Developer when it connect to the postgresql.However I connect postgresql with navicat successfully.(My postgresql username and database name are different
The way I have found to do this is use the onRestoreInstanceState
and the onSaveInstanceState
events to save something in the Bundle
(even if you dont need any variables saved, just put something in there so the Bundle
isn't empty). Then, on the onCreate
method, check to see if the Bundle
is empty, and if it is, then do the initialization, if not, then do it.
The trick is defining the masksToBounds
property of your view's layer properly:
view.layer.masksToBounds = NO;
and it should work.
(Source)
Array can only be used for specific types, whereas lists can be used for any object.
Arrays can also only data of one type, whereas a list can have entries of various object types.
Arrays are also more efficient for some numerical computation.
TL;DR: - grab the datatable from the dataset and read from the rows property.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn col = new DataColumn("Id", typeof(int));
dt.Columns.Add(col);
dt.Rows.Add(new object[] { 1 });
ds.Tables.Add(dt);
var row = ds.Tables[0].Rows[0];
//access the ID column.
var id = (int) row.ItemArray[0];
A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.
Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.
If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.
If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.
You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.
After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.
When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:
MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
//do some other work
The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!
Have you looked into easy_install at all? It won't synchronize your macports or anything like that, but it will automatically download the latest package and all necessary dependencies, i.e.
easy_install nose
for the nose unit testing package, or
easy_install trac
for the trac
bug tracker.
There's a bit more information on their EasyInstall page too.
3306 is default port for mysql. Check it with:
netstat -nl|grep 3306
it should give this result:
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
The official pattern to implement IDisposable
is hard to understand. I believe this one is better:
public class BetterDisposableClass : IDisposable {
public void Dispose() {
CleanUpManagedResources();
CleanUpNativeResources();
GC.SuppressFinalize(this);
}
protected virtual void CleanUpManagedResources() {
// ...
}
protected virtual void CleanUpNativeResources() {
// ...
}
~BetterDisposableClass() {
CleanUpNativeResources();
}
}
An even better solution is to have a rule that you always have to create a wrapper class for any unmanaged resource that you need to handle:
public class NativeDisposable : IDisposable {
public void Dispose() {
CleanUpNativeResource();
GC.SuppressFinalize(this);
}
protected virtual void CleanUpNativeResource() {
// ...
}
~NativeDisposable() {
CleanUpNativeResource();
}
}
With SafeHandle
and its derivatives, these classes should be very rare.
The result for disposable classes that don't deal directly with unmanaged resources, even in the presence of inheritance, is powerful: they don't need to be concerned with unmanaged resources anymore. They'll be simple to implement and to understand:
public class ManagedDisposable : IDisposable {
public virtual void Dispose() {
// dispose of managed resources
}
}
I found my git.exe
here
C:\Program Files\Git\bin\git.exe
while installing git
, it asks for the location. copy it and use it.
The following commands will work well for ruby on rails application deployment on heroku if heroku is already installed on developers machine. # indicates a comment
The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window
<!DOCTYPE html>
<html>
<body>
<center><h2>Heading</h2></center>
<center><p>Paragraph</p></center>
<iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
</body>
</html>
EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all
exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.
You can also simply significantly with:
.nav a {
transition: all .2s;
}
FWIW: all
is implied if not specified, so transition: .2s;
will get you to the same place.
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
It helps to prevent sticky execution
var done = false;
function doItOnce(func){
if(!done){
done = true;
func()
}
setTimeout(function(){
done = false;
},1000)
}
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
This is an old question, but here is something that might help someone.
From the official docs:
Django provides tools for performing URL reversing that match the different layers where URLs are needed: In templates: Using the url template tag. In Python code: Using the reverse() function. In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.
Eg. in templates (url tag)
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
Eg. in python code (using the reverse
function)
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
Direct links to source for some popular programs in coreutils
:
cat
(767 lines)chmod
(570 lines)cp
(2912 lines)cut
(831 lines)date
(570 lines)df
(1718 lines)du
(1112 lines)echo
(272 lines)head
(1070 lines)hostname
(116 lines)kill
(312 lines)ln
(651 lines)ls
(4954 lines)md5sum
(878 lines)mkdir
(306 lines)mv
(512 lines)nice
(220 lines)pwd
(394 lines)rm
(356 lines)rmdir
(252 lines)shred
(1325 lines)tail
(2301 lines)tee
(220 lines)touch
(437 lines)wc
(801 lines)whoami
(91 lines)Just for the sake of adding functions to the Date
prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
I'm turning my comment to an answer, so it can be accepted and this question no longer remains unanswered.
The most likely cause of this is a malformed response, which includes characters before the initial <?xml …>
. So please have a look at the document as transferred over HTTP, and fix this on the server side.
Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage
, supported by all browsers
Xcode 9.0.1, swift 4.0
Data
import Foundation
let array = [0,1,2,3,4,5,6,7,8]
Solution 1
extension Int {
func getString(prefix: Int) -> String {
return "\(prefix)\(self)"
}
func getString(prefix: String) -> String {
return "\(prefix)\(self)"
}
}
for item in array {
print(item.getString(prefix: 0))
}
for item in array {
print(item.getString(prefix: "0x"))
}
Solution 2
for item in array {
print(String(repeatElement("0", count: 2)) + "\(item)")
}
Solution 3
extension String {
func repeate(count: Int, string: String? = nil) -> String {
if count > 1 {
let repeatedString = string ?? self
return repeatedString + repeate(count: count-1, string: repeatedString)
}
return self
}
}
for item in array {
print("0".repeate(count: 3) + "\(item)")
}
see the code below of arraylist default it is 10 when u create List l = new ArrayList();
public class ArrayList<E> extends AbstractList<E> implements List<E>,
Cloneable, Serializable, RandomAccess {
private static final long serialVersionUID = 8683452581122892189L;
private transient int firstIndex;
private transient int lastIndex;
private transient E[] array;
/**
* Constructs a new instance of {@code ArrayList} with ten capacity.
*/
public ArrayList() {
this(10);
}
I found it much easier to use tokens than SSH keys. I couldn't find much good documentation on this, so I came across this solution mainly through trial and error. Further, installing from pip and setuptools have some subtle differences; but this way should work for both.
GitHub don't (currently, as of August 2016) offer an easy way to get the zip / tarball of private repositories. So you need to point setuptools to tell setuptools that you're pointing to a Git repository:
from setuptools import setup
import os
# Get the deploy key from https://help.github.com/articles/git-automation-with-oauth-tokens/
github_token = os.environ['GITHUB_TOKEN']
setup(
# ...
install_requires='package',
dependency_links = [
'git+https://{github_token}@github.com/user/{package}.git/@{version}#egg={package}-0'
.format(github_token=github_token, package=package, version=master)
]
A couple of notes here:
0
) at the end of the link, even if there's isn't any package on PyPI. This has to be a actual number, not a word.git+
to tell setuptools it's to clone the repository, rather than pointing at a zip / tarballversion
can be a branch, a tag, or a commit hash--process-dependency-links
if installing from pipHit Esc and then press: Shift + G
I think using multiple Jframe
s is not a good idea.
Instead we can use JPanel
s more than one or more JPanel
in the same JFrame
.
Also we can switch between this JPanel
s. So it gives us freedom to display more than on thing in the JFrame
.
For each JPanel
we can design different things and all this JPanel
can be displayed on the single JFrame
one at a time.
To switch between this JPanel
s use JMenuBar
with JMenuItems
for each JPanel
or 'JButtonfor each
JPanel`.
More than one JFrame
is not a good practice, but there is nothing wrong if we want more than one JFrame
.
But its better to change one JFrame
for our different needs rather than having multiple JFrame
s.
You can use ~
like {{ foo ~ 'inline string' ~ bar.fieldName }}
But you can also create your own concat
function to use it like in your question:
{{ concat('http://', app.request.host) }}
:
In src/AppBundle/Twig/AppExtension.php
<?php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
];
}
public function concat()
{
return implode('', func_get_args())
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'app_extension';
}
}
In app/config/services.yml
:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
a.update(b)
Will add keys and values from b to a, overwriting if there's already a value for a key.
.getCellType() != Cell.CELL_TYPE_BLANK
Is this role attribute necessary?
Answer: Yes.
It provides you:
Python lets you put the indented clause on the same line if it's only one line:
if "exam" in example: print "yes!"
def squared(x): return x * x
class MyException(Exception): pass
Ok, this might be a little after the fact, but .promise() should also achieve what you're after.
An example from a project i'm working on:
$( '.panel' )
.fadeOut( 'slow')
.promise()
.done( function() {
$( '#' + target_panel ).fadeIn( 'slow', function() {});
});
:)
The update from 3.2.x to 3.3.x broke some of the solutions explained here and on other threads because of the change: "Added transforms to improve carousel performance in modern browsers."
If you are using Bootstrap 3.3.x there's a solution here:
http://codepen.io/transportedman/pen/NPWRGq
Basically you need to add the "carousel-fade" class to your carousel so that you have:
<div class="carousel slide carousel-fade">
And then include the following CSS:
/*
Bootstrap Carousel Fade Transition (for Bootstrap 3.3.x)
CSS from: http://codepen.io/transportedman/pen/NPWRGq
and: http://stackoverflow.com/questions/18548731/bootstrap-3-carousel-fading-to-new-slide-instead-of-sliding-to-new-slide
Inspired from: http://codepen.io/Rowno/pen/Afykb
*/
.carousel-fade .carousel-inner .item {
opacity: 0;
transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-control {
z-index: 2;
}
/*
WHAT IS NEW IN 3.3: "Added transforms to improve carousel performance in modern browsers."
Need to override the 3.3 new styles for modern browsers & apply opacity
*/
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-fade .carousel-inner > .item.next,
.carousel-fade .carousel-inner > .item.active.right {
opacity: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-inner > .item.prev,
.carousel-fade .carousel-inner > .item.active.left {
opacity: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-inner > .item.next.left,
.carousel-fade .carousel-inner > .item.prev.right,
.carousel-fade .carousel-inner > .item.active {
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
Try this
@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}
Executing:
java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);
before hibernate's initialization worked for me.
Note: the line above will turn every logging off (Level.OFF
). If you want to be less strict, you can use
java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
that is silent enough. (Or check the java.util.logging.Level
class for more levels).
Just code it like this:
.OwnerJoe {
//other things here
&:before{
content: "Joe's Task: ";
}
}
just try
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
Simple Way
if ($('#text-field > p.filled-text').length != 0)
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Main purpose for Boolean is null value. Null value says, that property is undefined, for example take database nullable column.
If you really need to convert everyting from primitive boolean to wrapper Boolean, then you could use following to support old code:
Boolean set = Boolean.FALSE; //set to default value primitive value (false)
...
if (set) ...
This happened to me on a partition of type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
, where the directories where owned by another user in a group we were both members of. The group membership was already established before login, and the whole directory structure was group-writeable. I had manually run sudo chown -R otheruser.group directory
and sudo chmod -R g+rw directory
to confirm this.
I still have no idea why it didn't work originally, but taking ownership with sudo chown -R myuser.group directory
fixed it. Perhaps SELinux-related?
The install.packages command looks through the .libPaths variable. Here's what mine defaults to on OSX:
> .libPaths()
[1] "/Library/Frameworks/R.framework/Resources/library"
I don't install packages there by default, I prefer to have them installed in my home directory. In my .Rprofile, I have this line:
.libPaths( "/Users/tex/lib/R" )
This adds the directory "/Users/tex/lib/R" to the front of the .libPaths variable.
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.
I guess there mmust be some kind of dependency with this app.
Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager
and EntityManagerFactory
, without explicit Spring dependencies in your code:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa
This allows you to either inject the EntityManagerFactory
, or else inject a thread-safe, transactional proxy of an EntityManager
directly. The latter makes for simpler code, but means more Spring plumbing is required.
Regarding the original question asked in the title ...
sudo apt-get install libtcnative-1
or if you are on RHEL Linux yum install tomcat-native
The documentation states you need http://tomcat.apache.org/native-doc/
sudo apt-get install libapr1.0-dev libssl-dev
yum install apr-devel openssl-devel
post_max_size should be slightly bigger than upload_max_filesize, because when uploading using HTTP POST method the text also includes headers with file size and name, etc.
If you want to successfully uppload 1GiB files, you have to set:
upload_max_filesize = 1024M
post_max_size = 1025M
Note, the correct suffix for GB is G, i.e. upload_max_filesize = 1G.
No need to set memory_limit.
It should be at least this:
public function login(Request $loginCredentials){
$data = $loginCredentials->all();
return $data['username'];
}