The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <
)
select *
from xxx
where dates >= '20121026'
and dates < '20121028'
If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.
select *
from xxx
where CAST(dates as DATE) between '20121026' and '20121027'
This explicitly tells SQL Server that you are only interested in the DATE portion of the dates
column for comparison against the BETWEEN range.
Prolog predicates 'unify' -
So, in an imperative langauge I'd write
function bazoo(integer foo)
{
if(foo == 5)
doSomething();
else
doSomeOtherThing();
}
In Prolog I'd write
bazoo(5) :- doSomething.
bazoo(Foo) :- Foo =/= 5, doSomeOtherThing.
which, when you understand both styles, is actually a lot clearer.
"I'm bazoo for the special case when foo is 5"
"I'm bazoo for the normal case when foo isn't 5"
print_r($this->session->userdata);
or
print_r($this->session->all_userdata());
Because (
is special in regex, you should escape it \(
when matching. However, depending on what language you are using, you can easily match (
with string methods like index()
or other methods that enable you to find at what position the (
is in. Sometimes, there's no need to use regex.
The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø
== Tromso
).
I don't think this is possible. There appears to be an open Jira for it:
SPR-6702: Explicitly set response Content-Type in @ResponseBody
Reading app/config/mailphp
Supported : "smtp", "mail", "sendmail"
Depending on your mail utilities installed on your machine, fill in the value of the driver key. I would do
'driver' => 'sendmail',
Here's something I threw together to evaluate the truthiness of a string:
def as_bool(val):
if val:
try:
if not int(val): val=False
except: pass
try:
if val.lower()=="false": val=False
except: pass
return bool(val)
more-or-less same results as using eval
but safer.
There are situations where you can't use the (quite convincing) with... for...
structure. In that case, do the following:
line = self.fo.readline()
if len(line) != 0:
if 'str' in line:
break
This will work because the the readline()
leaves a trailing newline character, where as EOF is just an empty string.
ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;
worked in Oracle
e.g:
ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
I think the main and biggest difference they have is that ListView
looks for the position of the item while creating or putting it, on the other hand RecyclerView
looks for the type of the item. if there is another item created with the same type RecyclerView
does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView
doesn't try to create same type. ListView
doesn't have a this kind of pooling mechanism.
You can also use insertAdjacentHTML
function:
const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'
select.insertAdjacentHTML('beforeend', `
<option value="${value}">${label}</option>
`)
This worked for me while the other solutions were not!
This is stopping to need to be connected to your EC2 instance all the time. Therefore even if you loose connection due to internet connection loss, whenever you gain a new wifi access it automatically re-connects to the actively working kernel.
Also, don't forget to start your jupyter in a tmux account or a ngnix or other environments like that.
Hope this helps!
Try this, I think this is a natively way to concatenate strings in Kotlin:
val result = buildString{
append("a")
append("b")
}
println(result)
// you will see "ab" in console.
Most used is this:
$("input[name='varname[]']").map( function(key){
console.log(key+':'+$(this).val());
})
Whit that you get the key of the array possition and the value.
Here is a theme that I copied all the important parts of the Visual Studio 2013 dark theme.
**Update 08/Sep/15 - Qt Creator 3.5.1/Qt 5.5.1 might have fixed the rest of Qt not being dark properly and hard to read.
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
From the jinja docs section HTML Escaping:
When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.
Example:
<div class="info">
{{data.email_content|safe}}
</div>
A different way of implementing login redirection is to use events and interceptors as described here. The article describes some additional advantages such as detecting when a login is required, queuing the requests, and replaying them once the login is successful.
You can try out a working demo here and view the demo source here.
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode
to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
broadcast implementation on Kotlin:
private class SmsListener : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d(TAG, "SMS Received!")
val txt = getTextFromSms(intent?.extras)
Log.d(TAG, "message=" + txt)
}
private fun getTextFromSms(extras: Bundle?): String {
val pdus = extras?.get("pdus") as Array<*>
val format = extras.getString("format")
var txt = ""
for (pdu in pdus) {
val smsmsg = getSmsMsg(pdu as ByteArray?, format)
val submsg = smsmsg?.displayMessageBody
submsg?.let { txt = "$txt$it" }
}
return txt
}
private fun getSmsMsg(pdu: ByteArray?, format: String?): SmsMessage? {
return when {
SDK_INT >= Build.VERSION_CODES.M -> SmsMessage.createFromPdu(pdu, format)
else -> SmsMessage.createFromPdu(pdu)
}
}
companion object {
private val TAG = SmsListener::class.java.simpleName
}
}
Note: In your manifest file add the BroadcastReceiver-
<receiver android:name=".listener.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add this permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &
. That also requires using parentheses so that &
wouldn't take precedence.
It would go something like this:
mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
In order to avoid that, you can build series for lower and upper limits:
low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
Now you can slice it as follows:
mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
And for assignment you can use np.where:
df['class'] = np.where(mask, 'excellent', 'critical')
If I have understood well, you can get it replacing your echo with the following line:
echo -ne "Movie $movies - $dir ADDED! \033[0K\r"
Here is a small example that you can run to understand its behaviour:
#!/bin/bash
for pc in $(seq 1 100); do
echo -ne "$pc%\033[0K\r"
sleep 1
done
echo
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtils
class.
Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang StringUtils
for common string operations and such can make your code more readable.
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';
Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/
For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...
$("#myid li").click(function() {
alert(this.id); // id of clicked li by directly accessing DOMElement property
alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
alert($(this).html()); // gets innerHTML of clicked li
alert($(this).text()); // gets text contents of clicked li
});
If you are talking about replacing the ID with something:
$("#myid li").click(function() {
this.id = 'newId';
// longer method using .attr()
$(this).attr('id', 'newId');
});
Demo here. And to be fair, you should have first tried reading the documentation:
Test the return value of grep:
./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
echo "matched"
fi
which is done idiomatically like so:
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
and also:
./somecommand | grep -q 'string' && echo 'matched'
FQDN/auth/realms/{realm_name}/.well-known/openid-configuration
you will see everything here, plus if the identity provider is also Keycloak then feeding this URL will setup everything also true with other identity providers if they support and they already handled it
SUPER-SHIFT-p > File: Revert File
is the only way
(where SUPER
is Command
on Mac and Ctrl
on PC)
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
The only time you should worry your users about something that happened in the code is if there is something they can or need to do to avoid the issue. If they can change data on a form, push a button or change a application setting in order to avoid the issue then let them know. But warnings or errors that the user has no ability to avoid just makes them lose confidence in your product.
Exceptions and Logs are for you, the developer, not your end user. Understanding the right thing to do when you catch each exception is far better than just applying some golden rule or rely on an application-wide safety net.
Mindless coding is the ONLY kind of wrong coding. The fact that you feel there is something better that can be done in those situations shows that you are invested in good coding, but avoid trying to stamp some generic rule in these situations and understand the reason for something to throw in the first place and what you can do to recover from it.
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
I wrote the following simple class as, effectively, a way to emulate a pointer in python:
class Parameter:
"""Syntactic sugar for getter/setter pair
Usage:
p = Parameter(getter, setter)
Set parameter value:
p(value)
p.val = value
p.set(value)
Retrieve parameter value:
p()
p.val
p.get()
"""
def __init__(self, getter, setter):
"""Create parameter
Required positional parameters:
getter: called with no arguments, retrieves the parameter value.
setter: called with value, sets the parameter.
"""
self._get = getter
self._set = setter
def __call__(self, val=None):
if val is not None:
self._set(val)
return self._get()
def get(self):
return self._get()
def set(self, val):
self._set(val)
@property
def val(self):
return self._get()
@val.setter
def val(self, val):
self._set(val)
Here's an example of use (from a jupyter notebook page):
l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
return lst[number]
def l1_5_setter(val, lst=l1, number=5):
lst[number] = val
[
l1_5_getter(),
l1_5_setter(12),
l1,
l1_5_getter()
]
Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]
p = Parameter(l1_5_getter, l1_5_setter)
print([
p(),
p.get(),
p.val,
p(13),
p(),
p.set(14),
p.get()
])
p.val = 15
print(p.val, l1)
[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]
Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():
def setter(val, dict=globals(), key='a'):
dict[key] = val
def getter(dict=globals(), key='a'):
return dict[key]
pa = Parameter(getter, setter)
pa(2)
print(a)
pa(3)
print(a)
This will print out 2, followed by 3.
Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.
The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.
Although it doesn't look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.
This should help:
if(screen.width<1026){//get the screen width
//get element form document
elem.style.display == 'none'//toggle visibility
}
768 px should be enough as well
I would suggest you to use either an image or text. So, Remove the text and add it in your image(using Photoshop, maybe). Then, Use a width and height 100% for the image. it will do the trick. because the image can be resized based on the container. But, you have to manually resize the text. If you can provide the fiddle, I can help you achieve this.
Make sure you read SilverlightFox's answer. It highlights a more important reason.
The reason is mostly that if you know the source of a request you may want to customize it a little bit.
For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click.
The link may be www.example.com/recipe/apple_pie
Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.
Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie
but that's harder to maintain and share to other people.
But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.
The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.
It's actually kind of similar to the Accept-Language
header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.
Instead of making a touchable UIImageView then placing it on the navbar, you should just create a UIBarButtonItem, which you make out of a UIImageView.
First make the image view:
UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nameOfYourImage.png"]];
Then make the barbutton item out of your image view:
UIBarButtonItem *yourBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:yourImageView];
Then add the bar button item to your navigation bar:
self.navigationItem.rightBarButtonItem = yourBarButtonItem;
Remember that this code goes into the view controller which is inside a navigation controller viewcontroller array. So basically, this "touchable image-looking bar button item" will only appear in the navigation bar when this view controller when it's being shown. When you push another view controller, this navigation bar button item will disappear.
Although it creates a little clutter, it is worth putting final
. Ides e.g eclipse can automatically put the final
if you configure it to do so.
Yes, kill should be fine if you're running Jenkins with the built-in Winstone container. This Jenkins Wiki page has some tips on how to set up control scripts for Jenkins.
In my case, the problem popped up while configuring the web application on IIS, When the update command on any record was fired this error got generated.
It was a permission issue on App_Data which set to read-only. Right-click the folder, uncheck the Read-only checkbox and you are done. By the way, for testing purpose, I was using the localdb database which was in App_Data folder.
You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:
Use YQL: a sql-like language to retrieve stuff from public api's: YQL Console (external link)
It gives you a nice XML file to work with!
You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:
for(int i = 0; i < arraySize; i++){
if(array[i] == itemToFind){
break;
}
}
Velocity is a good candidate for writing this kind of stuff.
It allows you to keep your html and data-generation code as separated as possible.
My take on this for future people watching this:
This could also happen if you're using: <?
instead of <?php
.
try to break your large data as much as possible because I already faced number of times this types of problem. In which I have above 10 Lakh records with 15 columns.
You should \usepackage{longtable}
.
Note that the answers that suggest using unbind()
are now out of date as that method has been deprecated and will be removed in future versions of jQuery.
As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.
Instead, you should now use off()
:
$(window).off('scroll');
Check out the PHP cURL functions. They should do what you want.
Or if you just want a simple URL GET then:
$lines = file('http://www.example.com/');
Have you tried:
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("Data")
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)
Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};...
connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN";
worked, so I carried on experimenting for my in-house testing and learning purposes.
Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \
as \\
:)
After some dead-ends with server=server1;instanceName=dev
in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"
Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true
v Integrated Security = SSPI
v Trusted_Connection=Yes
- see Difference between Integrated Security = True and Integrated Security = SSPI
Beware that RecordCount will come back as -1
if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3);
(3=adOpenStatic) and this gives a valid rs.RecordCount
With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true
//First define some delay function which is called from async function_x000D_
function __delay__(timer) {_x000D_
return new Promise(resolve => {_x000D_
timer = timer || 2000;_x000D_
setTimeout(function () {_x000D_
resolve();_x000D_
}, timer);_x000D_
});_x000D_
};_x000D_
_x000D_
//Then Declare Some Variable Global or In Scope_x000D_
//Depends on you_x000D_
let Variable = false;_x000D_
_x000D_
//And define what ever you want with async fuction_x000D_
async function some() {_x000D_
while (!Variable)_x000D_
await __delay__(1000);_x000D_
_x000D_
//...code here because when Variable = true this function will_x000D_
};_x000D_
////////////////////////////////////////////////////////////_x000D_
//In Your Case_x000D_
//1.Define Global Variable For Check Statement_x000D_
//2.Convert function to async like below_x000D_
_x000D_
var isContinue = false;_x000D_
setTimeout(async function () {_x000D_
//STOPT THE FUNCTION UNTIL CONDITION IS CORRECT_x000D_
while (!isContinue)_x000D_
await __delay__(1000);_x000D_
_x000D_
//WHEN CONDITION IS CORRECT THEN TRIGGER WILL CLICKED_x000D_
$('a.play').trigger("click");_x000D_
}, 1);_x000D_
/////////////////////////////////////////////////////////////
_x000D_
Also you don't have to use setTimeout in this case just make ready function asynchronous...
Try CAST(CAST(@value AS bigint) AS varchar)
press Ctrl + H . Then choose "File Search" tab.
additional search options
search for resources: Ctrl + Shift + R
search for Java types: Ctrl + Shift + T
i do it with os.system temp file:
import tempfile,os
def readcmd(cmd):
ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False)
fpath = ftmp.name
if os.name=="nt":
fpath = fpath.replace("/","\\") # forwin
ftmp.close()
os.system(cmd + " > " + fpath)
data = ""
with open(fpath, 'r') as file:
data = file.read()
file.close()
os.remove(fpath)
return data
This is the general structure of an html document.
<html>
<head>
Title, meta-data, scripts, etc go here... Don't confuse with header
</head>
<body>
You body stuff comes here...
<footer>
Your footer stuff goes here...
</footer>
</body>
</html>
Let's say you have one more commit at the bottom (oldest), then this becomes pretty easy:
commit dj374
made changes
commit y4746
made changes
commit k73ud
made changes
commit oldestCommit
made changes
Now, using below will easily server the purpose.
git diff k73ud oldestCommit
It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).
Specifics are described as Netbeans bug #248182.
This problem is also related to postings mentioning the following error output:
'127.0.0.1*' is not recognized as an internal or external command, operable program or batch file.
For a tomcat installed from the zip file, I fixed it by changing the catalina.bat
file in the tomcat bin
directory.
Find the bellow configuration in your catalina.bat
file.
:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"
:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"
And change it as in below by removing the double quotes:
:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%
:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%
Now save your changes, and start your tomcat from within NetBeans.
If you're confused how table layouts work, they basically start at x=0, y=0 and work their way across. Let's explain with graphics, because they're so much fun!
When you start a table, you make a grid. Your first row and cell will be in the top left corner. Think of it like an array pointer, moving to the right with each incremented value of x, and moving down with each incremented value of y.
For your first row, you're only defining two cells. One spans 2 rows down and one spans 4 columns across. So when you reach the end of your first row, it looks something like this:
<table>
<tr>
<td rowspan="2"></td>
<td colspan="4"></td>
</tr>
</table>
Now that the row has ended, the "array pointer" jumps down to the next row. Since x position 0 is already taken up by a previous cell, x jumps to position 1 to start filling in cells. * See note about difference between rowspans.
This row has four cells in it which are all 1x1 blocks, filling in the same width of the row above it.
<table>
<tr>
<td rowspan="2"></td>
<td colspan="4"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The next row is all 1x1 cells. But, for example, what if you added an extra cell? Well, it would just pop off the edge to the right.
<table>
<tr>
<td rowspan="2"></td>
<td colspan="4"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
* But what if we instead (rather than adding the extra cell) made all these cells have a rowspan of 2? The thing you need to consider here is that even though you're not going to be adding any more cells in the next row, the row still must exist (even though it's an empty row). If you did try to add new cells in the row immediately after, you'd notice that it would start adding them to the end of the bottom row.
<table>
<tr>
<td rowspan="2"></td>
<td colspan="4"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td rowspan="2"></td>
<td rowspan="2"></td>
<td rowspan="2"></td>
<td rowspan="2"></td>
<td rowspan="2"></td>
</tr>
<tr>
<td></td>
</tr>
</table>
Enjoy the wonderful world of creating tables!
You can change axis text and label size with arguments axis.text=
and axis.title=
in function theme()
. If you need, for example, change only x axis title size, then use axis.title.x=
.
g+theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"))
There is good examples about setting of different theme()
parameters in ggplot2 page.
Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString()
it:
Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z
Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):
instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763
Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):
instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664
etc.
python setup.py install
You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install
EDIT- thanks to kwatford (see first comment)
To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.
The docs say:
Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:
More details can be found here: http://docs.python.org/2.7/install/index.html
you just open command prompt,
then enter in c:/>('cd../../')
then npm install -g cordova
Sure!
#file -- test.py --
myvar = 42
def test_func():
print("Hello!")
Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH
) Note that the current directory is always in PYTHONPATH
, so if use_test
is being run from the same directory where test.py
lives, you're all set:
#file -- use_test.py --
import test
test.test_func() #prints "Hello!"
print (test.myvar) #prints 42
from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar) #Exception (NameError)
from test import *
test_func() #prints "Hello"
print(myvar) #prints 42
There's a lot more you can do than just that through the use of special __init__.py
files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.
It can handle recursive objects or arrays in the STANDARD query form like a=val&b[0]=val&b[1]=val&c=val&d[some key]=val
, here's the final function.
const objectToQueryString = (initialObj) => {
const reducer = (obj, parentPrefix = null) => (prev, key) => {
const val = obj[key];
key = encodeURIComponent(key);
const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;
if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
if (['number', 'boolean', 'string'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val)}`);
return prev;
}
prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
return prev;
};
return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};
const testCase1 = {
name: 'Full Name',
age: 30
}
const testCase2 = {
name: 'Full Name',
age: 30,
children: [
{name: 'Child foo'},
{name: 'Foo again'}
],
wife: {
name: 'Very Difficult to say here'
}
}
console.log(objectToQueryString(testCase1));
console.log(objectToQueryString(testCase2));
Expand the snippet below to verify the result in your browser -
const objectToQueryString = (initialObj) => {
const reducer = (obj, parentPrefix = null) => (prev, key) => {
const val = obj[key];
key = encodeURIComponent(key);
const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;
if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
if (['number', 'boolean', 'string'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val)}`);
return prev;
}
prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
return prev;
};
return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};
const testCase1 = {
name: 'Full Name',
age: 30
}
const testCase2 = {
name: 'Full Name',
age: 30,
children: [
{name: 'Child foo'},
{name: 'Foo again'}
],
wife: {
name: 'Very Difficult to say here'
}
}
console.log(objectToQueryString(testCase1));
console.log(objectToQueryString(testCase2));
_x000D_
functions
, null
, undefined
keys
and values
for empty objects and arrays.new Number(1)
or new String('my string')
because NO ONE should ever do thatActually, Ruby does have an in-place editing feature. Like Perl, you can say
ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt
This will apply the code in double-quotes to all files in the current directory whose names end with ".txt". Backup copies of edited files will be created with a ".bak" extension ("foobar.txt.bak" I think).
NOTE: this does not appear to work for multiline searches. For those, you have to do it the other less pretty way, with a wrapper script around the regex.
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
body {
margin: 0;
padding: 0;
background: url('img/background.jpg') repeat;
}
body:before {
content: " ";
width: 100%;
height: 100%;
position: absolute;
z-index: -1;
top: 0;
left: 0;
background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}
PLEASE NOTE: This only using webkit so it will only work in webkit browsers.
try :
-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)
Just add these 2 lines;
android:gravity="center_horizontal"
android:textAlignment="center"
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
If you're deploying on Windows, the Windows Script Host offers a very useful JScript API to the file system and other local resources. Incorporating WSH scripts into a local web application may not be as elegant as you might wish, however.
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
Yes. You can pass a java array to Arrays.asList(Object[]).
List<String> fixedSizeList = Arrays.asList(new String[100]);
You cannot insert new Strings to the fixedSizeList (it already has 100 elements). You can only set its values like this:
fixedSizeList.set(7, "new value");
That way you have a fixed size list. The thing functions like an array and I can't think of a good reason to use it. I'd love to hear why you want your fixed size collection to be a list instead of just using an array.
There is a strcat() function from the ported C library that will do "C style string" concatenation for you.
BTW even though C++ has a bunch of functions to deal with C-style strings, it could be beneficial for you do try and come up with your own function that does that, something like:
char * con(const char * first, const char * second) {
int l1 = 0, l2 = 0;
const char * f = first, * l = second;
// step 1 - find lengths (you can also use strlen)
while (*f++) ++l1;
while (*l++) ++l2;
char *result = new char[l1 + l2];
// then concatenate
for (int i = 0; i < l1; i++) result[i] = first[i];
for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];
// finally, "cap" result with terminating null char
result[l1+l2] = '\0';
return result;
}
...and then...
char s1[] = "file_name";
char *c = con(s1, ".txt");
... the result of which is file_name.txt
.
You might also be tempted to write your own operator +
however IIRC operator overloads with only pointers as arguments is not allowed.
Also, don't forget the result in this case is dynamically allocated, so you might want to call delete on it to avoid memory leaks, or you could modify the function to use stack allocated character array, provided of course it has sufficient length.
For jQuery, do you mean like this?
$('#object').css('display');
You can check it like this:
if($('#object').css('display') === 'block')
{
//do something
}
else
{
//something else
}
Create a .bat
file and write two commands:
cd C:\ Path to your tomcat directory \ bin
startup.bat
Now on double-click, Tomcat server will start.
use
struct arg_struct *args = (struct arg_struct *)arguments;
in place of
struct arg_struct *args = (struct arg_struct *)args;
Thanks for all the answers everyone! I have found a solution, turns out I didn't provide enough code in my question.
The problem was NOT with the click() function after all, but instead related to cas authentication used with my project. In Selenium IDE my login test executed a "open" command to the following location,
/cas/login?service=https%1F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security
That worked. I exported the test to Selenium webdriver which naturally preserved that location. The command in Selenium Webdriver was,
driver.get(baseUrl + "/cas/login?service=https%1A%2F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security");
For reasons I have yet to understand the above failed. When I changed it to,
driver.get(baseUrl + "MOREURL/");
The click command suddenly started to work... I will edit this answer if I can figure out why exactly this is.
Note: I obscured the URLs used above to protect my company's product.
Easy, you can use a Post request and submit your file as binary (byte array).
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
This line is the problem:
int estimatedPopulation (int currentPopulation,
float growthRate (birthRate, deathRate))
Make it:
int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)
instead and invoke the function with three arguments like
estimatePopulation( currentPopulation, birthRate, deathRate );
OR declare it with two arguments like:
int estimatedPopulation (int currentPopulation, float growthrt ) { ... }
and call it as
estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));
Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate
variable in the main()
hides the function with the same name. So within main()
you can only access grouthRate
as float
. On the other hand, outside of the main()
you can only access that name as a function, since that automatic variable is only visible within the scope of main()
.
Just hope I didn't confuse you further :)
The following adds one line after SearchPattern
.
sed -i '/SearchPattern/aNew Text' SomeFile.txt
It inserts New Text
one line below each line that contains SearchPattern
.
To add two lines, you can use a \
and enter a newline while typing New Text
.
POSIX sed requires a \
and a newline after the a
sed function. [1]
Specifying the text to append without the newline is a GNU sed extension (as documented in the sed
info page), so its usage is not as portable.
[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
Add this to your main CSS:
table td {
border-top: none !important;
}
Use this for newer versions of bootstrap:
.table th, .table td {
border-top: none !important;
}
I had the same, eclipse polluted files even with one line change. Solution: Eclipse git settings -> Add Entry: Key: core.autocrlf Values: true
You need to start creating the JAR at the root of the files.
So, for instance:
jar cvf program.jar -C path/to/classes .
That assumes that path/to/classes
contains the com
directory.
FYI, these days it is relatively uncommon for most people to use the jar
command directly, as they will use a build tool such as Ant or Maven to take care of that (and other aspects of the build). It is well worth the effort of allowing one of those tools to take care of all aspects of your build, and it's even easier with a good IDE to help write the build.xml
(Ant) or pom.xml
(Maven).
Another solution, declare your controller as UITextFieldDelegate, implement this call-back:
@IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == myTextField {
return false; //do not show keyboard nor cursor
}
return true
}
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
Answer:
public void Print(string FileName)
{
StringBuilder logMessage = new StringBuilder();
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
try
{
if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
PrintDocument pd = new PrintDocument();
//Disable the printing document pop-up dialog shown during printing.
PrintController printController = new StandardPrintController();
pd.PrintController = printController;
//For testing only: Hardcoded set paper size to particular paper.
//pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
//pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrintPage += (sndr, args) =>
{
System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
//Adjust the size of the image to the page to print the full image without loosing any part of the image.
System.Drawing.Rectangle m = args.MarginBounds;
//Logic below maintains Aspect Ratio.
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
//Calculating optimal orientation.
pd.DefaultPageSettings.Landscape = m.Width > m.Height;
//Putting image in center of page.
m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
args.Graphics.DrawImage(i, m);
};
pd.Print();
}
catch (Exception ex)
{
log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
}
finally
{
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
log.Info(logMessage.ToString());
}
}
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
Why not just use the option Find and Replace. (every code editor has it)?
For example Visual Studio Code (under Edit option):
You just type in old name and new name and replace everyhting in the project with one click.
NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/
rename it to templates/my_app_new_name/
Floating point numbers are encoded using an exponential form, that is something like m * b ^ e
, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.
Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333
) which do not have a finite presentation in decimal but do have one in binary and vice versa.
Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1
yields value
, since value + 1
can not be encoded using m * b ^ e
, where m
, b
and e
are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.
Because of this there is no precision of exactly n
digits like with fixed point numbers, since not every number with n
decimal digits does have a IEEE encoding.
There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.
Try the following command, it worked for me.
cd; cd -
In my case there was a formatting issue earlier on, so the error was a consequence of something else. My server was rendering the lat/lon values with commas instead of periods, because of different regional settings.
In bash, you can construct a command line like the following:
$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
[1] 1 2 3 4 5 6 7 8 9 10
[1] 5.5
[1] 3.027650
$
You can see that the variable $z
is substituted by bash shell with "10" and this value is picked up by commandArgs
and fed into args[2]
, and the range command x=1:10
executed by R successfully, etc etc.
There's a new library in town, from rOpenSci: writexl
Portable, light-weight data frame to xlsx exporter based on libxlsxwriter. No Java or Excel required
I found it better and faster than the above suggestions (working with the dev version):
library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Ternary is the most clear way of doing this.
<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>
r = list(qs[:1])
if r:
return r[0]
return None
I had the same problems. I had to change file rights. Unmark "read only" in their properties.
This seems to be the default behavior on iOS 10.3 based on behavior people have been witnessing in beta #2. Haven't found any official documentation about this yet so please comment if you have.
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php
library
is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.
Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.
What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:
library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};
"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.
<BUTTON NAME='my_button' VALUE=sequence_no TYPE='SUBMIT' style="background-color:transparent ; border:none; color:blue;" onclick="this.form.target='_blank';return true;"><u>open new page</u></BUTTON>
This button will look like a URL and can be opened in a new tab.
function checkdate() {
var indate = new Date()
indate.setDate(dat)
indate.setMonth(mon - 1)
indate.setFullYear(year)
var one_day = 1000 * 60 * 60 * 24
var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
var str = diff + " days are remaining.."
document.getElementById('print').innerHTML = str.fontcolor('blue')
}
You can also use git diff HEAD file
to show the diff for a specific file.
See the EXAMPLE
section under git-diff(1)
I needed to be able to pause setTimeout() for slideshow-like feature.
Here is my own implementation of a pausable timer. It integrates comments seen on Tim Down's answer, such as better pause (kernel's comment) and a form of prototyping (Umur Gedik's comment.)
function Timer( callback, delay ) {
/** Get access to this object by value **/
var self = this;
/********************* PROPERTIES *********************/
this.delay = delay;
this.callback = callback;
this.starttime;// = ;
this.timerID = null;
/********************* METHODS *********************/
/**
* Pause
*/
this.pause = function() {
/** If the timer has already been paused, return **/
if ( self.timerID == null ) {
console.log( 'Timer has been paused already.' );
return;
}
/** Pause the timer **/
window.clearTimeout( self.timerID );
self.timerID = null; // this is how we keep track of the timer having beem cleared
/** Calculate the new delay for when we'll resume **/
self.delay = self.starttime + self.delay - new Date().getTime();
console.log( 'Paused the timer. Time left:', self.delay );
}
/**
* Resume
*/
this.resume = function() {
self.starttime = new Date().getTime();
self.timerID = window.setTimeout( self.callback, self.delay );
console.log( 'Resuming the timer. Time left:', self.delay );
}
/********************* CONSTRUCTOR METHOD *********************/
/**
* Private constructor
* Not a language construct.
* Mind var to keep the function private and () to execute it right away.
*/
var __construct = function() {
self.starttime = new Date().getTime();
self.timerID = window.setTimeout( self.callback, self.delay )
}(); /* END __construct */
} /* END Timer */
Example:
var timer = new Timer( function(){ console.log( 'hey! this is a timer!' ); }, 10000 );
timer.pause();
To test the code out, use timer.resume()
and timer.pause()
a few times and check how much time is left. (Make sure your console is open.)
Using this object in place of setTimeout() is as easy as replacing timerID = setTimeout( mycallback, 1000)
with timer = new Timer( mycallback, 1000 )
. Then timer.pause()
and timer.resume()
are available to you.
It solved my issue
smtpClient.Credentials = new NetworkCredential(sendMail.UserName, sendMail.Password);
smtpClient.EnableSsl = false;//sendMail.EnableSSL;
// With Reference to // Problem comes only Use above line to set false SSl to solve error when username and password is entered in SMTP settings.
I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:
SELECT a.*
FROM a
JOIN (
SELECT a.alias, MAX(a.year) as max_year
FROM a
GROUP BY a.alias
) b
ON a.alias=b.alias and a.year=b.max_year
Outline of solution:
Here's the solution query:
CREATE VIEW v_max_year AS
SELECT alias, MAX(year) as max_year
FROM a
GROUP BY a.alias;
CREATE VIEW v_latest_info AS
SELECT a.*
FROM a
JOIN v_max_year b
ON a.alias=b.alias and a.year=b.max_year;
It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).
Something like this will list and extract the files one by one, if you want to use SharpZipLib:
var zip = new ZipInputStream(File.OpenRead(@"C:\Users\Javi\Desktop\myzip.zip"));
var filestream = new FileStream(@"C:\Users\Javi\Desktop\myzip.zip", FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
Console.WriteLine(item.Name);
using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
{
// stream with the file
Console.WriteLine(s.ReadToEnd());
}
}
Based on this example: content inside zip file
This RE will do:
/^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i
Explanation of RE:
(?:...)
creates an unreferenced group/i
is the ignore-case flag, so that a-z
== a-zA-Z
.try this
new Handler().postDelayed(
new Runnable(){
@Override
public void run() {
if (i == 1){
tabLayout.getTabAt(0).select();
} else if (i == 2){
tabLayout.getTabAt(1).select();
}
}
}, 100);
for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!
i mean instead of this junk ternary condition inside your jsx in render part of your component:
// some component body
return(
<section>
{/* some ui */}
{ someCondition && <MyComponent /> }
or
{ someCondition ? <MyComponent /> : null }
{/* more ui */}
</section>
)
you can check than condition inside your component like:
const MyComponent:React.FC = () => {
// get someCondition from context at here before any thing
if(someCondition) return null; // i mean this part , checking inside component!
return (
<section>
// some ui...
</section>
)
}
Just Consider that in my case i provide the someCondition
variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition
inside MyComponent
.
Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:
// some component body
return(
<section>
{/* some ui */}
<MyComponent />
{/* more ui */}
</section>
)
and MyComponent
would handle the rest for you!
From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.
If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/>
instruction:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
When applying this transformation on the provided XML document:
<root><node/></root>
most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:
<root> <node /> </root>
Using split()
will be the most Pythonic way of splitting on a string.
It's also useful to remember that if you use split()
on a string that does not have a whitespace then that string will be returned to you in a list.
Example:
>>> "ark".split()
['ark']
Add the following to your Gemfile
ruby '2.3.0'
From the documentation:
Return date object with same year, month and day.
Using generics (as in the above answers) is your best bet here. I've just double checked and:
test.put("test", arraylistone);
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");
will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.
Replace the vendor id of 0bb4
with 18d1
in /etc/udev/rules.d/51-android.rules
Or add another line that reads:
SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"
As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.
Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T
generic type parameter.
interface ISignatur<T>
{
Type Type { get; }
}
interface IAccess<T>
{
ISignatur<T> Signature { get; }
T Value { get; set; }
}
class Signatur : ISignatur<bool>
{
public Type Type
{
get { return typeof(bool); }
}
}
class ServiceGate
{
public IAccess<T> Get<T>(ISignatur<T> sig)
{
throw new NotImplementedException();
}
}
static class Test
{
static void Main()
{
ServiceGate service = new ServiceGate();
var access = service.Get(new Signatur());
}
}
With plain old vanilla javaScript, here's a solution to promisify an api callback.
function get(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('successful ... should call callback ... ');
callback(null, JSON.parse(xhr.responseText));
} else {
console.log('error ... callback with error data ... ');
callback(xhr, null);
}
}
});
xhr.send();
}
/**
* @function promisify: convert api based callbacks to promises
* @description takes in a factory function and promisifies it
* @params {function} input function to promisify
* @params {array} an array of inputs to the function to be promisified
* @return {function} promisified function
* */
function promisify(fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return new Promise(function(resolve, reject) {
fn.apply(null, args.concat(function (err, result) {
if (err) reject(err);
else resolve(result);
}));
});
}
}
var get_promisified = promisify(get);
var promise = get_promisified('some_url');
promise.then(function (data) {
// corresponds to the resolve function
console.log('successful operation: ', data);
}, function (error) {
console.log(error);
});
To build a result string exactly in the format you show, you can use this:
var sList = "";
$('input[type=checkbox]').each(function () {
sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
});
console.log (sList);
However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.
EDIT: Sorry, I mis-read the output format you were looking for. Here is an update:
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);
Instead of IN
we can use ANY
with arrays casted to enum array, for example:
create type example_enum as enum (
'ENUM1', 'ENUM2'
);
create table example_table (
id integer,
enum_field example_enum
);
select
*
from
example_table t
where
t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);
Or we can still use 'IN' clause, but first, we should 'unnest' it:
select
*
from
example_table t
where
t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));
Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0
In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this
<binding name="WebServiceName" receiveTimeout="00:00:59" />
Use snprintf()
from stdlib.h
. Worked for me.
double num = 123412341234.123456789;
char output[50];
snprintf(output, 50, "%f", num);
printf("%s", output);
i created a node module called "rekiure"
it allows you to require without the use of relative paths
it is super easy to use
You can use the Media Library Folders plugin. It allows you to create folders, move or copy images to a folder and even includes a sync function to bulk add images uploaded by FTP to the server to the Wordpress media library.
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.
iTextSharp Example
You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
class Program
{
static void Main(string[] args)
{
// Right side of equation is location of YOUR pdf file
string ppath = "C:\\aworking\\Hawkins.pdf";
PdfReader pdfReader = new PdfReader(ppath);
int numberOfPages = pdfReader.NumberOfPages;
Console.WriteLine(numberOfPages);
Console.ReadLine();
}
}
}
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.
The last version of Mono to support Windows XP was 3.2.3.
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
Try this .. this method works for me..!! hope it may help somebody..!!
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:singleLine="true"
android:text="Toolbar Title"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
To display logo in toolbar try the below snippet. // Set drawable
toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));
Let me know the result.
Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).
From the Java Language Specification
15.17.3 Remainder Operator %
[...]
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.
Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
Ran into this just now in a Unit Test project after adding MsTest V2 through Nuget. Renaming app.config (so effectively removing it) did the trick for me.
Having read through all the above posts, I'm still not sure why, sorry!
revalidate
is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate
will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel
are considered dirty by the RepaintManager
.
repaint
is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.
If you don't want CPU time then I think what you're looking for is the timeval struct.
I use the below for calculating execution time:
int timeval_subtract(struct timeval *result,
struct timeval end,
struct timeval start)
{
if (start.tv_usec < end.tv_usec) {
int nsec = (end.tv_usec - start.tv_usec) / 1000000 + 1;
end.tv_usec -= 1000000 * nsec;
end.tv_sec += nsec;
}
if (start.tv_usec - end.tv_usec > 1000000) {
int nsec = (end.tv_usec - start.tv_usec) / 1000000;
end.tv_usec += 1000000 * nsec;
end.tv_sec -= nsec;
}
result->tv_sec = end.tv_sec - start.tv_sec;
result->tv_usec = end.tv_usec - start.tv_usec;
return end.tv_sec < start.tv_sec;
}
void set_exec_time(int end)
{
static struct timeval time_start;
struct timeval time_end;
struct timeval time_diff;
if (end) {
gettimeofday(&time_end, NULL);
if (timeval_subtract(&time_diff, time_end, time_start) == 0) {
if (end == 1)
printf("\nexec time: %1.2fs\n",
time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));
else if (end == 2)
printf("%1.2fs",
time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));
}
return;
}
gettimeofday(&time_start, NULL);
}
void start_exec_timer()
{
set_exec_time(0);
}
void print_exec_timer()
{
set_exec_time(1);
}
It really depends what you are going for, and specifically, what kind of performance you really need to offer.
I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.
In order of preference in the C# world,
From Wikipedia (emphasis and link added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
So, the real percent encoding uses %20
while form data in URLs is in a modified form that uses +
. So you're most likely to only see +
in URLs in the query string after an ?
.
if(!$('element').val()) {
// code
}
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".
While above approaches do not address the case for Mac OS X because Mac Os X does not support -readable
switch this is how you can avoid 'Permission denied' errors in your output. This might help someone.
find / -type f -name "your_pattern" 2>/dev/null
.
If you're using some other command with find
, for example, to find the size of files of certain pattern in a directory 2>/dev/null
would still work as shown below.
find . -type f -name "your_pattern" -exec du -ch {} + 2>/dev/null | grep total$
.
This will return the total size of the files of a given pattern. Note the 2>/dev/null
at the end of find command.
Actually, For me below works fine.
@Component
public class MyBean {
public static String prop;
@Value("${some.prop}")
public void setProp(String prop) {
this.prop= prop;
}
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Now whereever i want, just invoke
MyBean.prop
it will return value.
Here is the C++ implementation of Jon Skeets Answer. It might not be the most optimal way of implementing it, but it does exactly what it's supposed to.
class Stack {
private:
struct stack_node {
int val;
stack_node *next;
};
stack_node *top;
stack_node *min_top;
public:
Stack() {
top = nullptr;
min_top = nullptr;
}
void push(int num) {
stack_node *new_node = nullptr;
new_node = new stack_node;
new_node->val = num;
if (is_empty()) {
top = new_node;
new_node->next = nullptr;
min_top = new_node;
new_node->next = nullptr;
} else {
new_node->next = top;
top = new_node;
if (new_node->val <= min_top->val) {
new_node->next = min_top;
min_top = new_node;
}
}
}
void pop(int &num) {
stack_node *tmp_node = nullptr;
stack_node *min_tmp = nullptr;
if (is_empty()) {
std::cout << "It's empty\n";
} else {
num = top->val;
if (top->val == min_top->val) {
min_tmp = min_top->next;
delete min_top;
min_top = min_tmp;
}
tmp_node = top->next;
delete top;
top = tmp_node;
}
}
bool is_empty() const {
return !top;
}
void get_min(int &item) {
item = min_top->val;
}
};
And here is the driver for the class
int main() {
int pop, min_el;
Stack my_stack;
my_stack.push(4);
my_stack.push(6);
my_stack.push(88);
my_stack.push(1);
my_stack.push(234);
my_stack.push(2);
my_stack.get_min(min_el);
cout << "Min: " << min_el << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.get_min(min_el);
cout << "Min: " << min_el << endl;
return 0;
}
Output:
Min: 1
Popped stock element: 2
Popped stock element: 234
Popped stock element: 1
Min: 4
The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.
The menu location seems to have changed to:
Query Designer --> Pane --> SQL
Use np.multiply(a,b):
import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)
I made this "pure Swift" extension on UIDevice
.
This version works in Swift 2 or higher If you use an earlier version please use an older version of my answer.
If you are looking for a more elegant solution you can use my µ-framework DeviceKit
published on GitHub (also available via CocoaPods, Carthage and Swift Package Manager).
Here's the code:
import UIKit
public extension UIDevice {
static let modelName: String = {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity
#if os(iOS)
switch identifier {
case "iPod5,1": return "iPod touch (5th generation)"
case "iPod7,1": return "iPod touch (6th generation)"
case "iPod9,1": return "iPod touch (7th generation)"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE (2nd generation)"
case "iPhone13,1": return "iPhone 12 mini"
case "iPhone13,2": return "iPhone 12"
case "iPhone13,3": return "iPhone 12 Pro"
case "iPhone13,4": return "iPhone 12 Pro Max"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)"
case "iPad6,11", "iPad6,12": return "iPad (5th generation)"
case "iPad7,5", "iPad7,6": return "iPad (6th generation)"
case "iPad7,11", "iPad7,12": return "iPad (7th generation)"
case "iPad11,6", "iPad11,7": return "iPad (8th generation)"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad11,3", "iPad11,4": return "iPad Air (3rd generation)"
case "iPad13,1", "iPad13,2": return "iPad Air (4th generation)"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3"
case "iPad5,1", "iPad5,2": return "iPad mini 4"
case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)"
case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)"
case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch) (1st generation)"
case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)"
case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)"
case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)"
case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "AudioAccessory5,1": return "HomePod mini"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
default: return identifier
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return "Apple TV 4"
case "AppleTV6,2": return "Apple TV 4K"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
default: return identifier
}
#endif
}
return mapToDevice(identifier: identifier)
}()
}
You call it like this:
let modelName = UIDevice.modelName
For real devices it returns e.g. "iPad Pro 9.7 Inch", for simulators it returns "Simulator " + Simulator identifier, e.g. "Simulator iPad Pro 9.7 Inch"
There's an ELSE in the DOS batch language? Back in the days when I did more of this kinda thing, there wasn't.
If my theory is correct and your ELSE is being ignored, you may be better off doing
IF NOT EXIST file GOTO label
...which will also save you a line of code (the one right after your IF).
Second, I vaguely remember some kind of bug with testing for the existence of directories. Life would be easier if you could test for the existence of a file in that directory. If there's no file you can be sure of, something to try (this used to work up to Win95, IIRC) would be to append the device file name NUL
to your directory name, e.g.
IF NOT EXIST C:\dir\NUL GOTO ...
Answers above are shown how to remove an array and here is how to pull an object from an array.
Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/
db.survey.update( // select your doc in moongo
{ }, // your query, usually match by _id
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
{ multi: true } // set this to true if you want to remove multiple elements.
)
Using Eclipse IDE:-
This is all you need.
rsync -e ssh file host:/directory/.
You can use UNION All
clause to perform multiple insert in a table.
ex:
INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
<select>
<option selected="selected" class="Country">Country Name</option>
<option value="1">India</option>
<option value="2">us</option>
</select>
.country
{
display:none;
}
</style>
create a libs folder in the inside WEB-INF directory and add jstl, standard jars as below.
You could also print out the unique value in "file" using the cat
command by piping to sort
and uniq
cat file | sort | uniq -u
In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.
Well, one classic example is where you wanted to get a list of employees and their immediate managers:
select e.employee as employee, b.employee as boss
from emptable e, emptable b
where e.manager_id = b.empolyee_id
order by 1
It's basically used where there is any relationship between rows stored in the same table.
And so on...
I think this code will do what you want. It stores the first row as a set of headers, then stores the rest in a data object which you can write to disk as JSON.
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
var worksheet = workbook.Sheets[y];
var headers = {};
var data = [];
for(z in worksheet) {
if(z[0] === '!') continue;
//parse out the column, row, and value
var col = z.substring(0,1);
var row = parseInt(z.substring(1));
var value = worksheet[z].v;
//store header names
if(row == 1) {
headers[col] = value;
continue;
}
if(!data[row]) data[row]={};
data[row][headers[col]] = value;
}
//drop those first two rows which are empty
data.shift();
data.shift();
console.log(data);
});
prints out
[ { id: 1,
headline: 'team: sally pearson',
location: 'Australia',
'body text': 'majority have…',
media: 'http://www.youtube.com/foo' },
{ id: 2,
headline: 'Team: rebecca',
location: 'Brazil',
'body text': 'it is a long established…',
media: 'http://s2.image.foo/' } ]
src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"
worked for me for wordpress 3.6 i used it to get header logo using as
<img src="<?php bloginfo('template_url'); ?>/images/logo.jpg">
Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.
I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}
I know this has been answered a bunch of ways and this may not answer OP's specific question (with the list of criteria) but this is what I did for the most common use case and it's far simpler than the other responses:
answer = input('Please indicate approval: [y/n]')
if not answer or answer[0].lower() != 'y':
print('You did not indicate approval')
exit(1)
I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.
#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
Grep only solution which I tested with grep for windows:
grep -ro "pattern to find in files" "Directory to recursively search" | grep -c "pattern to find in files"
This solution will count all occurrences even if there are multiple on one line. -r
recursively searches the directory, -o
will "show only the part of a line matching PATTERN" -- this is what splits up multiple occurences on a single line and makes grep print each match on a new line; then pipe those newline-separated-results back into grep with -c
to count the number of occurrences using the same pattern.
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS.
I would name the images starting with bw_ and clr_ and just use JS to swap between them.
example:
$("#images").find('img').bind("click", function() {
var src = $(this).attr("src"),
state = (src.indexOf("bw_") === 0) ? 'bw' : 'clr';
(state === 'bw') ? src = src.replace('bw_','clr_') : src = src.replace('clr_','bw_');
$(this).attr("src", src);
});
link to fiddle: http://jsfiddle.net/felcom/J2ucD/
To open and read a text file line per line, you could use the following:
// define your file name
string file_name = "data.txt";
// attach an input stream to the wanted file
ifstream input_stream(file_name);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// file contents
vector<string> text;
// one line
string line;
// extract all the text from the input file
while (getline(input_stream, line)) {
// store each line in the vector
text.push_back(line);
}
To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read()
:
// define your file name
string file_name = "binary_data.bin";
// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// use function that explicitly specifies the amount of block memory read
int memory_size = 10;
// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];
// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);
When doing this you'll need to #include
the header : <iostream>
strtok modifies its input string. It places null characters ('\0') in it so that it will return bits of the original string as tokens. In fact strtok does not allocate memory. You may understand it better if you draw the string as a sequence of boxes.
This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:
<script src="http://somesite.net/js/somefile.js">
It did not have anything to do with JQuery.
You would probably see the same doing something like this:
var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);
But I haven't tested that idea.
As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean
(which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)
What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant)
form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.
Here are two solutions, I am using Oracle SQL server:
1) using over clause:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select id, uname
from (select a.id,
a.uname,
ROW_NUMBER() OVER(PARTITION BY a.id ORDER BY a.id) AS freq
from org_table a)
where freq = 1
2) Using sub-query:
with org_table as
(select 1 id, 'Ali' uname
from dual
union
select 1, 'June'
from dual
union
select 2, 'Jame'
from dual
union
select 2, 'July' from dual)
select a.id,
(select b.uname
from org_table b
where b.id = a.id
and rownum = 1)
from (select distinct id from org_table) a
You can easily pass it as an environment variable
docker run .. -e HOST_HOSTNAME=`hostname` ..
using
-e HOST_HOSTNAME=`hostname`
will call the hostname and use it's return as an environment variable called HOST_HOSTNAME
, of course you can customize the key as you like.
note that this works on bash shell, if you using a different shell you might need to see the alternative for "backtick", for example a fish
shell alternative would be
docker run .. -e HOST_HOSTNAME=(hostname) ..
First add action command on JButton or JTextField by:
JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");
Then add ActionListener to both JTextField and JButton.
JButton.addActionListener(listener);
JTextField.addActionListener(listener);
After that, On you ActionListener implementation write
@Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your actionCommand for press Enter"))
{
//Do something
}
}
Here are two more ways:
Please keep in mind that space is very important in Bash. So, if you want your command to run, use as is without introducing any more spaces.
The following assigns harshil
to L
and then prints it
L=$"harshil"
echo "$L"
The following assigns the output of the command tr
to L2. tr
is being operated on another variable, L1.
L2=$(echo "$L1" | tr [:upper:] [:lower:])
I also have the same problem, first I tried to restart redis-server by sudo service restart
but the problem still remained. Then I removed redis-server
by sudo apt-get purge redis-server
and install it again by sudo apt-get install redis-server
and then the redis was working again. It also worth to have a look at redis log which located in here /var/log/redis/redis-server.log
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
Obviously there is no "better" -- or more worth learning -- language at all. Which language you use is is just a matter of what you like AND what your server supports. You should not learn a language that wouldn't be supported by any server or is said to be dying in the near future. On the other hand it is obvious too that there will be even better languages in the future and that those will be more useful. So learn one that is fast, convenient and that you like and where learning it wouldn't be a too big effort because, as said, you're likely to change in less than 3 years.
I, personally would be considering an "open-source" (not proprietary) one, because the web is open to everyone and open-source is more likely to be supported by every-one. (Which means PHP in this case)
No need to use .each
. click
already binds to all div
occurrences.
$('div').click(function(e) {
..
});
Note: use hard binding such as .click
to make sure dynamically loaded elements don't get bound.
Here's another solution using df.transform
and df.set_index
:
>>> (df['teams']
.transform([lambda x:x[0], lambda x:x[1]])
.set_axis(['team1','team2'],
axis=1,
inplace=False)
)
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
I've created a simple example tutorial. You can read this and use in your application.
http://ribinsandroidhelper.blogspot.in/2013/03/qr-code-reading-on-your-application.html
Through this link you can download the qrcode library project and import into your workspace and add library to your project
and copy this code to your activity
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(this, contents,Toast.LENGTH_LONG).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
//Handle cancel
}
}
}
Saving to Hive is just a matter of using write()
method of your SQLContext:
df.write.saveAsTable(tableName)
From Spark 2.2: use DataSet instead DataFrame.
You want to define min-width
on row so when it browser is re-sized it does not go below that and wrap.
For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:
audio.mp3
for
http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
linking in a freely available mp3 off the web. Thank you for sharing the easy solution!
Try this:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto;
to the <table>
element.