Create a separate ul.nav
for just that list item and float that ul
right.
SELECT b.BatchID,
x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);
Demo: SQLFiddle
Move these two lines:
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
out of your AsyncTask's doInBackground
method and put them in the onPostExecute
method. Your AsyncTask
should look something like this:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(5000); // no need for a loop
} catch (InterruptedException e) {
Log.e("LongOperation", "Interrupted", e);
return "Interrupted";
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}
Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
you can set the x-frame-option in web config of the site you want to load in iframe like this
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="*" />
</customHeaders>
</httpProtocol>
It looks like your error is coming from the outer index.js file, not this one. Are you importing this one as './app/containers'
? because it should just be './containers'
.
From the Node.js documentation:
Node provides a tri-directional popen(3) facility through the ChildProcess class.
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
git add myfile.h
git commit -m "your commit message"
git push -u origin master
if you don't remember all the files you need to update, use
git status
EDIT: Firefox and Google Chrome now have a built-in JSON
object, so you can just say alert(JSON.stringify(myArray))
without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON
object being present in all browsers, but for debugging purposes it's incredibly useful.
I tend to use the jQuery-json plugin as follows:
alert( $.toJSON(myArray) );
This prints the array in a format like
[5, 6, 7, 11]
However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.
Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.
It appears that there is no "unlimited" value. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
As as already been observed, 17,000 records are hard to use well in the browser. If you are presenting an aggregate view it may be much more efficient to do the aggregation on the server and transfer only a summary in the browser. For example, consider a file system brower, we only see the top of the tree, then emit further requestes as we drill down. The number of records returned in each request is comparatively small. A tree view presentation can work well for large result sets.
I ran into this while I was learning Go 2 years ago, so I declared my own function.
// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}
And then you can use it like so:
UNUSED(x)
UNUSED(x, y)
UNUSED(x, y, z)
The great thing about it is, you can pass anything into UNUSED.
Is it better than the following?
_, _, _ = x, y, z
That's up to you.
For powershell, this will work:
git branch --format '%(refname:lstrip=2)' --merged `
| Where-Object { $_ -ne 'master' } `
| ForEach-Object { git branch -d $_ }
#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);
void SuspendSelf(){
NtSuspendProcess(GetCurrentProcess());
}
ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.
If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.
To set password enabled in EditText, We will have to set an "inputType" attribute in xml file.If we are using only EditText then we will have set input type in EditText as given in below code.
<EditText
android:id="@+id/password_Edit"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="password"
android:imeOptions="actionNext"
android:inputType="textPassword"
android:maxLength="100"
android:nextFocusDown="@+id/next"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Password enable attribute is
android:inputType="textPassword"
But if we are implementing Password EditText with Material Design (With Design support library) then we will have write code as given bellow.
<android.support.design.widget.TextInputLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/txtInput_currentPassword"
android:layout_width="match_parent"
app:passwordToggleEnabled="false"
android:layout_height="wrap_content">
<EditText
android:id="@+id/password_Edit"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="@string/hint_currentpassword"
android:imeOptions="actionNext"
android:inputType="textPassword"
android:maxLength="100"
android:nextFocusDown="@+id/next"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.TextInputLayout>
@Note: - In Android SDK 24 and above, "passwordToggleEnabled" is by default true. So if we have the customs handling of show/hide feature in the password EditText then we will have to set it false in code as given above in .
app:passwordToggleEnabled="true"
To add above line, we will have to add below line in root layout.
xmlns:app="http://schemas.android.com/apk/res-auto"
Linting is the process of running a program that will analyse code for potential errors.
See lint on wikipedia:
lint was the name originally given to a particular program that flagged some suspicious and non-portable constructs (likely to be bugs) in C language source code. The term is now applied generically to tools that flag suspicious usage in software written in any computer language.
No nonsense script this:
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSforeachtable 'DBCC CHECKIDENT ( ''?'', RESEED, 0)'
GO
Truncate will still not work if you have foreign keys in tables. This script will reset all identity columns as well.
To add to @Christian's comment:
Replace all single or double quotes in a string:
s = "'asdfa sdfa'"
import re
re.sub("[\"\']", "", s)
It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date)
for your queries and add an index expression for this if you find it running slow.
I was facing the same problem. For my solution, I added br
enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:
+"<br>"+
Try this in your browser and see, it certainly works in my Internet Explorer.
Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.
The best way is to create a person-component
and watch every person separately inside its own component, as shown below:
<person-component :person="person" v-for="person in people"></person-component>
Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit
to send an event upwards, containing the id
of modified person.
Vue.component('person-component', {_x000D_
props: ["person"],_x000D_
template: `_x000D_
<div class="person">_x000D_
{{person.name}}_x000D_
<input type='text' v-model='person.age'/>_x000D_
</div>`,_x000D_
watch: {_x000D_
person: {_x000D_
handler: function(newValue) {_x000D_
console.log("Person with ID:" + newValue.id + " modified")_x000D_
console.log("New age: " + newValue.age)_x000D_
},_x000D_
deep: true_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
people: [_x000D_
{id: 0, name: 'Bob', age: 27},_x000D_
{id: 1, name: 'Frank', age: 32},_x000D_
{id: 2, name: 'Joe', age: 38}_x000D_
]_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
<div id="app">_x000D_
<p>List of people:</p>_x000D_
<person-component :person="person" v-for="person in people"></person-component>_x000D_
</div>_x000D_
</body>
_x000D_
Start Activity2 with startActivityForResult
and use setResult
method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult
for updating TextView
with EditText
data from Activity2.
For example:
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult
for sending data back:
Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult
:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strEditText = data.getStringExtra("editTextValue");
}
}
}
If you can, also use SharedPreferences for sharing data between Activities.
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
>>> print sorted(d.keys())
['a', 'b', 'c']
Use the sorted function, which sorts the iterable passed in.
The .keys()
method returns the keys in an arbitrary order.
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
Asset.objects.filter( project__name__contains="Foo" )
There is a python package for this Autopy
The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).
You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.
Assuming:
<div id="a" class="a"></div>
this:
$('div.a')[0] == $('div#a')[0]
returns true.
// ---------------------------------------------------------- Generic Confirm
function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
var confirmModal =
$('<div class="modal hide fade">' +
'<div class="modal-header">' +
'<a class="close" data-dismiss="modal" >×</a>' +
'<h3>' + heading +'</h3>' +
'</div>' +
'<div class="modal-body">' +
'<p>' + question + '</p>' +
'</div>' +
'<div class="modal-footer">' +
'<a href="#" class="btn" data-dismiss="modal">' +
cancelButtonTxt +
'</a>' +
'<a href="#" id="okButton" class="btn btn-primary">' +
okButtonTxt +
'</a>' +
'</div>' +
'</div>');
confirmModal.find('#okButton').click(function(event) {
callback();
confirmModal.modal('hide');
});
confirmModal.modal('show');
};
// ---------------------------------------------------------- Confirm Put To Use
$("i#deleteTransaction").live("click", function(event) {
// get txn id from current table row
var id = $(this).data('id');
var heading = 'Confirm Transaction Delete';
var question = 'Please confirm that you wish to delete transaction ' + id + '.';
var cancelButtonTxt = 'Cancel';
var okButtonTxt = 'Confirm';
var callback = function() {
alert('delete confirmed ' + id);
};
confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);
});
What you need is nm
and its -D
option:
$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
U atanf
U calloc
.
.
.
Exported sumbols are indicated by a T
. Required symbols that must be loaded from other shared objects have a U
. Note that the symbol table does not include just functions, but exported variables as well.
See the nm
manual page for more information.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
int g[] = {9,8};
This declares an object of type int[2], and initializes its elements to {9,8}
int (*j) = g;
This declares an object of type int *, and initializes it with a pointer to the first element of g.
The fact that the second declaration initializes j with something other than g is pretty strange. C and C++ just have these weird rules about arrays, and this is one of them. Here the expression g
is implicitly converted from an lvalue referring to the object g into an rvalue of type int*
that points at the first element of g.
This conversion happens in several places. In fact it occurs when you do g[0]
. The array index operator doesn't actually work on arrays, only on pointers. So the statement int x = j[0];
works because g[0]
happens to do that same implicit conversion that was done when j
was initialized.
A pointer to an array is declared like this
int (*k)[2];
and you're exactly right about how this would be used
int x = (*k)[0];
(note how "declaration follows use", i.e. the syntax for declaring a variable of a type mimics the syntax for using a variable of that type.)
However one doesn't typically use a pointer to an array. The whole purpose of the special rules around arrays is so that you can use a pointer to an array element as though it were an array. So idiomatic C generally doesn't care that arrays and pointers aren't the same thing, and the rules prevent you from doing much of anything useful directly with arrays. (for example you can't copy an array like: int g[2] = {1,2}; int h[2]; h = g;
)
Examples:
void foo(int c[10]); // looks like we're taking an array by value.
// Wrong, the parameter type is 'adjusted' to be int*
int bar[3] = {1,2};
foo(bar); // compile error due to wrong types (int[3] vs. int[10])?
// No, compiles fine but you'll probably get undefined behavior at runtime
// if you want type checking, you can pass arrays by reference (or just use std::array):
void foo2(int (&c)[10]); // paramater type isn't 'adjusted'
foo2(bar); // compiler error, cannot convert int[3] to int (&)[10]
int baz()[10]; // returning an array by value?
// No, return types are prohibited from being an array.
int g[2] = {1,2};
int h[2] = g; // initializing the array? No, initializing an array requires {} syntax
h = g; // copying an array? No, assigning to arrays is prohibited
Because arrays are so inconsistent with the other types in C and C++ you should just avoid them. C++ has std::array
that is much more consistent and you should use it when you need statically sized arrays. If you need dynamically sized arrays your first option is std::vector.
If you are using Toolbar, you don't need those solutions. You only have to change the theme of the toolbar
app:theme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
If you are using a dark.actionBar your back button is going to be white else if you are using light actionbar theme it is going to be black.
try out this if you want to assign value to object and it is showing this error in angular..
crate object in construtor
this.modelObj = new Model();
//<---------- after declaring object above
In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.
See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.
You're thinking of a continue
statement like Java's or Python's, but VBA has no such native statement, and you can't use VBA's Next
like that.
You could achieve something like what you're trying to do using a GoTo
statement instead, but really, GoTo
should be reserved for cases where the alternatives are contrived and impractical.
In your case with a single "continue" condition, there's a really simple, clean, and readable alternative:
If Not InStr(sname, "Configuration item") Then
'// other code to copy paste and do various stuff
End If
If you're using underscore.js then you can use the _.isEmpty function:
var obj = {};
var emptyObject = _.isEmpty(obj);
It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.
Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.
function showHideColumns() {
$('#jqGrid').jqGrid('columnChooser', {
width: 250,
dialog_opts: {
modal: true,
minWidth: 250,
height: 300,
show: 'blind',
hide: 'explode',
dividerLocation: 0.5
} });
Add <br style="clear: both" />
after the last floated div worked for me.
The problem could be in the path of the file you want to open. Try and print the path and see if it is fine I had a similar problem
def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
filenm=filenm.split("?")[0]
filenm=("{}.html").format(filenm)
print("Converted a file into html that was not compatible")
if ".aspx" in htm:
htm=htm.replace(".aspx",".aspx.html")
print("[process]...conversion fron aspx")
if ".jsp" in htm:
htm=htm.replace(".jsp",".jsp.html")
print("[process]..conversion from jsp")
if ".php" in htm:
htm=htm.replace(".php",".php.html")
print("[process]..conversion from php")
output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))
but after adding this code:
nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
filenm=("{}index.html").format(filenm)
Use x=as.name("string")
. You can use then use x
to refer to the variable with name string.
I don't know, if it answers your question correctly.
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
Just to add, we can use array as well:
int i, array[4];
printf("Enter Four Ints: ");
for(i=0; i<4; i++) {
scanf("%d", &array[i]);
}
To do this you should alter the vertical-align property of the input.
<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>
Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:
<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>
You could also try this function. Can't remember the original author, but all credits goes to him/her.
Works like a charm - 100% the same as var_dump in PHP.
Check it out.
function dump(arr,level) {_x000D_
var dumped_text = "";_x000D_
if(!level) level = 0;_x000D_
_x000D_
//The padding given at the beginning of the line._x000D_
var level_padding = "";_x000D_
for(var j=0;j<level+1;j++) level_padding += " ";_x000D_
_x000D_
if(typeof(arr) == 'object') { //Array/Hashes/Objects_x000D_
for(var item in arr) {_x000D_
var value = arr[item];_x000D_
_x000D_
if(typeof(value) == 'object') { //If it is an array,_x000D_
dumped_text += level_padding + "'" + item + "' ...\n";_x000D_
dumped_text += dump(value,level+1);_x000D_
} else {_x000D_
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";_x000D_
}_x000D_
}_x000D_
} else { //Stings/Chars/Numbers etc._x000D_
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";_x000D_
}_x000D_
return dumped_text;_x000D_
}_x000D_
_x000D_
_x000D_
// Example:_x000D_
_x000D_
var employees = [_x000D_
{ id: '1', sex: 'm', city: 'Paris' }, _x000D_
{ id: '2', sex: 'f', city: 'London' },_x000D_
{ id: '3', sex: 'f', city: 'New York' },_x000D_
{ id: '4', sex: 'm', city: 'Moscow' },_x000D_
{ id: '5', sex: 'm', city: 'Berlin' }_x000D_
]_x000D_
_x000D_
_x000D_
// Open dev console (F12) to see results:_x000D_
_x000D_
console.log(dump(employees));
_x000D_
Nobody has posted the simplest answer:
x[!x %in% boxplot.stats(x)$out]
Also see this: http://www.r-statistics.com/2011/01/how-to-label-all-the-outliers-in-a-boxplot/
you can also just change your delete to a select *
and test your selection
the records selected will be the same as the ones deleted
you can also wrap your statement in a begin / rollback if you are not sure - test the statement then if all is good remove rollback
for example
SELECT * FROM table WHERE id BETWEEN 79 AND 296
will show all the records matching the where if they are the wants you 'really' want to delete then use
DELETE FROM table WHERE id BETWEEN 79 AND 296
You can also create a trigger / which catches deletes and puts them into a history table
so if you delete something by mistake you can always get it back
(keep your history table records no older than say 6 months or whatever business rules say)
The correct solution that i get is
<html>
<head>
<script type="text/javascript" language="JavaScript">
function clickedButton()
{
window.location = 'new url'
}
</script>
</head>
<form name="login_form" method="post">
..................
<input type="button" value="Login" onClick="clickedButton()"/>
</form>
</html>
Here the new url is given inside the single quote.
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Select-Object Size,FreeSpace
$disk.Size
$disk.FreeSpace
To extract the values only and assign them to a variable:
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Foreach-Object {$_.Size,$_.FreeSpace}
You can use CSS to hide the button.
button {
visibility: hidden;
}
If your <button>
is just a clickable area on the image, why bother make it a button? You can use <map>
element instead.
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
To prove my point further, here's the code from Reflector for Enumerable.Count()
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
What worked for me was: git branch --set-upstream-to=origin master When I did a pull again I only got the updates from master and the warning went away.
For Http Request Default Port number is 80
For Https Default Port Number is 443
For Sql Server Default Port Number is 1433
Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();
It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();
Here's the results of MY homework. It doesn't ensure the input is in the right range and I probably should be using StringBuilder
(time I looked it up!) and isn't one single method. But if anyone is reading this far I'd appreciate both positive and negative feedback on it!
import java.util.Scanner;
/**
*Main() allows user input and tests 1-3999
*toRoman() breaks the number down into digits and passes them to romanLogic()
*romanLogic() converts each digit into a the numerals that represent it.
*/
public class RomanNumerals
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("give us an integer < 4000: ");
System.out.println("the roman numeral version is: " + toRoman(in.nextInt()));
for (int i = 1; i<=3999; i++){
System.out.println(i +" === "+ toRoman(i));
}
}
public static String toRoman(int i){
String output = "";
int digits = i%10;
int tens = (i%100)/10;
int hundreds = (i%1000)/100;
int thousands = (i%10000)/1000;
return (romanLogic(thousands, "M","","")+
romanLogic(hundreds,"C","D","M")+
romanLogic(tens,"X","L","C")+
romanLogic(digits,"I","V","X"));
}
public static String romanLogic(int i, String ones, String fives, String tens){
String result = "";
if (i == 0){
return result;
} else {
if ((i>=4)&&(i<=8)){
result += fives;
}
if (i==9){
result += tens;
}
if(i%5 < 4){
while(i%5 > 0){
result += ones;
i--;
}
}
if(i%5 == 4){
result = ones + result;
}
}
return result;
}
}
If you just want to use proxy on a specified repository, don't need on other repositories. The preferable way is the -c, --config <key=value>
option when you git clone
a repository. e.g.
$ git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git --config "http.proxy=proxyHost:proxyPort"
If your shell supports it, would something like this work ?
javac com/**/*.java
If your shell does not support **
, then maybe
javac com/*/*/*.java
works (for all packages with 3 components - adapt for more or less).
I'm probably a bit late to the party, but I wrote the junitcategorizer for my thesis project at TOPdesk. Earlier versions indeed used a company internal Parent POM. So your problems are caused by the Parent POM not being resolvable, since it is not available to the outside world.
You can either:
<parent>
block, but then have to configure the Surefire, Compiler and other plugins yourself<parent>
<groupId>com.topdesk</groupId>
<artifactId>open-source-parent</artifactId>
<version>1.2.0</version>
</parent>
none of the above answers worked for me. This one did:
=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s
):
@reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
@reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
I like to use:
(strlen(string) + 1 ) * sizeof(char)
This will give you the buffer size in bytes. You can use this with snprintf() may help:
const char* message = "%s, World!";
char* string = (char*)malloc((strlen(message)+1))*sizeof(char));
snprintf(string, (strlen(message)+1))*sizeof(char), message, "Hello");
Cheers! Function: size_t strlen (const char *s)
I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:
fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
The solution from @VonC on this thread didn't work for me.
The solution from this Fabian Lee's article solved it for me:
openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt
If you're using Maven and don't want to link Tomcat in the Targeted Runtimes in Eclipse, you can simply add the dependency with scope provided in your pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
This can be done in a very way using Java 8:
Files.lines(Paths.get(file))
.flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
.filter(s->s.length()>0).count();
In the component.css or app.css add Icon Color styles
.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }
In the component.html set the icon class
<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>
ng build
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
See String formatting in C# for some example uses of String.Format
Actually a better example of formatting int
String.Format("{0:00000}", 15); // "00015"
or use String Interpolation:
$"{15:00000}"; // "00015"
From a book named OCA Java SE 7 Programmer I:
The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.
Best avoid casting by declaring f to be f the correct type to correspond to the JSON.
You can't access element like you did (document.frm_new_user_request
). You have to use the function getElementById
:
document.getElementById("frm_new_user_request")
So getting a value from an input could look like this:
var value = document.getElementById("frm_new_user_request").value
Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.
Getting a value from an input using jQuery would look like this:
var value = $("#element).value
var value = $(".element).value
You should also be able to use..
swfobject.getFlashPlayerVersion().major === 0
with the swfobject-Plugin.
Either
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1 from tablename
I wrote a custom hook that will run a function once before first render.
useBeforeFirstRender.js
import { useState, useEffect } from 'react'
export default (fun) => {
const [hasRendered, setHasRendered] = useState(false)
useEffect(() => setHasRendered(true), [hasRendered])
if (!hasRendered) {
fun()
}
}
Usage:
import React, { useEffect } from 'react'
import useBeforeFirstRender from '../hooks/useBeforeFirstRender'
export default () => {
useBeforeFirstRender(() => {
console.log('Do stuff here')
})
return (
<div>
My component
</div>
)
}
I also experienced such error when by accident put two @JsonProperty("some_value") identical lines on different properties inside the class
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines
.
Pretty Picture:
In matplotlib
it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.
Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy
and a couple of functions from the standard math
library.
The default behaviour of the labelLines
function is to space the labels evenly along the x
axis (automatically placing at the correct y
-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.
In addition, the label_lines
function does not account for the lines which have not had a label assigned in the plot
command (or more accurately if the label contains '_line'
).
Keyword arguments passed to labelLines
or labelLine
are passed on to the text
function call (some keyword arguments are set if the calling code chooses not to specify).
1
and 10
annotations in the top left plot. I'm not even sure this can be avoided.y
position instead sometimes.x
-axis values are float
slabelLines
function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x
range 0.5
-1
then then we couldn't possibly place a label at the desired location (which is a little less than 0.2
). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals
argument; a list of x
-values specified by the user instead of the default linear distribution across the width. So the user can decide which x
-values to use for the label placement of each data series.Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)
label_lines.py:
from math import atan2,degrees
import numpy as np
#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):
ax = line.axes
xdata = line.get_xdata()
ydata = line.get_ydata()
if (x < xdata[0]) or (x > xdata[-1]):
print('x label location is outside data range!')
return
#Find corresponding y co-ordinate and angle of the line
ip = 1
for i in range(len(xdata)):
if x < xdata[i]:
ip = i
break
y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])
if not label:
label = line.get_label()
if align:
#Compute the slope
dx = xdata[ip] - xdata[ip-1]
dy = ydata[ip] - ydata[ip-1]
ang = degrees(atan2(dy,dx))
#Transform to screen co-ordinates
pt = np.array([x,y]).reshape((1,2))
trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]
else:
trans_angle = 0
#Set a bunch of keyword arguments
if 'color' not in kwargs:
kwargs['color'] = line.get_color()
if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
kwargs['ha'] = 'center'
if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
kwargs['va'] = 'center'
if 'backgroundcolor' not in kwargs:
kwargs['backgroundcolor'] = ax.get_facecolor()
if 'clip_on' not in kwargs:
kwargs['clip_on'] = True
if 'zorder' not in kwargs:
kwargs['zorder'] = 2.5
ax.text(x,y,label,rotation=trans_angle,**kwargs)
def labelLines(lines,align=True,xvals=None,**kwargs):
ax = lines[0].axes
labLines = []
labels = []
#Take only the lines which have labels other than the default ones
for line in lines:
label = line.get_label()
if "_line" not in label:
labLines.append(line)
labels.append(label)
if xvals is None:
xmin,xmax = ax.get_xlim()
xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]
for line,x,label in zip(labLines,xvals,labels):
labelLine(line,x,label,align,**kwargs)
Test code to generate the pretty picture above:
from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2
from labellines import *
X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]
plt.subplot(221)
for a in A:
plt.plot(X,np.arctan(a*X),label=str(a))
labelLines(plt.gca().get_lines(),zorder=2.5)
plt.subplot(222)
for a in A:
plt.plot(X,np.sin(a*X),label=str(a))
labelLines(plt.gca().get_lines(),align=False,fontsize=14)
plt.subplot(223)
for a in A:
plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))
xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')
plt.subplot(224)
for a in A:
plt.plot(X,chi2(5).pdf(a*X),label=str(a))
lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)
plt.show()
I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda
You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.
Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"
img {
float:left;
}
h3 {
float:right;
}
Note that you will probably want to use the style clear:both
on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.
you can always use memset:
int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
You need a public class for Form1 to initialize.
See this code:
namespace TimerApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int counter = 60;
private void button1_Click(object sender, EventArgs e)
{
//Insert your code from before
}
private void timer1_Tick(object sender, EventArgs e)
{
//Again insert your code
}
}
}
I've tried this and it all worked fine
If you need anymore help feel free to comment :)
#For brevity, I didn't define a function.
#Place the directories you want to exclude in this array.
#Case insensitive and exact match. So 'archive' and
#'ArcHive' will match but 'BuildArchive' will not.
$noDirs = @('archive')
#Build a regex using array of excludes
$excRgx = '^{0}$' -f ($noDirs -join ('$|^'))
#Rather than use the gci -Recurse option, use a more
#performant approach by not processing the match(s) as
#soon as they are located.
$cmd = {
Param([string]$Path)
Get-ChildItem $Path -Directory |
ForEach-Object {
if ($_.Name -inotmatch $excRgx) {
#Recurse back into the scriptblock
Invoke-Command $cmd -ArgumentList $_.FullName;
#If you want all directory info change to return $_
return $_.FullName
}
}
}
#In this example, start with the current directory
$searchPath = .
#Start the Recursion
Invoke-Command $cmd -ArgumentList $searchPath
I have a simpler answer, which works perfectly for days; for months, it's +-2 days:
let today=new Date();
const days_to_subtract=30;
let new_date= new Date(today.valueOf()-(days_to_subtract*24*60*60*1000));
You get the idea - for months, multiply by 30; but that will be +-2 days.
This is an acknowledged bug in the Chrome Dev Tools:
Use anchor links and the scroll-behavior
property (MDN reference) for the scrolling container:
scroll-behavior: smooth;
Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.
Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior
and simply "jump" to the link target.
Example usage:
<head>
<style type="text/css">
html {
scroll-behavior: smooth;
}
</style>
</head>
<body id="body">
<a href="#foo">Go to foo!</a>
<!-- Some content -->
<div id="foo">That's foo.</div>
<a href="#body">Back to top</a>
</body>
Here's a Fiddle.
And here's also a Fiddle with both horizontal and vertical scrolling.
always make SQL re-usuable: -:)
-- ===================================================
-- &role_name will be "enter value for 'role_name'".
-- Date: 2015 NOV 11.
-- sample code: define role_name=&role_name
-- sample code: where role like '%&&role_name%'
-- ===================================================
define role_name=&role_name
select * from ROLE_ROLE_PRIVS where ROLE = '&&role_name';
select * from ROLE_SYS_PRIVS where ROLE = '&&role_name';
select role, privilege,count(*)
from ROLE_TAB_PRIVS
where ROLE = '&&role_name'
group by role, privilege
order by role, privilege asc
;
As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor
alert(myDiv.style.backgroundColor);
I just solved this problem a few hours ago.
var thename = 'Andrew'
db.collection.find({ $text: { $search: thename } });
You can even expand upon this by selecting on the fields you need from Andrew's user object by doing it this way:
db.collection.find({ $text: { $search: thename } }).select('age height weight');
Reference: https://docs.mongodb.org/manual/reference/operator/query/text/#text
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
You should create a XML file for the disabled button (drawable/btn_disable.xml)
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/grey" />
<corners android:radius="6dp" />
</shape>
And create a selector for the button (drawable/btn_selector.xml)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_disable" android:state_enabled="false"/>
<item android:drawable="@drawable/btn_default" android:state_enabled="true"/>
<item android:drawable="@drawable/btn_default" android:state_pressed="false" />
</selector>
Add the selector to your button
<style name="srp_button" parent="@android:style/Widget.Button">
<item name="android:background">@drawable/btn_selector</item>
</style>
Enums are classes and should follow the conventions for classes. Instances of an enum are constants and should follow the conventions for constants. So
enum Fruit {APPLE, ORANGE, BANANA, PEAR};
There is no reason for writing FruitEnum any more than FruitClass. You are just wasting four (or five) characters that add no information.
Java itself recommends this approach and it is used in their examples.
Compare the folder META-INF in new jar with old jar (before you added new libraries). It is possibility that there will be new files. If yes, you can remove them. It should helps. Regards, 999michal
urlparse is fine to use if you want to (say, to get rid of any query string parameters).
import urllib.parse
urls = [
'http://www.test.com/TEST1',
'http://www.test.com/page/TEST2',
'http://www.test.com/page/page/12345',
'http://www.test.com/page/page/12345?abc=123'
]
for i in urls:
url_parts = urllib.parse.urlparse(i)
path_parts = url_parts[2].rpartition('/')
print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))
Output:
URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
URL: http://www.test.com/page/page/12345?abc=123
returns: 12345
There isn't really a formal manual, because there's no single style or standard.
So long as you understand the rules of identifier naming you can use whatever you like.
In practice, I find it easier to use lower_case_underscore_separated_identifiers
because it isn't necessary to "Double Quote"
them everywhere to preserve case, spaces, etc.
If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42"
you'd be free to do that, though it'd be pain to type everywhere.
The main things to understand are:
Unless double-quoted, identifiers are case-folded to lower-case, so MyTable
, MYTABLE
and mytable
are all the same thing, but "MYTABLE"
and "MyTable"
are different;
Unless double-quoted:
SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).
You must double-quote keywords if you wish to use them as identifiers.
In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with"
doesn't mean you should.
this.tablenameTableAdapter.Fill(this.databasenameDataSet.tablename)
I know its older post but still posting for someone like me. This worked for me
<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />
put your favicon icon on root directory..
It's basically a shorthand. So instead of having to write:
this.props.dispatch(toggleTodo(id));
You would use mapDispatchToProps as shown in your example code, and then elsewhere write:
this.props.onTodoClick(id);
or more likely in this case, you'd have that as the event handler:
<MyComponent onClick={this.props.onTodoClick} />
There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist
Adding and removing tab may be a bit less effective May be this will help
To hide/show tab page => let tabPage1 of tabControl1
tapPage1.Parent = null; //to hide tabPage1 from tabControl1
tabPage1.Parent = tabControl1; //to show the tabPage1 in tabControl1
You're expecting a behaviour that is contrary to the documented behaviour of the % operator in c# - possibly because you're expecting it to work in a way that it works in another language you are more used to. The documentation on c# states (emphasis mine):
For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b. The sign of the non-zero remainder is the same as that of the left-hand operand
The value you want can be calculated with one extra step:
int GetArrayIndex(int i, int arrayLength){
int mod = i % arrayLength;
return (mod>=0) : mod ? mod + arrayLength;
}
var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');
Change this line from your code to this -
var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');
or in my case, I gave the encoding in reverse order
var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
Is this issue resolved.
I am getting this error: ERROR in node_modules/ngx-restangular/lib/ngx-restangular-http.d.ts(3,27): error TS2307: Cannot find module '@angular/common/http/src/response'.
After updating my angular to version=8
Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.
I've done this to extend Python 2's str()
class, for instance. str()
is a particularly interesting target because of the implicit linkage to quoted data such as 'this'
and 'that'
.
Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad
bit:
extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
After which I can write in the code fed to the preprocessor:
if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.
Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall
option, really works well
I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:
Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]
Neither of these was true, the user had all the necessary permissions in SQL Server.
In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService
.
In JDK 8+, without using any additional libs:
Iterator<T> source = ...;
List<T> target = new ArrayList<>();
source.forEachRemaining(target::add);
Edit: The above one is for Iterator
. If you are dealing with Iterable
,
iterable.forEach(target::add);
So before I found this post, I successfully found this to work.
Model._meta.fields
It works equally as
Model._meta.get_fields()
I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
print(field.name)
The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:
{
"env": {},
"extends": [],
"parser": "",
"plugins": [],
"rules": {},
"overrides": [
{
"files": ["test/*.spec.js"], // Or *.test.js
"rules": {
"require-jsdoc": "off"
}
}
],
"settings": {}
}
I fix the lack of example's library here:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">
You need to change Java compiler version in in build config.
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)
Since Management Studio 2005 it seems that you can use GO
with an int
parameter, like:
INSERT INTO mytable DEFAULT VALUES
GO 10
The above will insert 10 rows into mytable
. Generally speaking, GO
will execute the related sql commands n
times.
For future purposes, this may help too:
It's ok to use setState in useEffect
you just need to have attention as described already to not create a loop.
But it's not the only problem that may occur. See below:
Imagine that you have a component Comp
that receives props
from parent and according to a props
change you want to set Comp
's state. For some reason, you need to change for each prop in a different useEffect
:
DO NOT DO THIS
useEffect(() => {
setState({ ...state, a: props.a });
}, [props.a]);
useEffect(() => {
setState({ ...state, b: props.b });
}, [props.b]);
It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w
The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a
and prop.b
so the value of {...state}
when you do setState
are exactly the same in both useEffect
because they are in the same context. When you run the second setState
it will replace the first setState
.
DO THIS INSTEAD
The solution for this problem is basically call setState
like this:
useEffect(() => {
setState(state => ({ ...state, a: props.a }));
}, [props.a]);
useEffect(() => {
setState(state => ({ ...state, b: props.b }));
}, [props.b]);
Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx
Now, you always receive the most updated and correct value of the state when you proceed with the setState
.
I hope this helps someone!
Regular javascript can be used to trap the backspace key. You can use the event.keyCode method. The keycode is 8, so the code would look something like this:
if (event.keyCode == 8) {
// Do stuff...
}
If you want to check for both the [delete] (46) as well as the [backspace] (8) keys, use the following:
if (event.keyCode == 8 || event.keyCode == 46) {
// Do stuff...
}
Modified question is - What's the difference between A mutex and a "binary" semaphore in "Linux"?
Ans: Following are the differences – i) Scope – The scope of mutex is within a process address space which has created it and is used for synchronization of threads. Whereas semaphore can be used across process space and hence it can be used for interprocess synchronization.
ii) Mutex is lightweight and faster than semaphore. Futex is even faster.
iii) Mutex can be acquired by same thread successfully multiple times with condition that it should release it same number of times. Other thread trying to acquire will block. Whereas in case of semaphore if same process tries to acquire it again it blocks as it can be acquired only once.
This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.
If you're dividing positive integers you can shift it up, do the division and then check the bit to the right of the real b0. In other words, 100/8 is 12.5 but would return 12. If you do (100<<1)/8, you can check b0 and then round up after you shift the result back down.
what works for me:
1- in styles.xml:
<style name="generalnotitle" parent="Theme.AppCompat.Light" >
<item name="android:windowNoTitle">true</item> <!-- //this -->
</style>
2- in MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this
setContentView(R.layout.activity_main);
}
in manifest inherit the style:
<activity android:name=".MainActivity" android:theme="@style/generalnotitle">
I would like to expand on the ===
operator.
===
is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with ===
as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does ===
do?
===
is the pattern matching operator!
===
matches regular expressions===
checks range membership===
checks being instance of a class ===
calls lambda expressions===
sometimes checks equality, but mostly it does notSo how does this madness make sense?
Enumerable#grep
uses ===
internallycase when
statements use ===
internallyrescue
uses ===
internallyThat is why you can use regular expressions and classes and ranges and even lambda expressions in a case when
statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value
too, as well as with grep
method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]
Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.
Stole this from here. I found it very useful!
DECLARE @DB_USers TABLE
(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime)
INSERT @DB_USers
EXEC sp_MSforeachdb
'
use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%'''
SELECT
dbname,username ,logintype ,create_date ,modify_date ,
STUFF(
(
SELECT ',' + CONVERT(VARCHAR(500),associatedrole)
FROM @DB_USers user2
WHERE
user1.DBName=user2.DBName AND user1.UserName=user2.UserName
FOR XML PATH('')
)
,1,1,'') AS Permissions_user
FROM @DB_USers user1
GROUP BY
dbname,username ,logintype ,create_date ,modify_date
ORDER BY DBName,username
You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload
I've put up some algorithms to do image interpolation on html canvas pixel arrays that might be useful here:
https://web.archive.org/web/20170104190425/http://jsperf.com:80/pixel-interpolation/2
These can be copy/pasted and can be used inside of web workers to resize images (or any other operation that requires interpolation - I'm using them to defish images at the moment).
I haven't added the lanczos stuff above, so feel free to add that as a comparison if you'd like.
your startDate is first-day-of-month, In this case we can use
var endDate = moment(startDate).add(1, 'months').subtract(1, 'days');
Hope this helps!!
You're missing a few (not terribly clear) steps. Pandas is distributed through pip as a wheel, which means you need to do:
pip install wheel
pip install pandas
You're probably going to run into other issues after this - it looks like you're installing on Windows which isn't the most friendly of targets for numpy/scipy/pandas. Alternatively, you could pickup a binary installer from here.
You also had an error installing numpy. Like before, I recommend grabbing a binary installer for this, as it's not a simple process. However, you can resolve your current error by installing this package from Microsoft.
While it's completely possible to get a perfect environment setup on Windows, I have found the quality-of-life for a Python dev is vastly improved by setting up a debian VM. Especially with the scientific packages, you will run into many cases like this.
You can use an extension.
import UIKit
extension UILabel {
func sizeFont(_ size: CGFloat) {
self.font = self.font.withSize(size)
}
}
To use it:
self.myLabel.fontSize(100)
The simplest, and best long-term solution
Go to the main menu on top of Eclipse and locate Window next to Run and expand it.
Window->Reset Perspective... to restore all views to their defaults
It will reset the default setting.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
You can redirect anything or more URL via javascript, Just simple window.location.href
with if else
Use this code,
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
//Another url redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
You can redirect many URL's by this procedure. Thanks.
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
You can use dotPeek The only thing I have to say is that when using it, right-click on the class to select Decompiled Source instead of double-clicking, otherwise dotpeek will only display the contents of the local cs file, not the decompiled content. Option instance
That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:
List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
List<CharSequence> result;
// result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
result = input.stream().collect(Collectors.toList());
System.out.println(result);
what about this?
Function TruncateDecimal2(MyValue As Decimal) As Decimal
Try
Return Math.Truncate(100 * MyValue) / 100
Catch ex As Exception
Return Math.Round(MyValue, 2)
End Try
End Function
I had this problem too.
SVN doesn't do any line ending conversion, so files are committed with CRLF line endings intact. If you then use git-svn to put the project into git then the CRLF endings persist across into the git repository, which is not the state git expects to find itself in - the default being to only have unix/linux (LF) line endings checked in.
When you then check out the files on windows, the autocrlf conversion leaves the files intact (as they already have the correct endings for the current platform), however the process that decides whether there is a difference with the checked in files performs the reverse conversion before comparing, resulting in comparing what it thinks is an LF in the checked out file with an unexpected CRLF in the repository.
As far as I can see your choices are:
Footnote: if you choose option #2 then my experience is that some of the ancillary tools (rebase, patch etc) do not cope with CRLF files and you will end up sooner or later with files with a mix of CRLF and LF (inconsistent line endings). I know of no way of getting the best of both.
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
headers were not working for me on my shared hosting, reason was i was using my hotmail email address in header. i created a email on my cpanel and i set that same email in the header yeah it worked like a charm!
$header = 'From: ShopFive <[email protected]>' . "\r\n";
It sounds like you're looking for applicationHost.config
, which is located in C:\Windows\System32\inetsrv\config
.
Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config
and web.config
.
Put these lines in the beginning of web.xml:
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/main/resources/log4j.xml</param-value>
</context-param>
This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);
var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");
theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});
The trunc()
function truncates a date to the specified time period; so trunc(sysdate,'mm')
would return the beginning of the current month. You can then use the add_months()
function to get the beginning of the previous month, something like this:
select count(distinct switch_id)
from [email protected]
where dealer_name = 'XXXX'
and creation_date >= add_months(trunc(sysdate,'mm'),-1)
and creation_date < trunc(sysdate, 'mm')
As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31
, or the to_date()
function, for example to_date('2012-08-31','YYYY-MM-DD')
. If you don't then you are bound to get this wrong at some point.
You would not use sysdate - 15
as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc()
.
Just as a little demonstration of what trunc(<date>,'mm')
does:
select sysdate
, case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as gt
, case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as lt
, case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as eq
from dual
;
SYSDATE GT LT EQ
----------------- ---------- ---------- ----------
20120911 19:58:51 1
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
I thought this might be useful when using bootstrap and some glypicons:
<a class="btn btn-primary"
href="<%: Url.Action("Download File", "Download",
new { id = msg.Id, distributorId = msg.DistributorId }) %>">
Download
<span class="glyphicon glyphicon-paperclip"></span>
</a>
This will show an A tag, with a link to a controller, with a nice paperclip icon on it to represent a download link, and the html output is kept clean
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.
Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.
Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.
To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
.bash_profile
is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.
.bashrc
is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.
I personally put everything in .bashrc
so that I don't have to restart the application for changes to take effect.
Quick and dirty fix
class MyData:
def __init__(string=None,list=None):
if string is not None:
#do stuff
elif list is not None:
#do other stuff
else:
#make data empty
Then you can call it with
MyData(astring)
MyData(None, alist)
MyData()
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
setting the view's layout_weight="1"
would do the trick.!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
I fixed it with this
select {
max-height: calc(1.2em + 24px);
height: calc(1.2em + 24px);
}
max-height: calc(your line height + (top + bottom padding));
height: calc(your line height + (top + bottom padding));
If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking()
, otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:
http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/
Don't want to create a drawable resource?
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:minHeight="128dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:background="@android:color/white">
<TextView ... />
</FrameLayout>
</FrameLayout>
Take a look at this WPF metro-styled window with optional glowing borders.
This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.
Supports Windows all the way back to XP (.NET4).
@TheBigO, that's not correct. Spans can have background/images (tested in IE8 and Chrome as a sanity check).
The issue is that the a.btn-pToolName is marked as display: block. This causes webkit browsers to no longer show the background in the outer span. IE seems to render it how the OP is wanting.
OP chance the .btn-pTool class to be display: inline-block to make it work like a span/div hybrid (take the background, but not cause a break in the layout).
it simple way in xml:
android:maxLength="@{length}"
for setting it programmatically you can use the following function
public static void setMaxLengthOfEditText(EditText editText, int length) {
InputFilter[] filters = editText.getFilters();
List arrayList = new ArrayList();
int i2 = 0;
if (filters != null && filters.length > 0) {
int filtersSize = filters.length;
int i3 = 0;
while (i2 < filtersSize) {
Object obj = filters[i2];
if (obj instanceof LengthFilter) {
arrayList.add(new LengthFilter(length));
i3 = 1;
} else {
arrayList.add(obj);
}
i2++;
}
i2 = i3;
}
if (i2 == 0) {
arrayList.add(new LengthFilter(length));
}
if (!arrayList.isEmpty()) {
editText.setFilters((InputFilter[]) arrayList.toArray(new InputFilter[arrayList.size()]));
}
}
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}
This solution is very close to what @domi has, but is designed to shorten the name by fetching first 4 letters and last number.
library(ggplot2)
# simulate some data
xy <- data.frame(hospital = rep(paste("Hospital #", 1:3, sep = ""), each = 30),
value = rnorm(90))
shortener <- function(string) {
abb <- substr(string, start = 1, stop = 4) # fetch only first 4 strings
num <- gsub("^.*(\\d{1})$", "\\1", string) # using regular expression, fetch last number
out <- paste(abb, num) # put everything together
out
}
ggplot(xy, aes(x = value)) +
theme_bw() +
geom_histogram() +
facet_grid(hospital ~ ., labeller = labeller(hospital = shortener))
C++ STL style
std::string Trimed(const std::string& s)
{
std::string::const_iterator begin = std::find_if(s.begin(),
s.end(),
[](char ch) { return !std::isspace(ch); });
std::string::const_iterator end = std::find_if(s.rbegin(),
s.rend(),
[](char ch) { return !std::isspace(ch); }).base();
return std::string(begin, end);
}
To expand on Ryand's answer, if you're using Bootstrap.ui, this on your modal-instance will do the trick:
modalInstance.rendered.then(function (result) {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
$('.modal .modal-body').css('height', $(window).height() * 0.7);
});
Here's what I initially did, which does work, however it seems rather long-winded and ugly (global static anything is never good)
1: App.xaml.cs
public partial class App : Application
{
// create a new global custom WPF Command
public static readonly RoutedUICommand LoggedIn = new RoutedUICommand();
}
2: LoginForm.xaml
// bind the global command to a local eventhandler
<CommandBinding Command="client:App.LoggedIn" Executed="OnLoggedIn" />
3: LoginForm.xaml.cs
// implement the local eventhandler in codebehind
private void OnLoggedIn( object sender, ExecutedRoutedEventArgs e )
{
DialogResult = true;
Close();
}
4: LoginFormViewModel.cs
// fire the global command from the viewmodel
private void OnRemoteServerReturnedSuccess()
{
App.LoggedIn.Execute(this, null);
}
I later on then removed all this code, and just had the LoginFormViewModel
call the Close method on it's view. It ended up being much nicer and easier to follow. IMHO the point of patterns is to give people an easier way to understand what your app is doing, and in this case, MVVM was making it far harder to understand than if I hadn't used it, and was now an anti-pattern.
I had the same issue in Travis and solved by adding:
addons:
chrome: stable
to my .travis.yml
file.
Updated names for Swift 3.0
Based on Abhishek's answer and Druva's answer
func loadJson(forFilename fileName: String) -> NSDictionary? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
if let data = NSData(contentsOf: url) {
do {
let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary
return dictionary
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
print("Error!! Unable to load \(fileName).json")
}
return nil
}
Width: MediaQuery.of(context).size.width
,
Height: MediaQuery.of(context).size.height
,
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
You can simply use angular.filter module, and then you can filter even by nested properties.
see: jsbin
2 Examples:
JS:
angular.module('app', ['angular.filter'])
.controller('MainCtrl', function($scope) {
//your example data
$scope.items = {
'A2F0C7':{ secId:'12345', pos:'a20' },
'C8B3D1':{ pos:'b10' }
};
//more advantage example
$scope.nestedItems = {
'A2F0C7':{
details: { secId:'12345', pos:'a20' }
},
'C8B3D1':{
details: { pos:'a20' }
},
'F5B3R1': { secId:'12345', pos:'a20' }
};
});
HTML:
<b>Example1:</b>
<p ng-repeat="item in items | toArray: true | pick: 'secId'">
{{ item.$key }}, {{ item }}
</p>
<b>Example2:</b>
<p ng-repeat="item in nestedItems | toArray: true | pick: 'secId || details.secId' ">
{{ item.$key }}, {{ item }}
</p>
Setting JAVA_HOME directory from command line worked for me!
First:
JAVA_HOME="C:\Program Files\Java\jdk1.8.0"
Or :
export JAVA_HOME="C:\Program Files\Java\jdk1.8.0"
Then try:
mvn -version
to make sure you do not get the same error. :)
when you have an existing form, that should now work with jquery - ajax/post now you could:
do your own stuff
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'application/json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
});
Please note that, in order for the serialize()
function to work in the example above, all form elements need to have their name
attribute defined.
Example of the form:
<form id="myform" method="post" action="http://example.com/do_recieve_request">
<input type="text" size="20" value="default value" name="my_input_field">
..
.
</form>
@PtF - the data is submitted using POST in this sample, so this means you can access your data via
$_POST['dataproperty1']
, where dataproperty1 is a "variable-name" in your json.
here sample syntax if you use CodeIgniter:
$pdata = $this->input->post();
$prop1 = $pdata['prop1'];
$prop1 = $pdata['prop2'];
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:
StringBuilder sb = new StringBuilder();
sb.Append(......);
StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
sw.Write(sb.ToString());
sw.Close();
Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append
boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.
Try git rebase -i master
on your feature branch. You can then change all but one 'pick' to 'squash' to combine the commits. See squashing commits with rebase
Finally, you can then do the merge from master branch.
You can wrap the contents of the li
in another element such as a span
. Then, give the li
a larger font-size
, and set a normal font-size
back on the span
:
li {
font-size: 36px;
}
li span {
font-size: 18px;
}
<ul>
<li><span>Item 1</span></li>
<li><span>Item 2</span></li>
<li><span>Item 3</span></li>
</ul>
Try to generate the proxy class via SvcUtil.exe with command
Syntax:
svcutil.exe /language:<type> /out:<name>.cs /config:<name>.config http://<host address>:<port>
Example:
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceSamples/myService1
To check if service is available try in your IE URL from example upon without myService1 postfix
The bootstrap docs do explain it, but it still took me a while to get it. It makes more sense when I explain it to myself in one of two ways:
If you think of the columns starting out horizontally, then you can choose when you want them to stack.
For example, if you start with columns: A B C
You decide when should they stack to be like this:
A
B
C
If you choose col-lg, then the columns will stack when the width is < 1200px.
If you choose col-md, then the columns will stack when the width is < 992px.
If you choose col-sm, then the columns will stack when the width is < 768px.
If you choose col-xs, then the columns will never stack.
On the other hand, if you think of the columns starting out stacked, then you can choose at what point they become horizontal:
If you choose col-sm, then the columns will become horizontal when the width is >= 768px.
If you choose col-md, then the columns will become horizontal when the width is >= 992px.
If you choose col-lg, then the columns will become horizontal when the width is >= 1200px.
Here's another simple way using Runnable interface in Thread Constructor
public class Demo {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T1 : "+i);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T2 : "+i);
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T3 : "+i);
}
}
});
t1.start();
t2.start();
t3.start();
}
}
Another option is to use the package require-dir which let's you do the following. It supports recursion as well.
var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');
Flow chart describes the program (see old fortran flow charts - surely, there are some floating around on google).
Data flow diagram determines the flow of data, for example, between subroutines, or between different programs.
Based on the doc
<div class="row">
<div class="span4 collapse-group">
<h2>Heading</h2>
<p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
$('.row .btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
});
In Git 2.x:
If you are located directly at the working directory, then git add -A
and git add .
work without the difference.
If you are in any subdirectory of the working directory, git add -A
will add all files from the entire working directory, and git add .
will add files from your current directory.
And that's all.
I would start by reading up on streams on MSDN: http://msdn.microsoft.com/en-us/library/system.io.stream.aspx
Memorystream and FileStream are streams used to work with raw memory and Files respectively...
Python 3 - UPDATED 18th November 2015
Found the accepted answer useful, yet wished to expand on several points for the benefit of others based on my own experiences.
Module: A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
Module Example: Assume we have a single python script in the current directory, here I am calling it mymodule.py
The file mymodule.py contains the following code:
def myfunc():
print("Hello!")
If we run the python3 interpreter from the current directory, we can import and run the function myfunc in the following different ways (you would typically just choose one of the following):
>>> import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mymodule import myfunc
>>> myfunc()
Hello!
>>> from mymodule import *
>>> myfunc()
Hello!
Ok, so that was easy enough.
Now assume you have the need to put this module into its own dedicated folder to provide a module namespace, instead of just running it ad-hoc from the current working directory. This is where it is worth explaining the concept of a package.
Package: Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.
Package Example: Let's now assume we have the following folder and files. Here, mymodule.py is identical to before, and __init__.py is an empty file:
.
+-- mypackage
+-- __init__.py
+-- mymodule.py
The __init__.py files are required to make Python treat the directories as containing packages. For further information, please see the Modules documentation link provided later on.
Our current working directory is one level above the ordinary folder called mypackage
$ ls
mypackage
If we run the python3 interpreter now, we can import and run the module mymodule.py containing the required function myfunc in the following different ways (you would typically just choose one of the following):
>>> import mypackage
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> import mypackage.mymodule
>>> mypackage.mymodule.myfunc()
Hello!
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mypackage.mymodule import myfunc
>>> myfunc()
Hello!
>>> from mypackage.mymodule import *
>>> myfunc()
Hello!
Assuming Python 3, there is excellent documentation at: Modules
In terms of naming conventions for packages and modules, the general guidelines are given in PEP-0008 - please see Package and Module Names
Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Add a limit
to the delete query
delete from orders
where id_users = 1 and id_product = 2
limit 1
I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.
Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:
implementation 'com.google.code.gson:gson:2.8.5'
To Save:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("Key", json);
prefsEditor.commit();
To Retrieve in a Different Activity:
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("Key", "");
MyObject obj = gson.fromJson(json, MyObject.class);
I see that you've tagged this question with the google-spreadsheet-api
tag. So by "drop-down" do you mean Google App Script's ListBox? If so, you may toggle a user's ability to select multiple items from the ListBox with a simple true/false value.
Here's an example:
`var lb = app.createListBox(true).setId('myId').setName('myLbName');`
Notice that multiselect is enabled because of the word true.
Get rid of your quotes around your command. When you quote it, docker tries to run the full string "lsb_release -a"
as a command, which doesn't exist. Instead, you want to run the command lsb_release
with an argument -a
, and no quotes.
sudo docker exec -it c44f29d30753 lsb_release -a
Note, everything after the container name is the command and arguments to run inside the container, docker will not process any of that as options to the docker command.
to list only commits details for specific file changes,
git log --follow file_1.rb
to list difference among various commits for same file,
git log -p file_1.rb
to list only commit and its message,
git log --follow --oneline file_1.rb
You can get value
of key
like this...
var obj = {
a: "A",
b: "B",
c: "C"
};
console.log(obj.a);
console.log(obj['a']);
name = "a";
console.log(obj[name])
_x000D_
You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!
The better approach would be to extract this logic into reusable function on your $rootScope
:
.run(function ($rootScope) {
$rootScope.inArray = function (item, array) {
return (-1 !== array.indexOf(item));
};
})
Then, use it in your template:
<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>
I think everyone will agree that this example is much more readable and maintainable.
If you just want to print the substrings ...
char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
printf("%.4s\n", s + i);
}
Combining the top-rated answer with the second-top-rated answer to get the filename without the full path:
$ x="/foo/fizzbuzz.bar.quux"
$ y=(`basename ${x%%.*}`)
$ echo $y
fizzbuzz
Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView
will get it working on API level 21+
if (Build.VERSION.SDK_INT >= 21) {
videoViewContainer.setBackgroundColor(Color.BLACK);
((ViewGroup) webView.getParent()).addView(videoViewContainer);
webView.scrollTo(0,0); // centers full screen view
} else {
activityNonVideoView.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
activityVideoView.addView(videoViewContainer,vg);
activityVideoView.setVisibility(View.VISIBLE);
}
You will also need to reflect the changes in onHideCustomView
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
You have ArrayList
all wrong,
add()
method in an arrayRather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0
to N-1
where N
is size()
of list.
I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.
a -- b -- c <-- Master
\ \
\ d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
\
f -- g <-- Branch2