Just provide the jQuery val function with an array of values:
var values = "Test,Prof,Off";
$('#strings').val(values.split(','));
And to get the selected values in the same format:
values = $('#strings').val();
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:
int r = (int) (Math.random() * (upper - lower)) + lower;
One other option would be to use something like this
SELECT *
FROM table t INNER JOIN
(
SELECT 'Text%' Col
UNION SELECT 'Link%'
UNION SELECT 'Hello%'
UNION SELECT '%World%'
) List ON t.COLUMN LIKE List.Col
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.
You don't get all the history etc, but you probably don't want that in this case.
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.
HTML:
<div rel="this-should-be-the-target">
</div>
JQuery:
$(function() {
var targetElement = 'rel="this-should-be-the-target"';
initPopover(targetElement, "Test Popover Content");
// use this line if you want it to show by default
$(targetElement).popover('show');
function initPopover(target, popOverContent) {
$(target).each(function(i, obj) {
$(this).popover({
placement : 'auto',
trigger : 'hover',
"html": true,
content: popOverContent
});
});
}
});
As of Socket.IO 1.0 (May 2014), all connections begin with an HTTP polling request (more info here). That means that in addition to forwarding WebSocket traffic, you need to forward any transport=polling
HTTP requests.
The solution below should redirect all socket traffic correctly, without redirecting any other traffic.
Enable the following Apache2 mods:
sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
Use these settings in your *.conf file (e.g. /etc/apache2/sites-available/mysite.com.conf
). I've included comments to explain each piece:
<VirtualHost *:80>
ServerName www.mydomain.com
# Enable the rewrite engine
# Requires: sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
# In the rules/conds, [NC] means case-insensitve, [P] means proxy
RewriteEngine On
# socket.io 1.0+ starts all connections with an HTTP polling request
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*) http://localhost:3001/$1 [P]
# When socket.io wants to initiate a WebSocket connection, it sends an
# "upgrade: websocket" request that should be transferred to ws://
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://localhost:3001/$1 [P]
# OPTIONAL: Route all HTTP traffic at /node to port 3001
ProxyRequests Off
ProxyPass /node http://localhost:3001
ProxyPassReverse /node http://localhost:3001
</VirtualHost>
I've included an extra section for routing /node
traffic that I find handy, see here for more info.
No.
You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.
See also my article on CSS inheritance.
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
I use the following .gitignore file generated in gitignore.io:
### Xcode ###
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.xcuserstate
### Objective-C ###
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
Pods/
@ModelAttribute
is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username
and userClient.firstName
, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient
object.
(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)
setInterval
fires again and again in intervals, while setTimeout
only fires once.
See reference at MDN.
Handle should do the trick.
Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.
Try This One:
@list_of_params varchar(20) -- value 1, 2, 5, 7, 20
SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id) +'%')
very simple.
My solution was not to rely on the class name. object.constructor.name works in theory. But if you're using TypeScript in something like Ionic, as soon as you go to production it's going to go up in flames because Ionic's production mode minifies the Javascript code. So the classes get named things like "a" and "e."
What I ended up doing was having a typeName class in all my objects that the constructor assigns the class name to. So:
export class Person {
id: number;
name: string;
typeName: string;
constructor() {
typeName = "Person";
}
Yes that wasn't what was asked, really. But using the constructor.name on something that might potentially get minified down the road is just begging for a headache.
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:
new_cols = ["a", "b", "c" ]
df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)
It's based on the second variant of the accepted answer.
Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-
http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/
Thanks to gene tsai
, here is some modifications to his code to run on my target page:
csv = []
rows = $('#data tr');
for(i =0;i < rows.length;i++) {
cells = $(rows[i]).find('td,th');
csv_row = [];
for (j=0;j<cells.length;j++) {
txt = cells[j].innerText;
csv_row.push(txt.replace(",", "-"));
}
csv.push(csv_row.join(","));
}
output = csv.join("\n")
improvements:
for
loopif the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
I just came across a similar problem. Try
require './st.rb'
This should do the trick.
First, disable the php5
module:
a2dismod php5
then, enable the php7
module:
a2enmod php7.0
Next, reload/restart the Apache service:
service apache2 restart
wrt the comment, you need to specify exact installed php-7.x version.
The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources
class to resolve the string into that integer.
Resources res = getResources();
int resourceId = res.getIdentifier(
generatedString, "drawable", getPackageName() );
imageView.setImageResource( resourceId );
This resolves your generated string into the integer that the ImageView
can use to load the right image.
Alternately, you can use the id to load the Drawable
manually and then set the image using that drawable instead of the resource ID.
Drawable drawable = res.getDrawable( resourceId );
imageView.setImageDrawable( drawable );
Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.
For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.
After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
As far as I am aware you have to use javascript to travel up the dom.
Something like this:
$("textarea:focus").parent().attr("border", "thin solid black");
you'll need the jQuery libraries loaded as well.
If you're willing to use pseudo elements and let them insert content, you can do the following. It doesn't assume knowledge of the original element and doesn't require additional markup.
.element {
text-indent: -9999px;
line-height: 0; /* Collapse the original line */
}
.element::after {
content: "New text";
text-indent: 0;
display: block;
line-height: initial; /* New content takes up original line height */
}
never use getApplicationContext()
. Just use your Activity as the Context. See if that helps.
Please check here: CommonsWare answers
<button type="button" onClick="refreshPage()">Close</button>
<script>
function refreshPage(){
window.location.reload();
}
</script>
or
<button type="button" onClick="window.location.reload();">Close</button>
For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:
This was due to a function not returning a value it was supposed to.
std::vector<Object> generateStuff(std::vector<Object>& target> {
std::vector<Object> returnValue;
editStuff(target);
// RETURN MISSING
}
Don't know why this was able to compile after all. Probably there was a warning about it.
as.character()
would be the general way rather than use paste()
for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.
// Assuming moduleFileName contains full or valid relative path to assembly
var moduleInstance = Activator.CreateInstanceFrom(moduleFileName, "MyNamespace.MyClass");
MethodInfo mi = moduleInstance.Unwrap().GetType().GetMethod("MyMethod");
// Assuming the method returns a boolean and accepts a single string parameter
bool rc = Convert.ToBoolean(mi.Invoke(moduleInstance.Unwrap(), new object[] { "MyParamValue" } ));
sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance1 = SomeModel.objects.get(id=id)
instance1.delete()
// don't use same name
(so Windows releases it's hold on the file)
Instead, do Ctrl+Alt+Del right after the Stop of the service and kill the .exe of the service. Than, you can uninstall the service without rebooting. This happened to me in the past and it solves the part that you need to reboot.
The backslash \
is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.
\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.
Along with the points made by others, the $=
selector is the "ends with" selector. You will want the *=
(contains) selector, like so:
$('a').each(function() {
if ($(this).is('[href*="?"')) {
alert("Contains questionmark");
}
});
As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:
$('a[href*="?"]').each(function() {
alert("Contains questionmark");
});
The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:
JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])
I fixed it by changing the selector. The full snippet is this:
$(function() {
$("a[href*='#']:not([href='#'])").click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Another simple way would be:
Integer i = new Integer("10");
if (i != null)
int ip = Integer.parseInt(i.toString());
no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list
The other answers have all given good information, but I feel this needs to be made clear.
No, you should never use:
if A:
if what you need to test is:
if A is not None:
The first will often work as a replacement for the second but the first is a common source of hard to find bugs. Even if all you are doing is writing some quick throw-away code, you should not allow yourself to get into the habit of writing buggy code. Train your fingers and your mind to write and read the correct verbose form of the test:
if A is not None:
The common use of None is to define optional parameter values and to give a variable a default starting value which means "no value yet", and functions a meaning of "no value retured". If you write a function such as:
def my_func(a_list, obj=None):
if obj: # Trying to test if obj was passed
a_list.append(obj)
# do something with a_list
This will work fine for many real world uses like:
my_func(user_names, "bob")
But if any of this happens:
my_func(user_names, "")
my_func(user_names, [])
my_func(user_names, 0)
Then the zero-length objects will not be added to the list. When the first code was written, you might know that zero-length user names are not allowed. So the short code works fine. But then you try to modify the code to use an empty string to mean something like an anonymous user with no name, and suddenly this function stops doing what it is expected to do (adding the annonomous user to the list).
For example, lets say you have logic to define when a user is allowed to log in written like:
new_user = get_user_name()
if user_list_ok(my_func(current_users, new_user)):
# user_list_ok() tests that no more than 10 users can
# log in at the same time, and that no sigle user can
# can log in more than 3 times at once.
# This user is allowed to log in!
log_user_in(new_user)
This now creates subtle and complex bugs in your code. The anonmous user of "" will not be added to the list for the test, so when the system has hit the limit of 10 users, the test will still allow the anonomous user to log in, pushing the user count to 11. This then might trigger a bug in another part of the system that requires there only be 10 users max.
When you need to test for "var does not have a value" you should always use the longer "is not None" test even though it feels ugly and verbose.
Wrap the child you want centered in a View and make the View absolute.
<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
<Text>Centered text</Text>
</View>
New method in Django 3
you can use Field.choices Enumeration Types new update in django3 like this :
from django.db import models
class Status(models.TextChoices):
UNPUBLISHED = 'UN', 'Unpublished'
PUBLISHED = 'PB', 'Published'
class Book(models.Model):
status = models.CharField(
max_length=2,
choices=Status.choices,
default=Status.UNPUBLISHED,
)
you can use ps
.
e.g. having python process with two busy threads on dual core CPU:
$ ps -p 29492 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
29492 29492 1 0.0
29492 29493 1 48.7
29492 29494 1 51.9
(PSR is CPU id the thread is currently assigned to)
you see that the threads are running on the same cpu core (because of GIL)
running the same python script in jython, we see, that the script is utilizing both cores (and there are many other service or whatever threads, which are almost idle):
$ ps -p 28671 -L -o pid,tid,psr,pcpu
PID TID PSR %CPU
28671 28671 1 0.0
28671 28672 0 4.4
28671 28673 0 0.6
28671 28674 0 0.5
28671 28675 0 2.3
28671 28676 0 0.0
28671 28677 1 0.0
28671 28678 1 0.0
28671 28679 0 4.6
28671 28680 0 4.4
28671 28681 1 0.0
28671 28682 1 0.0
28671 28721 1 0.0
28671 28729 0 88.6
28671 28730 1 88.5
you can process the output and calculate the total CPU for each CPU core.
Unfortunately, this approach does not seem to be 100% reliable, sometimes i see that in the first case, the two working threads are reported to be separated to each CPU core, or in the latter case, the two threads are reported to be on the same core..
codeblocks.It seems to be good
Why not simply add the following to the beginning of the script
PRINT 'INACTIVE SCRIPT'
RETURN
When you create an object myObj
as you have, think of it more like a dictionary. In this case, it has two keys, name
, and age
.
You can access these dictionaries in two ways:
myObj[name]
); ormyObj.name
); do note that some properties are reserved, so the first method is preferred.You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name
is a variable, and since you haven't created a variable called name
, it won't be able to access the key you're expecting.
It's stored in the process (shell) and since you've exported it, any processes that process spawns.
Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.
You can override the canvas style width !important ...
canvas{
width:1000px !important;
height:600px !important;
}
also
specify responsive:true,
property under options..
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
update under options added : maintainAspectRatio: false,
Manifold Preprocessor implemented as a javac compiler plugin is designed exclusively for conditional compilation of Java source code. It uses familiar C/C++ style of directives: #define, #undef, #if, #elif, #else, #endif, #error. and #warning.
It has Maven and Gradle plugins.
by XML:
<EditText
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
android:imeOptions="actionSearch"
android:inputType="text" />
By Java:
editText.clearFocus();
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
What about this:
select{
width: 150px;
height: 30px;
padding: 5px;
color: green;
}
select option { color: black; }
select option:first-child{
color: green;
}
_x000D_
<select>
<option>one</option>
<option>two</option>
</select>
_x000D_
Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".
In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.
Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.
i = 0
while i < len(str):
print str[i]
i += 1
But then again, why do that when strings are inherently iterable?
for i in str:
print i
Had same issue in Cygwin, this is what helped me
sudo apt-get install python-pip python-dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev
but instead of sudo apt-get install, I installed those packages via Cygwin Source of this code
Android Studio debug.keystore file path depend on environment variable ANDROID_SDK_HOME.
If ANDROID_SDK_HOME defined, then file placed in SDK's subfolder named .android .
When not defined, then keystore placed at user home path in same subfolder:
- %HOMEPATH%\.android\ on Windows
- $HOME/.android/ on Linux
There is a quite simple way to solve this.
You just have to duplicate the content of child1 and child2 in relative divs with display:none in parent div. Say child1_1 and child2_2. Put child2_2 on top and child1_1 at the bottom.
When your jquery (or whatever) calls the absolute div, just set the according relative div (child1_1 or child2_2) with display:block AND visibility:hidden. The relative child will still be invisible but will make parent's div higher.
In Python 3 you can overwrite print function with default set to flush = True
def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=True):
__builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush)
You are always allowed to initialize a final
variable. The compiler makes sure that you can do it only once.
Note that calling methods on an object stored in a final
variable has nothing to do with the semantics of final
. In other words: final
is only about the reference itself, and not about the contents of the referenced object.
Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end
.
To make life easier for substring
operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
? ?
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.
You will need to add the application.properties
file in your classpath.
If you are using Maven or Gradle, you can just put the file under src/main/resources
.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.
Then you can just add an entry server.port = xxxx
in the properties file.
You cannot return anonymous types. Can you create a model that can be returned? Otherwise, you must use an object
.
Here is an article written by Jon Skeet on the subject
Code from the article:
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
Or, here is another similar article
Or, as others are commenting, you could use dynamic
Like that:
class Zoo {
AnimalClass: typeof Animal;
constructor(AnimalClass: typeof Animal ) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
Or just:
class Zoo {
constructor(public AnimalClass: typeof Animal ) {
let Hector = new AnimalClass();
}
}
typeof Class
is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.
Here's the relevant part of TypeScript docs. Search for the typeof
. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.
For modern browsers, use td:nth-child(2)
for the second td
, and td:nth-child(3)
for the third. Remember that these retrieve the second and third td
for every row.
If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.
To make things even more clearer,
The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text
. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt
:
$2a$COST$BASE64
This value is stored eventually.
In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random.
Then he will need to decrypt the cipher text
.
What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.
you can simply use varialbles and one file to check for running your program. when open the file contain a value and when program closes changes this value to another one.
Pushing multiple objects at once often depends on how are you declaring your array
.
This is how I did
//declaration
productList= [] as any;
now push
records
this.productList.push(obj.lenght, obj2.lenght, items);
The simplest way to update is as follows:
Go to the start screen for Android Studio. If it automatically opens a project when you open it, close that project (not exit).
At the bottom there will be a check for updates link which you can use to update to the latest version.
Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.
listItems = $("#productList li").each(function(){
var product = $(this);
var productid = product.children(".productId").val();
var productPrice = product.find(".productPrice").val();
var productMSRP = product.find(".productMSRP").val();
totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));
});
From the docs
Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.
For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.
The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.
There should not be any performance impacts.
No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.
You have the following options on Windows command line:
net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]
Try like:
net use H: /delete /y
You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..
Public Sub Test()
Dim ReadData as String
Open "C:\satheesh\myfile\file.txt" For Input As #1
Do Until EOF(1)
Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
If Not Left(ReadData, 1) = "*" then
'' you can write the variable ReadData into the database or file
End If
Loop
Close #1
End Sub
[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx
The command ansible localhost -m setup
basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.
When you run the echo
command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:
- hosts: localhost
tasks:
- debug: var=ansible_date_time
- debug: msg="the current date is {{ ansible_date_time.date }}"
Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:
PLAY [localhost] **************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [debug var=ansible_date_time] *******************************************
ok: [localhost] => {
"ansible_date_time": {
"date": "2015-07-09",
"day": "09",
"epoch": "1436461166",
"hour": "16",
"iso8601": "2015-07-09T16:59:26Z",
"iso8601_micro": "2015-07-09T16:59:26.896629Z",
"minute": "59",
"month": "07",
"second": "26",
"time": "16:59:26",
"tz": "UTC",
"tz_offset": "+0000",
"weekday": "Thursday",
"year": "2015"
}
}
TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
ok: [localhost] => {
"msg": "the current date is 2015-07-09"
}
PLAY RECAP ********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0
If you want check access to databases for a particular login has use this simple script as below:
sys.sp_helplogins @LoginNamePattern = 'Domain\login' -- sysname
Ashirvad's answer no longer works. Note the class name changes and using the option element instead of the li element. I've updated my answer to not use the deprecated "success" event, instead opting for .done():
$('.chosen-search input').autocomplete({
minLength: 3,
source: function( request, response ) {
$.ajax({
url: "/some/autocomplete/url/"+request.term,
dataType: "json",
beforeSend: function(){ $('ul.chosen-results').empty(); $("#CHOSEN_INPUT_FIELDID").empty(); }
}).done(function( data ) {
response( $.map( data, function( item ) {
$('#CHOSEN_INPUT_FIELDID').append('<option value="blah">' + item.name + '</option>');
}));
$("#CHOSEN_INPUT_FIELDID").trigger("chosen:updated");
});
}
});
Justas answer is outdated so I'm posting up to date answer with apache text commons.
StringSubstitutor
from Apache Commons Text may be used for string formatting with named placeholders:
https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods. Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
Example:
// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);
// Replace
String resolvedString = sub.replace(templateString);
In Google Sheets you can use =ArrayFormula(Sheet1!B2:B)on the first cell and it will populate all column contents not sure if that will work in excel
If, like me, what you usually want is to overwrite the contents of the working directory with that of the stashed files, and you still get a conflict, then what you want is to resolve the conflict using git checkout --theirs -- .
from the root.
After that, you can git reset
to bring all the changes from the index to the working directory, since apparently in case of conflict the changes to non-conflicted files stay in the index.
You may also want to run git stash drop [<stash name>]
afterwards, to get rid of the stash, because git stash pop
doesn't delete it in case of conflicts.
Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>
):
<customErrors mode="off" />
I had the same problem and tried everything but it didn't worked. So I used following trick:
function do_stuff(e)
{
if(e){ alert(e); }
}
$("#delete").click(function() {
do_stuff("Clicked");
});
You check if that parameter isn't null than you do code. So when the function will triggered second time it will show what you want.
If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.
dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');
or
DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) ||
'good' || CHR(13) || CHR(10) ||
'morning' || CHR(13) || CHR(10) ||
'friends' || CHR(13) || CHR(10) ||);
try it.
While many of the suggestions work when converting 2 -> 4 space. I ran into some issues when converting 4 -> 2.
Here's what I ended up using:
Sublime Text 3/Packages/User/to-2.sublime-macro
[
{ "args": null, "command": "select_all" },
{ "args": { "set_translate_tabs": true }, "command": "unexpand_tabs" },
{ "args": { "setting": "tab_size", "value": 1 }, "command": "set_setting" },
{ "args": { "set_translate_tabs": true }, "command": "expand_tabs" },
{ "args": { "setting": "tab_size", "value": 2 }, "command": "set_setting" }
]
The statement basically does the following:
First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.
Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.
Then compile your project and see the effect.
See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0
if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.
In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.
I had the same problem: port-443-in-use-by-unable-to-open-process-with-pid-4
First I disabled the weather tile in Win* that apparently phones home to Redmond for updates after this showed on netstat list.
This didn't solve the problem. I looked at the post already here which mentioned VPNs, so
I went to Control Panel\Network and Internet\Network and Sharing Center
and clicked on Change adapter settings
I clicked on Incoming Connections
and right clicked on properties
The VPN click box at the bottom of the General
tab was on, so I unchecked it
Under Users
, I also unchecked a previous user I had allowed to copy some data weeks before
Then I clicked okay
Closed the control panel and restarted the XAMPP control panel
It fired right up without a problem.
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
This worked for me:
$.ajax({
url:"../messaging/delete.php",
type:"POST",
data:{messages:selected},
success:function(data){
if(data === "done"){
}
info($("#notification"), data);
},
beforeSend:function(){
info($("#notification"),"Deleting "+count+" messages");
},
error:function(jqXHR, textStatus, errorMessage){
error($("#notification"),errorMessage);
}
});
And this for your PHP:
$messages = $_POST['messages']
foreach($messages as $msg){
echo $msg;
}
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()
I have found a fairly simple way to do this.
Initially, through your Anaconda Prompt, you can follow the steps in this official Tensorflow site - here. You have to follow the steps as is, no deviation.
Later, you open the Anaconda Navigator. In Anaconda Navigator, go to Applications On --- section. Select the drop down list, after following above steps you must see an entry - tensorflow into it. Select tensorflow and let the environment load.
Then, select Jupyter Notebook in this new context, and install it, let the installation get over.
After that you can run the Jupyter notebook like the regular notebook in tensorflow environment.
path.resolve('.')
is also a reliable and clean option, because we almost always require('path')
. It will give you absolute path of the directory from where it is called.
Apache Subversion supports path-based authorization that helps you configure granular permissions for user and group accounts on paths in your repositories (files or directories). Path-based authorization supports three access levels - No Access, Read Only and Read / Write.
Path-based authorization permissions are stored in per-repository or per-server authorization files with a special syntax. Here is an example from SVNBook:
[calc:/branches/calc/bug-142]
harry = rw
sally = r
When you require a complex permission structure with many paths and accounts you can benefit from a GUI-based permission management tools provided by VisualSVN Server:
Repository permissions in VisualSVN Server Manager
If you're on java 6 can use NetworkInterface to check for available network interfaces. I.e. something like this:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback())
return true;
}
Haven't tried it myself, yet.
This will call git blame
for every meaningful revision to show line $LINE
of file $FILE
:
git log --format=format:%H $FILE | xargs -L 1 git blame $FILE -L $LINE,$LINE
As usual, the blame shows the revision number in the beginning of each line. You can append
| sort | uniq -c
to get aggregated results, something like a list of commits that changed this line. (Not quite, if code only has been moved around, this might show the same commit ID twice for different contents of the line. For a more detailed analysis you'd have to do a lagged comparison of the git blame
results for adjacent commits. Anyone?)
For VBScript use FormatDateTime, which has 5 numerical arguments to give you one of 5 predefined formats. Its not great.
FormatDateTime(now, 4)
08:12
Bitmap d = new Bitmap(c.Width, c.Height);
for (int i = 0; i < c.Width; i++)
{
for (int x = 0; x < c.Height; x++)
{
Color oc = c.GetPixel(i, x);
int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
d.SetPixel(i, x, nc);
}
}
This way it also keeps the alpha channel.
Enjoy.
You can use the Logical NOT !
operator:
if (!$(this).parent().next().is('ul')){
Or equivalently (see comments below):
if (! ($(this).parent().next().is('ul'))){
For more information, see the Logical Operators section of the MDN docs.
First you have to add an ArrayList to the Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
then you can add an item to the ArrayLIst that is inside the Map like this:
Items.get("theKey").add(item); // item is an object of type Item
PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
or not putting any arguments on the starting line, then indenting to a uniform level:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.
If you already have the string, you can use this function:
bool isNumber( const string& s )
{
bool hitDecimal=0;
for( char c : s )
{
if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
hitDecimal=1; // first hit here, we forgive and skip
else if( !isdigit( c ) )
return 0 ; // not ., not
}
return 1 ;
}
Add this css property to the element being flickered:
-webkit-transform-style: preserve-3d;
(And a big thanks to Nathan Hoad: http://nathanhoad.net/how-to-stop-css-animation-flicker-in-webkit)
How I update my deviceToken
First when I login I send the first device token under the user collection and the current logged in user.
After that, I just override onNewToken(token:String)
in my FirebaseMessagingService()
and just update that value if a new token is generated for that user
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
val currentUser= FirebaseAuth.getInstance().currentUser?.uid
if(currentUser != null){
FirebaseFirestore.getInstance().collection("user").document(currentUser).update("deviceToken",token)
}
}
}
Each time your app opens it will check for a new token, if the user is not yet signed in it will not update the token, if the user is already logged in you can check for a newToken
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )
Below is the sql code for a Unique Constraint
ALTER TABLE `MyDatabase`.`Provider`
ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;
So at the most basic level a HANDLE of any sort is a pointer to a pointer or
#define HANDLE void **
Now as to why you would want to use it
Lets take a setup:
class Object{
int Value;
}
class LargeObj{
char * val;
LargeObj()
{
val = malloc(2048 * 1000);
}
}
void foo(Object bar){
LargeObj lo = new LargeObj();
bar.Value++;
}
void main()
{
Object obj = new Object();
obj.val = 1;
foo(obj);
printf("%d", obj.val);
}
So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.
Now if we update foo to:
void foo(Object * bar)
{
LargeObj lo = new LargeObj();
bar->val++;
}
There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.
The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.
A final update to foo of:
void foo(Object **bar){
LargeObj lo = LargeObj();
Object * b = &bar;
b->val++;
}
This will always print the updated value.
See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.
Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.
I had the same issue and here is how I manage to pass through:
In your case you have addToCount()
which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"
in your function implementation you can receive the params like:
addToCount(paramContactID){
// the paramContactID contains the value you passed into the function when you called it
// you can do what you want to do with the paramContactID in here!
}
The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.
I usually create a libs
folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.
(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)
PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...
Because of changes to how tracking branches are created and pushed I no longer recommend renaming branches. This is what I recommend now:
Make a copy of the branch at its current state:
git branch crazyexperiment
(The git branch <name>
command will leave you with your current branch still checked out.)
Reset your current branch to your desired commit with git reset
:
git reset --hard c2e7af2b51
(Replace c2e7af2b51
with the commit that you want to go back to.)
When you decide that your crazy experiment branch doesn't contain anything useful, you can delete it with:
git branch -D crazyexperiment
It's always nice when you're starting out with history-modifying git commands (reset, rebase) to create backup branches before you run them. Eventually once you're comfortable you won't find it necessary. If you do modify your history in a way that you don't want and haven't created a backup branch, look into git reflog
. Git keeps commits around for quite a while even if there are no branches or tags pointing to them.
A slightly less scary way to do this than the git reset --hard
method is to create a new branch. Let's assume that you're on the master
branch and the commit you want to go back to is c2e7af2b51
.
Rename your current master branch:
git branch -m crazyexperiment
Check out your good commit:
git checkout c2e7af2b51
Make your new master branch here:
git checkout -b master
Now you still have your crazy experiment around if you want to look at it later, but your master branch is back at your last known good point, ready to be added to. If you really want to throw away your experiment, you can use:
git branch -D crazyexperiment
#include <algorithm>
std::reverse(str.begin(), str.end());
This is the simplest way in C++.
Actually things changed slightly these days in order to get rid of those dead containers you may try to unmount those blocked filesystems to release them
So if you get message like this
Error response from daemon: Cannot destroy container elated_wozniak: Driver devicemapper failed to remove root filesystem 656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3: Device is Busy
just run this
umount /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3
and you can normally remove container after that
I am changing your id to current-month (having no space)
alert($('#current-month').attr('month'));
alert($('#current-month').attr('year'));
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
You could try setting up a filter using the unicodedata.category()
function:
import unicodedata
printable = {'Lu', 'Ll'}
def filter_non_printable(str):
return ''.join(c for c in str if unicodedata.category(c) in printable)
See Table 4-9 on page 175 in the Unicode database character properties for the available categories
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1();
- here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
From Maven - Settings Reference
The repositories for download and deployment are defined by the repositories
and distributionManagement
elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
...
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
...
</settings>
id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.
username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.
privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa
) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.
Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.
All you should need is the id
, username
and password
The id
and URL
should be defined in your pom.xml
like this:
<repositories>
...
<repository>
<id>acme-nexus-releases</id>
<name>acme nexus</name>
<url>https://nexus.acme.net/content/repositories/releases</url>
</repository>
...
</repositories>
If you need a username and password to your server, you should encrypt it. Maven Password Encryption
The below query helps to get the row number in oracle,
SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';
I'd say the code you need is:
test = input("enter the test")
print(test)
Otherwise it shouldn't run at all, due to a syntax error. The print
function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?
Well, you can't add styling using pseudo selectors like :hover
, :after
, :nth-child
, or anything like that using jQuery.
If you want to add a CSS rule like that you have to create a <style>
element and add that :hover
rule to it just like you would in CSS. Then you would have to add that <style>
element to the page.
Using the .hover
function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:
$('head').append('<style>.myclass:hover div {background-color : red;}</style>')
If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.
Old Thread but I found this on my journey to the below answer and figure someone else might need it too.
=IFERROR(ArrayFormula(query(index(Sheet3!A:C&""),"select* Where Col1="""&B1&""" ")), ARRAYFORMULA({"* *","no cells","match"}));
Here is a simply built text Filter from a 3 column data set (A,B and C) located in "sheet3" into the current sheet and calling a comparison to a cell from the current sheet to filter within Col1(A)
.
This bit is just to get rid of the #N/A
error if the filter turns up no results //ARRAYFORMULA({"* *","no cells","match"}))
Looks like the extension is not installed in the particular database you require it.
You should connect to this particular database with
\CONNECT my_database
Then install the extension in this database
CREATE EXTENSION "uuid-ossp";
The .bash_profile for macOS is found in the $HOME
directory. You can create the file if it does not exit. Sublime Text 3 can help.
If you follow the instruction from OS X Command Line - Sublime Text to launch ST3 with subl
then you can just do this
$ subl ~/.bash_profile
An easier method is to use open
$ open ~/.bash_profile -a "Sublime Text"
Use Command + Shift + . in Finder to view hidden files in your home directory.
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None
and usecols=[3,6]
for the 4th and 7th columns:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
See the docs
In short:
static_cast<>()
gives you a compile time checking ability, C-Style
cast doesn't.static_cast<>()
is more readable and can be spotted easily
anywhere inside a C++ source code, C_Style cast is'nt.More Explanation:
The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer ( a pointer to 4-byte datatype) pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
You can also check this page on more explanation on C++ casts : Click Here
I built a general method for that with following features:
Here the code:
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
File repositoryFile = new File("c:/temp/myfile.png");
return returnFile(repositoryFile, modified);
}
/**
*
* Sends the file if modified and "not modified" if not modified
* future work may put each file with a unique id in a separate folder in tomcat
* * use that static URL for each file
* * if file is modified, URL of file changes
* * -> client always fetches correct file
*
* method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
*
* @param file to send
* @param modified - HeaderField "If-Modified-Since" - may be "null"
* @return Response to be sent to the client
*/
public static Response returnFile(File file, String modified) {
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
// do we really need to send the file or can send "not modified"?
if (modified != null) {
Date modifiedDate = null;
// we have to switch the locale to ENGLISH as parseDate parses in the default locale
Locale old = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
try {
modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
Locale.setDefault(old);
if (modifiedDate != null) {
// modifiedDate does not carry milliseconds, but fileDate does
// therefore we have to do a range-based comparison
// 1000 milliseconds = 1 second
if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
return Response.status(Status.NOT_MODIFIED).build();
}
}
}
// we really need to send the file
try {
Date fileDate = new Date(file.lastModified());
return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
} catch (FileNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
public static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1036,
PATTERN_RFC1123,
PATTERN_ASCTIME
};
Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...
Java native code necessities:
hope these points answers your question :)
Default values in appcompat-v7
<dimen name="abc_text_size_body_1_material">14sp</dimen>
<dimen name="abc_text_size_body_2_material">14sp</dimen>
<dimen name="abc_text_size_button_material">14sp</dimen>
<dimen name="abc_text_size_caption_material">12sp</dimen>
<dimen name="abc_text_size_display_1_material">34sp</dimen>
<dimen name="abc_text_size_display_2_material">45sp</dimen>
<dimen name="abc_text_size_display_3_material">56sp</dimen>
<dimen name="abc_text_size_display_4_material">112sp</dimen>
<dimen name="abc_text_size_headline_material">24sp</dimen>
<dimen name="abc_text_size_large_material">22sp</dimen>
<dimen name="abc_text_size_medium_material">18sp</dimen>
<dimen name="abc_text_size_menu_material">16sp</dimen>
<dimen name="abc_text_size_small_material">14sp</dimen>
<dimen name="abc_text_size_subhead_material">16sp</dimen>
<dimen name="abc_text_size_subtitle_material_toolbar">16dp</dimen>
<dimen name="abc_text_size_title_material">20sp</dimen>
<dimen name="abc_text_size_title_material_toolbar">20dp</dimen>
$str = "Is your name O\'vins?";
// Outputs: Is your name O'vins? echo stripslashes($str);
You can create a subprocess using Windows cmd.exe
that restarts yourself:
Process process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c net stop \"servicename\" & net start \"servicename\"";
process.Start();
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Found some of these answers very useful, but wanted to add this URL for completeness since it walks you through the questions:
https://itunespartner.apple.com/en/apps/faq/Managing%20Your%20Apps_Export%20Compliance#21109148
Actually, the HTML 4.01 spec says that these attributes do not require values. I haven't personally encountered a situation where providing a value rendered these controls as unselected.
Here are the respective links to the spec document for selected and checked.
Edit: Firebug renders the checkbox as checked regardless of any values I put in quotes for the checked attribute (including just typing "checked" with no values whatsoever), and IE 8's Developer Tools forces checked="checked". I'm not sure if any similar tools exist for other browsers that might alter the rendered state of a checkbox, however.
h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
http://docs.h5py.org/en/latest/quick.html
A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:
In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">
In [6]: h5f.close()
You can then load that data back in using: '
In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()
In [13]: np.allclose(a,b)
Out[13]: True
Definitely check out the docs:
Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save
, np.savez
etc:
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
Contrary to @Liza Daly's note about HTML5, that spec is actually quite specific about which tags can be omitted, and when (and the rules are a bit different from HTML 4.01, mostly to clarify where ambiguous elements like comments and whitespace belong)
The relevant reference is http://www.w3.org/TR/2011/WD-html5-20110525/syntax.html#optional-tags, and it says:
An html element's start tag may be omitted if the first thing inside the html element is not a comment.
An html element's end tag may be omitted if the html element is not immediately followed by a comment.
A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.
A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.
A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.
A body element's end tag may be omitted if the body element is not immediately followed by a comment.
So your example is valid HTML5, and would be parsed like this, with the html, head and body tags in their implied positions:
<!DOCTYPE html><HTML><HEAD>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<script src="js/head_script.js"></script></HEAD><BODY><!-- this script will be in head //-->
<div>Some html</div> <!-- here body starts //-->
<script src="js/body_script.js"></script></BODY></HTML>
Note that the comment "this script will be in head" is actually parsed as part of the body, although the script itself is part of the head. According to the spec, if you want that to be different at all, then the </HEAD>
and <BODY>
tags may not be omitted. (Although the corresponding <HEAD>
and </BODY>
tags still can be)
appsettings.json:
"MySetting": {
"MyValues": [
"C#",
"ASP.NET",
"SQL"
]
},
MySetting class:
namespace AspNetCore.API.Models
{
public class MySetting : IMySetting
{
public string[] MyValues { get; set; }
}
public interface IMySetting
{
string[] MyValues { get; set; }
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
...
}
Controller.cs
public class DynamicController : ControllerBase
{
private readonly IMySetting _mySetting;
public DynamicController(IMySetting mySetting)
{
this._mySetting = mySetting;
}
}
Access values:
var myValues = this._mySetting.MyValues;
To let the password least not pop up in your .bash_history
:
curl -u user:$(cat .password-file) http://example-domain.tld
Do you have an index defined over the Status column and MemberType column?
I was creating an application having a canvas over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf, I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.
I was using rxjs and angular 6, and didn't found any answer specific to the newest version.
Here is the entire code snippet that would be helpful, to anyone leveraging rxjs to draw on top of canvas.
private captureEvents(canvasEl: HTMLCanvasElement) {
this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
.pipe(
switchMap((e: any) => {
return fromEvent(canvasEl, 'mousemove')
.pipe(
takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
const prevPos = {
x: null,
y: null
};
})),
takeUntil(fromEvent(canvasEl, 'mouseleave')),
pairwise()
)
})
)
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = this.cx.canvas.getBoundingClientRect();
const prevPos = {
x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
const currentPos = {
x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
this.drawOnCanvas(prevPos, currentPos);
});
}
And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.
const prevPos = {
x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
const currentPos = {
x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0;
and bottom:0;
style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
I usually do this:
#define COLOR_STR(color) \
(RED == color ? "red" : \
(BLUE == color ? "blue" : \
(GREEN == color ? "green" : \
(YELLOW == color ? "yellow" : "unknown"))))
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
Try this:
if (Boolean.TRUE.equals(yourValue)) { ... }
As additional benefit this is null-safe.
My Working solution is
var town_code = $('#town_code').val();
if(town_code.trim().length == 0){
var town_code = 0;
}
If it is in RelativeLayout
you can use android:layout_toRightOf="@id/<id_of_desired_item>"
Or
If you want to align to the right
corner of the device the place android:layout_alignParentRight="true"
use this
$("#tblEntAttributes tbody").append(newRowContent);
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:
public class GenericList <T> extends ArrayList<T>
{
private Class<T> genericType;
public GenericList(Class<T> c)
{
this.genericType = c;
}
public Class<T> getGenericType()
{
return genericType;
}
}
For me, the problem was that in Android 5.0 the android:colorButtonNormal
had no effect, and actually, no item from the theme (like android:colorAccent
), but in Android 4.4.3, for example, did. The project was configured with compileSdkVersion
and targetSdkVersion
to 22, so I've made all the changes as @Muhammad Alfaifi sugessted, but in the end, I've noticed that the problem was the buildToolsVersion, that wasn't updated. Once I changed to 23.0.1, everything start working almost as normal. Now, the android:colorButtonNormal
still has no effect, but at least the button reacts to android:colorAccent
, which for me is acceptable.
I hope that this hint could help someone.
Note: I've applied the style directly to the button, since the button's android:theme=[...]
also didn't have effect.
Generally you can define the precision of a number in SQL by defining it with parameters. For most cases this will be NUMERIC(10,2)
or Decimal(10,2)
- will define a column as a Number with 10 total digits with a precision of 2 (decimal places).
Edited for clarity
If it helps someone you can just use css property
text-decoration-color: red;
I have created a class which adds a border to imageView h. Use this class instead of UIImageView.I have given a padding of 4. You can give as per your wish.
class UIBorderImageView: UIView {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.White()
self.layer.borderColor = UIColor.GreyMedium().cgColor
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 4.0
self.layer.masksToBounds = true
self.setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUpViews(){
self.addSubview(imageView)
self.addConstraintsWithFormat(format: "H:|-4-[v0]-4-|", views: imageView)
self.addConstraintsWithFormat(format: "V:|-4-[v0]-4-|", views: imageView)
}
func configureImageViewWith(image:UIImage){
self.imageview.image = image
}}
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
There is an option in the Interface Builder which calls the iOS 6/7 Delta property which aim to solve the offset problem.
Take a look at it in Stack Overflow question Interface Builder: What are the UIView's Layout iOS 6/7 Deltas for?.
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Even though this is fairly an old question, I have my 2 cents to share.
Like the zipball
link pointed by various answers here, There is a tarball
link as well which downloads the content of the git repository in tar.gz
format.
curl -L http://github.com/zoul/Finch/tarball/master/
Git also provides a different URL pattern where you can simply append the type of file you want to download at the end of url. This way is better if you want to process these urls in a batch or bash script.
curl -L http://github.com/zoul/Finch/archive/master.zip
curl -L http://github.com/zoul/Finch/archive/master.tar.gz
Replace master
with the commit-hash
or the branch-name
in the above urls like below.
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.zip
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.tar.gz
curl -L http://github.com/zoul/Finch/archive/your-branch-name.zip
curl -L http://github.com/zoul/Finch/archive/your-branch-name.tar.gz
If It is simple Session you can apply NULL
Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}
I have a problem with merged_cells and autosize not work correctly, if you have the same problem, you can solve with the next code:
for col in worksheet.columns:
max_length = 0
column = col[0].column # Get the column name
for cell in col:
if cell.coordinate in worksheet.merged_cells: # not check merge_cells
continue
try: # Necessary to avoid error on empty cells
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2) * 1.2
worksheet.column_dimensions[column].width = adjusted_width
You might also have a use case where you want to delete a block of text and replace it.
Like this
Hello World
Hello World
To
Hello Cool
Hello Cool
You can just visual block select "World" in both lines.
Type c for change - now you will be in insert mode.
Insert the stuff you want and hit escape.
Both get reflected vertically. It works just like 'I', except that it replaces the block with the new text instead of inserting it.
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Lütfen isaretli yerleri doldurunuz');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
For anyone looking at this old post, this is the easiest way to do it currently. It only requires an AngularJS $filter
. Its like Willemoes answer, but shorter and easier to understand.
{
"results": [
{
"id": 1,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
]
}
var object_by_id = $filter('filter')(foo.results, {id: 2 })[0];
// Returns { id: 2, name: "Beispiel" }
WARNING
As @mpgn says, this doesn't work properly. This will catch more results. Example: when you search 3 this will catch 23 too
If you want an alternative image instead of a text, you can as well use php:
$file="smiley.gif";
$alt_file="alt.gif";
if(file_exist($file)){
echo "<img src='".$file."' border="0" />";
}else if($alt_file){
// the alternative file too might not exist not exist
echo "<img src='".$alt_file."' border="0" />";
}else{
echo "smily face";
}
EDIT: (As per the comments in question:)
I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.
The best way to do it is:
return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");
'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
Use push_back()
:
std::string y("Hello worl");
y.push_back('d')
std::cout << y;
The .NET garbage collector takes care of all this for you.
It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.
The const with the int on either sides will make pointer to constant int:
const int *ptr=&i;
or:
int const *ptr=&i;
const
after *
will make constant pointer to int:
int *const ptr=&i;
In this case all of these are pointer to constant integer, but none of these are constant pointer:
const int *ptr1=&i, *ptr2=&j;
In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:
int const *ptr1=&i, *const ptr2=&j;
this.label1.BackColor = System.Drawing.Color.Transparent;
From go 1.13 onwards, if you had already configured your terminal with the git credentials and yet facing this issue, then you could try setting the GOPRIVATE
environment variable. Setting this environment variable solved this issue for me.
export GOPRIVATE=github.com/{organizationName/userName of the package}/*
This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.
I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.
On your exampe I would like to do this setup:
$ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
This request will return data in 0.10 second max
IIS will not server .woff
files by default, so in IIS you'll need to add a <mimeMap>
entry to your web.config
file;
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".woff" mimeType="application/x-woff" />
</staticContent>
</system.webServer>
</configuration>
I might have found it now. http://blog.lroot.com/articles/the-ie7-compatibility-tag-force-ie8-to-use-the-ie7-rendering-mode/
The site says adding this meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
or adding this to .htaccess
Header set X-UA-Compatible: IE=EmulateIE7
I am simply completing @Jasny's answer for others like @Brian
and I who have views in our database.
If you have an error like this:
ERROR 1347 (HY000) at line 17: 'dbname.table_name' is not of type 'BASE TABLE'
It's because you probably have views and you need to exclude them. But when trying to exclude them, MySQL returns 2 columns instead of 1.
SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE';
-- table_name1 BASE TABLE
-- table_name2 BASE TABLE
So we have to adapt Jasny's command with awk
to extract only the 1st column which contains the table name.
DB="dbname"
(
echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'
mysql "$DB" -e "SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'" --batch --skip-column-names \
| awk '{print $1 }' \
| xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;'
) \
| mysql "$DB"
DB="dbname"; ( echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'; mysql "$DB" -e "SHOW FULL TABLES WHERE Table_Type = 'BASE TABLE'" --batch --skip-column-names | awk '{print $1 }' | xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;' ) | mysql "$DB"
You probably mean Notification.Builder.setLargeIcon(Bitmap)
, right? :)
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap
s.
Ronal, to answer your question in the comment in my answer above:
function wasClicked(str)
{
return str+' def';
}
Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.
And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.
More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.
Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.
Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!
Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.
As I commented you need to use a StringIO object and decode i.e c=pd.read_csv(io.StringIO(s.decode("utf-8")))
if using requests, you need to decode as .content returns bytes if you used .text you would just need to pass s as is s = requests.get(url).text
c = pd.read_csv(StringIO(s))
.
A simpler approach is to pass the correct url of the raw data directly to read_csv
, you don't have to pass a file like object, you can pass a url so you don't need requests at all:
c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")
print(c)
Output:
Country Region
0 Algeria AFRICA
1 Angola AFRICA
2 Benin AFRICA
3 Botswana AFRICA
4 Burkina AFRICA
5 Burundi AFRICA
6 Cameroon AFRICA
..................................
From the docs:
filepath_or_buffer :
string or file handle / StringIO The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv
An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/
You're missing the ()
after ToString
that marks it as a function call vs. a function reference (the kind you pass to delegates), which incidentally is why c# has no AddressOf
operator, it's implied by how you type it.
Try this:
string guid = System.Guid.NewGuid().ToString();
I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems?
If you are a MS SQL developer, here is the answer directly from Microsoft.
IN
:
Determines whether a specified value matches any value in a subquery or a list.
Specifies a subquery to test for the existence of rows.
I played a bit with it and the syntax seems to get quite strange when a constructor takes no arguments. Let me give an example:
#include <iostream>
using namespace std;
class Thing
{
public:
Thing();
};
Thing::Thing()
{
cout << "Hi" << endl;
}
int main()
{
//Thing myThing(); // Does not work
Thing myThing; // Works
}
so just writing Thing myThing w/o brackets actually calls the constructor, while Thing myThing() makes the compiler thing you want to create a function pointer or something ??!!