I had this problem recently. I made these settings change. And it worked for me. !
Had a crack at it myself and this is what I came up with:
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
for (var i in d) {
if (d[i].is(o)) {
s.append(d[i]);
console.log(d[i]);
// TODO: remove option from data array
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
You can see the example at http://www.jsfiddle.net/g5YKh/
The option
elements are fully removed from the select
s and can be re-added again by jQuery selector.
Probably needs a bit of work and testing before it works well enough for all cases, but it's good enough for what I need.
Few more things I've come across:
When your sticky element is a component (angular etc)
If the 'sticky' element itself is a component with a custom element-selector, such as an angular component named <app-menu-bar>
you will need to add the following to the component's css:
:host { display: block; } // or use flexbox
or
app-menu-bar { display: block; } // (in the containing component's css)
Safari on iOS in particular seems to require `display:block` even on the root element `app-root` of an angular application or it won't stick.
If you are creating a component and defining the css inside the component (shadow DOM / encapsulated styles), make sure the position: sticky
is being applied to the 'outer' selector (eg. app-menu-bar
in devtools should show the sticky position) and not a top level div
within the component. With Angular, this can be achieved with the :host
selector in the css for your component.
:host
{
position: sticky;
display: block; // this is the same as shown above
top: 0;
background: red;
}
Other
If the element following your sticky element has a solid background, you must add the following to stop it from sliding underneath:
.sticky-element { z-index: 100; }
.parent-of-sticky-element { position: relative; }
Your sticky element must be before your content if using top
and after it if using bottom
.
There are complications when using overflow: hidden
on your wrapper element – in general it will kill the sticky element inside. Better explained in this question
Mobile browsers may disable sticky/fixed positioned items when the onscreen keyboard is visible. I'm not sure of the exact rules (does anybody ever know) but when the keyboard is visible you're looking at a sort of 'window' into the window and you won't easily be able to get things to stick to the actual visible top of the screen.
Make sure you have:
position: sticky;
and not
display: sticky;
Misc usability concerns
From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
This is what you need :)
The following code will return a JavaScript Object containing the URL parameters:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
For example, if you have the URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
This code will return:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
and you can do:
var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
You can start Eclipse in clean mode from the command line:
eclipse -clean
From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):
ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.
http://ora-06512.ora-code.com/:
ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.
impdp
exports the DDL of a dmp
backup to a file if you use the SQLFILE
parameter. For example, put this into a text file
impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
Then check ddl_dump.txt
for the tablespaces, users, and schemas in the backup.
According to the documentation, this does not actually modify the database:
The SQL is not actually executed, and the target system remains unchanged.
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
Optimization for emplace_back
can be demonstrated in next example.
For emplace_back
constructor A (int x_arg)
will be called. And for
push_back
A (int x_arg)
is called first and move A (A &&rhs)
is called afterwards.
Of course, the constructor has to be marked as explicit
, but for current example is good to remove explicitness.
#include <iostream>
#include <vector>
class A
{
public:
A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }
A () { x = 0; std::cout << "A ()\n"; }
A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }
A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }
private:
int x;
};
int main ()
{
{
std::vector<A> a;
std::cout << "call emplace_back:\n";
a.emplace_back (0);
}
{
std::vector<A> a;
std::cout << "call push_back:\n";
a.push_back (1);
}
return 0;
}
output:
call emplace_back:
A (x_arg)
call push_back:
A (x_arg)
A (A &&)
You could also solve this problem in following way:
$totalView = View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
->groupBy(DB::raw('Date(read_at)'))
->orderBy(DB::raw('Date(read_at)'))
->get();
Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.
Everyone wants to make this more complicated than it is. The crypt() function does most of the work.
function blowfishCrypt($password,$cost)
{
$chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
// $salt=sprintf('$2a$%02d$',$cost);
//Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
mt_srand();
for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
return crypt($password,$salt);
}
Example:
$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password
I know it should be obvious, but please don't use 'password' as your password.
Without using regex
, you can just do:
def get_num(x):
return int(''.join(ele for ele in x if ele.isdigit()))
Result:
>>> get_num(x)
120
>>> get_num(y)
90
>>> get_num(banana)
200
>>> get_num(orange)
300
EDIT :
Answering the follow up question.
If we know that the only period in a given string is the decimal point, extracting a float is quite easy:
def get_num(x):
return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))
Result:
>>> get_num('dfgd 45.678fjfjf')
45.678
simply you can do like this because when you initialized the form in contains form data and invalid data as well:
def some_func(request):
form = MyForm(request.POST)
if form.is_valid():
//other stuff
return render(request,template_name,{'form':form})
if will raise the error in the template if have any but the form data will still remain as :
I just installed the 32bit 11g R2 Express edition version on 64bit windows, created a new database and performed some queries. Seems to work like it should work! :-) I followed the following easy guide!
$scope.countDown = 30;
var timer;
$scope.countTimer = function () {
var time = $timeout(function () {
timer = setInterval(function () {
if ($scope.countDown > 0) {
$scope.countDown--;
} else {
clearInterval(timer);
$window.location.href = '/Logoff';
}
$scope.$apply();
}, 1000);
}, 0);
}
$scope.stop= function () {
clearInterval(timer);
}
IN HTML:
<button type="submit" ng-click="countTimer()">Start</button>
<button type="submit" ng-click="stop()">Clear</button>
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
There are two possible reasons for that error:
try to put your jquery code in document.ready, like this:
$(document).ready(function(){
....your code....
});
cheers
As an starting point, it will be good to create a recursive descent parser (RDP) (let's say you want to create your own flavour of BASIC and build a BASIC interpreter) to understand how to write a compiler. I found the best information in Herbert Schild's C Power Users, chapter 7. This chapter refers to another book of H. Schildt "C The complete Reference" where he explains how to create a calculator (a simple expression parser). I found both books on eBay very cheap. You can check the code for the book if you go to www.osborne.com or check in www.HerbSchildt.com I found the same code but for C# in his latest book
I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.
Suppose you have added iframe in "abc.com/page" web page
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
Next you have to bind windows "message" event under web page "abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message:
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
window.addEventListener('message', function (event) {
// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
You can try the keyword use
in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
#wrapper
{
min-width:960px;
margin-left:auto;
margin-right:auto;
position-relative;
}
#left
{
width:200px;
position: absolute;
background-color:antiquewhite;
margin-left:10px;
z-index: 2;
}
#content
{
padding-left:210px;
width:100%;
background-color:AppWorkspace;
position: relative;
z-index: 1;
}
If you need the whitespace on the right of #left
, then add a border-right: 10px solid #FFF;
to #left
and add 10px
to the padding-left
in #content
string uriPath =
"file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;
Please see below for a modest improvement on @Sled's code shown above, that turn-back-on method was missing one line, now it passes my tests. This disables HTTPS certificate and hostname spoofing when using RestTemplate in a Spring-Boot version 2 application that uses the default HTTP configuration, NOT configured to use Apache HTTP Client.
package org.my.little.spring-boot-v2.app;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Disables and enables certificate and host-name checking in
* HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
* Has no effect on implementations such as Apache Http Client, Ok Http.
*/
public final class SSLUtils {
private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
};
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
// Return it to the initial state (discovered by reflection, now hardcoded)
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, null, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
private SSLUtils() {
throw new UnsupportedOperationException("Do not instantiate libraries.");
}
}
The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)
To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:
var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);
Using writing-mode
and transform
.
.rotate {
writing-mode: vertical-lr;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
}
<span class="rotate">Hello</span>
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session
used by the EntityManager
. With JPA 1.0, you'll have to do something like this:
Session session = (Session)em.getDelegate();
Connection conn = session.connection();
Note that the getDelegate()
is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().
In JPA 2.0, things are a bit better and you can do the following:
Connection conn = em.unwrap(Session.class).connection();
If you are running inside a container, you could also perform a lookup on the configured DataSource
.
Not very pretty but here is another way:
String runFct =
queryType.equals("eq") ? "method1":
queryType.equals("L_L")? "method2":
queryType.equals("L_R")? "method3":
queryType.equals("L_LR")? "method4":
"method5";
Method m = this.getClass().getMethod(runFct);
m.invoke(this);
Login Page design using SwiftUI
import SwiftUI
struct ContentView: View {
@State var email: String = "[email protected]"
@State var password: String = ""
@State static var labelTitle: String = ""
var body: some View {
VStack(alignment: .center){
//Label
Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
//TextField
TextField("Email", text: $email)
.textContentType(.emailAddress)
.foregroundColor(.blue)
.frame(minHeight: 40)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
TextField("Password", text: $password) //Placeholder
.textContentType(.newPassword)
.frame(minHeight: 40)
.foregroundColor(.blue) // Text color
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
//Button
Button(action: {
}) {
HStack {
Image(uiImage: UIImage(named: "Login")!)
.renderingMode(.original)
.font(.title)
.foregroundColor(.blue)
Text("Login")
.font(.title)
.foregroundColor(.white)
}
.font(.headline)
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.padding(.horizontal, 20)
.frame(width: 200, height: 50, alignment: .center)
}
Spacer()
}.padding(10)
.frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
.background(Color.gray)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can use this for getting current and log times:
#!/bin/bash
log="log_file_name"
while read line
do
current_hours=`date | awk 'BEGIN{FS="[ :]+"}; {print $4}'`
current_minutes=`date | awk 'BEGIN{FS="[ :]+"}; {print $5}'`
current_seconds=`date | awk 'BEGIN{FS="[ :]+"}; {print $6}'`
log_file_hours=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $7}'`
log_file_minutes=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $8}'`
log_file_seconds=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $9}'`
done < $log
And compare log_file_*
and current_*
variables.
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
Sorry to bump an old question but the answer is to count the character length of the cell and not its value.
CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If
hope that helps. Cheers
I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.
select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];
Consistency is what everyone strongly suggest, the rest is upto you as long as it works.
For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.
foo
foobar
or foo_bar
is great.
We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration
to student_registration
like @Zbyszek says, having a simple id
is more than enough for the auto-increment. The simplier the better. Why do you need foo_id
? We had the same problem early on, we named all our columns with the table prefix. like foo_id
, foo_name
, foo_age
. We dropped the tablename now and kept only the col as short as possible.
Since we are using just an id for PK we will be using foo_bar_fk
(tablename is unique, folowed by the unique PK, followed by the _fk
) as foreign key. We don't add id
to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk
at the end.
For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk
(for username_fk col). It's just a way we are following. We keep a documentation for every names structures.
When keeping the col name short, we should also keep an eye on the RESTRICTED names.
+------------------------------------+
| foobar |
+------------------------------------+
| id (PK for the current table) |
| username_fk (PK of username table) |
| location (other column) |
| tel (other column) |
+------------------------------------+
Create a toolbar in your xml...toolbar.xml:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
</android.support.v7.widget.Toolbar>
Then add the following in your toolbar.xml:
app:titleTextColor="@color/colorText"
app:title="@string/app_name">
Remeber @color/colorText is simply your color.xml file with the color attribute named colorText and your color.This is the best way to calll your strings rather than hardcoding your color inside your toolbar.xml. You also have other options to modify your text,such as:textAppearance...etc...just type app:text...and intelisense will give you options in android studio.
your final toolbar should look like this:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/Theme.AppCompat"
app:subtitleTextAppearance="@drawable/icon"
app:title="@string/app_name">
</android.support.v7.widget.Toolbar>
NB:This toolbar should be inside your activity_main.xml.Easy Peasie
Another option is to do it all in your class:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);
Good Luck
Bootstrap 4+ has made changes to the utility classes for this. From the documentation:
Added
.float-{sm,md,lg,xl}-{left,right,none}
classes for responsive floats and removed.pull-left
and.pull-right
since they’re redundant to.float-left
and.float-right
.
So use the .float-right
(or a size equivalent such as .float-lg-right
) instead of .pull-right
for your right alignment if you're using a newer Bootstrap version.
Just wanted to add that if you want to add several parameters with the same key name for example: www.test.com/home?id=1&id=2
let params = new HttpParams();
params = params.append(key, value);
Use append, if you use set, it will overwrite the previous value with the same key name.
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
as simple as:
tmpHM.each{ key, value ->
doSomethingWithKeyAndValue key, value
}
The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"
So you could take a substring starting at the colon with something like this:
String selector = divA.toString().substring(s.indexOf(":") + 2);
With this, you could find your element inside your other element with this:
WebElement input = driver.findElement( By.xpath( selector + "//input" ) );
Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.
Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> </a>';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>
The listen socket on a server can use linger with time 0 to have access to binding back to the socket immediately and to reset any clients whose connections are not yet finished connecting. TIME_WAIT is something that is only interesting when you have a multi-path network and can end up with miss-ordered packets or otherwise are dealing with odd network packet ordering/arrival-timing.
Put this in /etc/init
(Use /etc/systemd
in Ubuntu 15.x)
mystartupscript.conf
start on runlevel [2345]
stop on runlevel [!2345]
exec /path/to/script.py
By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.
manual starting/stopping is done with
sudo service mystartupscript start
and
sudo service mystartupscript stop
In MySQL you can do this:
SELECT `PRIMARY_KEY`, rand() FROM table ORDER BY rand() LIMIT 5000;
Turns out you can download a MS version of this header from:
https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h
A portable one can be found here:
http://www.azillionmonkeys.com/qed/pstdint.h
Thanks to the Software Ramblings blog.
You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.
You can wait for a file to be ready by using this function in a loop.
For me such issue occur when I had multiple export
statements in single .ts
file...
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
You can use this program instead of sprintf.
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = '\0';
strrev(buffer);
}
%
(any host) (see manual for details)The current problem is the first one, but right after you resolve it you will likely get the second one.
This is a more common error now as many projects are moving their master
branch to another name like main
, primary
, default
, root
, reference
, latest
, etc, as discussed at Github plans to replace racially insensitive terms like ‘master’ and ‘whitelist’.
To fix it, first find out what the project is now using, which you can find via their github, gitlab or other git server.
Then do this to capture the current configuration:
$ git branch -vv
...
* master 968695b [origin/master] Track which contest a ballot was sampled for (#629)
...
Find the line describing the master
branch, and note whether the remote repo is called origin
, upstream
or whatever.
Then using that information, change the branch name to the new one, e.g. if it says you're currently tracking origin/master
, substitute main
:
git branch master --set-upstream-to origin/main
You can also rename your own branch to avoid future confusion:
git branch -m main
There are two ways to delete a stash:
$ git stash drop <stash_id>
. $ git stash clear
.Use both of them with caution, it maybe is difficult to revert the once deleted stashes.
Here is the reference article.
With an already accepted answer present, I think this is a better answer to the question on how to handle this on the inventory level. I consider this more secure by isolating this insecure setting to the hosts required for this (e.g. test systems, local development machines).
What you can do at the inventory level is add
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
or
ansible_ssh_extra_args='-o StrictHostKeyChecking=no'
to your host definition (see Ansible Behavioral Inventory Parameters).
This will work provided you use the ssh
connection type, not paramiko
or something else).
For example, a Vagrant host definition would look like…
vagrant ansible_port=2222 ansible_host=127.0.0.1 ansible_ssh_common_args='-o StrictHostKeyChecking=no'
or
vagrant ansible_port=2222 ansible_host=127.0.0.1 ansible_ssh_extra_args='-o StrictHostKeyChecking=no'
Running Ansible will then be successful without changing any environment variable.
$ ansible vagrant -i <path/to/hosts/file> -m ping
vagrant | SUCCESS => {
"changed": false,
"ping": "pong"
}
In case you want to do this for a group of hosts, here's a suggestion to make it a supplemental group var for an existing group like this:
[mytestsystems]
test[01:99].example.tld
[insecuressh:children]
mytestsystems
[insecuressh:vars]
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
The Directory is not set correctly so Please follow these steps.
In the "Variable value" box, Make sure you see following:
;c:\python27\;c:\python27\scripts
Click "OK", Test this change by restarting your windows powershell. Type
python
Now python version 2 runs! yay!
May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML
<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>
using System;
using System.ComponentModel;
using System.Threading;
namespace BackGroundWorkerExample
{
class Program
{
private static BackgroundWorker backgroundWorker;
static void Main(string[] args)
{
backgroundWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
backgroundWorker.DoWork += backgroundWorker_DoWork;
//For the display of operation progress to UI.
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
//After the completation of operation.
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");
Console.ReadLine();
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
Console.ReadLine();
}
}
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 200; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
backgroundWorker.ReportProgress(i);
Thread.Sleep(1000);
e.Result = 1000;
}
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}
static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("Operation Cancelled");
}
else if (e.Error != null)
{
Console.WriteLine("Error in Process :" + e.Error);
}
else
{
Console.WriteLine("Operation Completed :" + e.Result);
}
}
}
}
Also, referr the below link you will understand the concepts of Background
:
http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/
Use the range's NumberFormat
property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.
As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).
Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
And then use this in your code via:
WriteLine("{0}", DateTimeUtils.Tomorrow)
file1=/tmp/main.one.two.sh
t=$(basename "$file1") # output is main.one.two.sh
name=$(echo "$file1" | sed -e 's/\.[^.]*$//') # output is /tmp/main.one.two
name=$(echo "$t" | sed -e 's/\.[^.]*$//') # output is main.one.two
use whichever you want. Here I assume that last .
(dot) followed by text is extension.
If the IBM mainframe JCL has some extra characters or numbers at the end of the name of unix script being called then it can throw such error.
You have here available an example of DNS Caching in Debian using dnsmasq.
Configuration summary:
# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"
# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888
nameserver 127.0.0.1
Then just restart dnsmasq.
Benchmark test using DNS 1.1.1.1:
for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Benchmark test using you local cached DNS:
for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.
And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.
Personally, I would print them to a file using Perl or Python in the format
<COL_NAME>: <COL_VAL>
for each row so that the file has as many lines as there are columns. Then I'd do a diff
between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines
I reproduced this error message in the following three cases:
The obvious solution is to create new database user with the same username and password as in the spring-boot app or change username and password in your spring-boot app files to match an existing database user and grant sufficient privileges to that database user. In case of MySQL database this can be done as shown below:
mysql -u root -p
>CREATE USER 'theuser'@'localhost' IDENTIFIED BY 'thepassword';
>GRANT ALL ON *.* to theuser@localhost IDENTIFIED BY 'thepassword';
>FLUSH PRIVILEGES;
Obviously there are similar commands in Postgresql but I haven't tested if in case of Postgresql this error message can be reproduced in these three cases.
The only working solution I found was this one that uses reflection
/**
* Get external sd card path using reflection
* @param mContext
* @param is_removable is external storage removable
* @return
*/
private static String getExternalStoragePath(Context mContext, boolean is_removable) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removable == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Just a quick addition, because I tackled the same issue today:
With Go 1.13 it is possible to use the new isZero()
method:
if reflect.ValueOf(session).IsZero() {
// do stuff...
}
I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual()
.
But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles
Vue.set(object, prop, value)
For vuex you will want to do Vue.set(state.object, key, value)
So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val)
in favor of this.$set(this.items, index, val)
.
Splice is still available and here is a link to array mutation methods available in vue link.
DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}
add to your using clause :
using System.Linq;
and add :
System.Data.DataSetExtensions
to references.
You can use a transparent poster image in combination with a CSS background image to achieve this (example); however, to have a background stretched to the height and the width of a video, you'll have to use an absolutely positioned <img>
tag (example).
It is also possible to set background-size
to 100% 100%
in browsers that support background-size
(example).
A better way to do this would be to use the object-fit
CSS property as @Lars Ericsson suggests.
Use
object-fit: cover;
if you don't want to display those parts of the image that don't fit the video's aspect ratio, and
object-fit: fill;
to stretch the image to fit your video's aspect ratio
Hopefully I'm understanding your question correctly in that you are wondering about the differences between dispatch_async and dispatch_sync?
dispatch_async
will dispatch the block to a queue asynchronously. Meaning it will send the block to the queue and not wait for it to return before continuing on the execution of the remaining code in your method.
dispatch_sync
will dispatch the block to a queue synchronously. This will prevent any more execution of remaining code in the method until the block has finished executing.
I've mostly used a dispatch_async
to a background queue to get work off the main queue and take advantage of any extra cores that the device may have. Then dispatch_async
to the main thread if I need to update the UI.
Good luck
People will offer you obfuscators, but no amount of obfuscation can prevent someone from getting at your code. None. If your computer can run it, or in the case of movies and music if it can play it, the user can get at it. Even compiling it to machine code just makes the job a little more difficult. If you use an obfuscator, you are just fooling yourself. Worse, you're also disallowing your users from fixing bugs or making modifications.
Music and movie companies haven't quite come to terms with this yet, they still spend millions on DRM.
In interpreted languages like PHP and Perl it's trivial. Perl used to have lots of code obfuscators, then we realized you can trivially decompile them.
perl -MO=Deparse some_program
PHP has things like DeZender and Show My Code.
My advice? Write a license and get a lawyer. The only other option is to not give out the code and instead run a hosted service.
See also the perlfaq entry on the subject.
Simple, here replace the "APP" by name of the app you want to launch.
export APP_HOME=/Applications/APP.app/Contents/MacOS
export PATH=$PATH:$APP_HOME
Thanks me later.
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
even shorter if you can lose the yearStart value:
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
while(yearStart < yearEnd+1){
arr.push(yearStart++);
}
UPDATE: If you can use the ES6 syntax you can do it the way proposed here:
let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
.fill()
.map(() => yearStart++);
The top answers are correct, but deeply technical. For those newer to Ruby:
require_relative
will most likely be used to bring in code from another file that you wrote. for example, what if you have data in ~/my-project/data.rb
and you want to include that in ~/my-project/solution.rb
? in solution.rb
you would add require_relative 'data'
.
it is important to note these files do not need to be in the same directory. require_relative '../../folder1/folder2/data'
is also valid.
require
will most likely be used to bring in code from a library someone else wrote.for example, what if you want to use one of the helper functions provided in the active_support
library? you'll need to install the gem with gem install activesupport
and then in the file require 'active_support'
.
require 'active_support/all'
"FooBar".underscore
Said differently--
require_relative
requires a file specifically pointed to relative to the file that calls it.
require
requires a file included in the $LOAD_PATH
.
The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .
I noticed no one mentioned the use of regular expressions when using find
/findstr
-based Answers. That can be problematic for similarly named services.
Lets say you have two services, CDPUserSvc
and CDPUserSvc_54530
If you use most of the find
/findstr
-based Answers here so far, you'll get false-positives for CDPUserSvc
queries when only CDPUserSvc_54530
is running.
The /r
and /c
switches for findstr
can help us handle that use-case, as well as the special character that indicates the end of the line, $
This query will only verify the running of the CDPUserSvc
service and ignore CDPUserSvc_54530
sc query|findstr /r /c:"CDPUserSvc$"
new Double(99.9999).intValue()
Similar error with Glassfish 4.0 and several JDK installed:
SEVERE: GlassFish requires JDK 7, you are using JDK version 6.
There is no AS_JAVA reference in "C:\glassfish\config\asenv.bat" by default. After adding manually
set AS_JAVA=C:\Program Files\Java\jdk1.7.0_25
it works.
By using all() method we can select particular columns from table like as shown below.
ModelName::all('column1', 'column2', 'column3');
Note: Laravel 5.4
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
You can use the re.sub() function to remove these characters:
>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'
re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)
"[^a-zA-Z]+"
- look for any group of characters that are NOT
a-zA-z.""
- Replace the matched characters with ""Yout can try this below.
<style name="MyToolbar" parent="Widget.AppCompat.Toolbar">
<!-- your code here -->
</style>
And the detail elements you can find them in https://developer.android.com/reference/android/support/v7/appcompat/R.styleable.html#Toolbar
Here are some more:TextAppearance.Widget.AppCompat.Toolbar.Title
, TextAppearance.Widget.AppCompat.Toolbar.Subtitle
, Widget.AppCompat.Toolbar.Button.Navigation
.
Hope this can help you.
Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)
You can't set the size of your background image with the current version of CSS (2.1).
You can only set: position
, fix
, image-url
, repeat-mode
, and color
.
This function does what you want, and performs a lot faster than the option suggested in the accepted answer :
var repeat = function(str, count) {
var array = [];
for(var i = 0; i <= count;)
array[i++] = str;
return array.join('');
}
You use it like this :
var repeatedCharacter = repeat("a", 10);
To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.
In modern browsers, you can now also do this :
var repeatedCharacter = "a".repeat(10) };
This option is even faster. However, unfortunately it doesn't work in any version of Internet explorer.
The numbers in the table specify the first browser version that fully supports the method :
Install Tkinter
. I've included the win32api for as a Windows-only solution.
#!/usr/bin/env python
"""Get the current mouse position."""
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
def get_mouse_position():
"""
Get the current position of the mouse.
Returns
-------
dict :
With keys 'x' and 'y'
"""
mouse_position = None
import sys
if sys.platform in ['linux', 'linux2']:
pass
elif sys.platform == 'Windows':
try:
import win32api
except ImportError:
logging.info("win32api not installed")
win32api = None
if win32api is not None:
x, y = win32api.GetCursorPos()
mouse_position = {'x': x, 'y': y}
elif sys.platform == 'Mac':
pass
else:
try:
import Tkinter # Tkinter could be supported by all systems
except ImportError:
logging.info("Tkinter not installed")
Tkinter = None
if Tkinter is not None:
p = Tkinter.Tk()
x, y = p.winfo_pointerxy()
mouse_position = {'x': x, 'y': y}
print("sys.platform={platform} is unknown. Please report."
.format(platform=sys.platform))
print(sys.version)
return mouse_position
print(get_mouse_position())
Use sort.
You just have to do this:
All elements in the list must implement the Comparable interface.
(Or use the version below it, as others already said.)
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
Here's my take on this. It handles the edge cases and takes an optional parameter to remove empty entries from the results.
bool endsWith(const std::string& s, const std::string& suffix)
{
return s.size() >= suffix.size() &&
s.substr(s.size() - suffix.size()) == suffix;
}
std::vector<std::string> split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries = false)
{
std::vector<std::string> tokens;
for (size_t start = 0, end; start < s.length(); start = end + delimiter.length())
{
size_t position = s.find(delimiter, start);
end = position != string::npos ? position : s.length();
std::string token = s.substr(start, end - start);
if (!removeEmptyEntries || !token.empty())
{
tokens.push_back(token);
}
}
if (!removeEmptyEntries &&
(s.empty() || endsWith(s, delimiter)))
{
tokens.push_back("");
}
return tokens;
}
Examples
split("a-b-c", "-"); // [3]("a","b","c")
split("a--c", "-"); // [3]("a","","c")
split("-b-", "-"); // [3]("","b","")
split("--c--", "-"); // [5]("","","c","","")
split("--c--", "-", true); // [1]("c")
split("a", "-"); // [1]("a")
split("", "-"); // [1]("")
split("", "-", true); // [0]()
If navigating to another page . Navigator.pushReplacement()
can be used. It can be used If you're navigating from login to home screen. Or you can use .
AppBar(automaticallyImplyLeading: false)
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.
TLDR: Use background-size: 100% 100%;
.
background-size: cover;
may cut off some parts of the image producing poor results.
Using background-size: 100% 100%;
you force the image to take up 100%
of the parent element for both height
and width
.
See W3Schools for more information on this.
Here is a working, responsive jumbotron
background image:
<div class="jumbotron" style="background-image: url(http://yourImageUrl.jpg); background-size: 100% 100%;">
<h1>Welcome</h1>
<p class="lead">Your message here</p>
<p><a href="http://www.YourLinkHere.com" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
As other answers have mentioned, pprint
is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.
Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found
.
For more complex objects, make sure the class has a __repr__
method that prints the property information you want:
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __repr__(self):
return "Foo - (%r)" % self.bar
And then when you want to print the output, simply map your list to the str
function like this:
l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))
outputs:
[Foo - (10),
Foo - (20),
Foo - ('A string'),
Foo - (2.4)]
You can also do things like override the __repr__
method of list
to get a form of nested pretty printing:
class my_list(list):
def __repr__(self):
return "[%s]" % ",\n ".join(map(str, self))
a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a
gives
[first,
2,
[another,
list,
here],
last]
Unfortunately no second-level indentation but for a quick debug it can be useful.
You can use another console method:
let name = prompt("what is your name?");
console.log(`story ${name} story`);
In my case my request object inherited from base object. Without knowingly I added a property with int? in my request object and my base object also has same property ( same name ) with int datatype. I noticed this and deleted the property which I added in request object and after that it worked fine.
I would try to make @ErichBSchulz's answer simpler for beginners:
Change this line
double *ptr = malloc(sizeof(double *) * TIME);
to
double *ptr = malloc(sizeof(double) * TIME);
While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...
Ex:
//in xml
android:onClick="onButtonClicked"
// in java file
public void onButtonClicked(View v)
{
//your code here
}
Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v
and \h
, as well as the generic whitespace character class \s
The cleanest solution is to use the horizontal whitespace character class \h
. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters
U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)
U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE
The vertical space pattern \v
is less useful, but matches these characters
U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
There are seven vertical whitespace characters which match \v
and eighteen horizontal ones which match \h
. \s
matches twenty-three characters
All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h
also matches U+00A0 NO-BREAK SPACE, and \v
also matches U+0085 NEXT LINE, neither of which are matched by \s
I was also facing same issue, It resolved in 2 min for me i just white list ip through cpanel
Suppose you are trying to connect database of server B from server A. Go to Server B Cpanel->Remote MySQL-> enter Server A IP Address and That's it.
You can use java.security.MessageDigest
with SHA
as your algorithm choice.
For reference,
This gets routes registered directly on the app (via app.VERB) and routes that are registered as router middleware (via app.use). Express 4.11.0
//////////////
app.get("/foo", function(req,res){
res.send('foo');
});
//////////////
var router = express.Router();
router.get("/bar", function(req,res,next){
res.send('bar');
});
app.use("/",router);
//////////////
var route, routes = [];
app._router.stack.forEach(function(middleware){
if(middleware.route){ // routes registered directly on the app
routes.push(middleware.route);
} else if(middleware.name === 'router'){ // router middleware
middleware.handle.stack.forEach(function(handler){
route = handler.route;
route && routes.push(route);
});
}
});
// routes:
// {path: "/foo", methods: {get: true}}
// {path: "/bar", methods: {get: true}}
You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.
To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.
COPY ./files/. /files/
Try this :
Set the width of the form as 20% by:
width : 20%;
now if the entire canvas is 100 %, the centre is at 50%. So to align the centre of the form at the centre, 50-(20/2) = 40.
therefore set your left margin as 40% by doing this :
left : 40%;
Found this on HTML table: keep the same width for columns
If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .
It may sometime arises when MySQL service does not shut down properly during the OS reboot. The /var/lib/mysql/mysql.sock has been left. This prevents 'mysqld' from starting up.
These steps may help:
1: service mysqld start killall -9 mysqld_safe mysqld service mysqld start
2: rm /var/lib/mysql/mysql.sock service mysqld start
my problem is solved by this step
Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height
rule, some won't.
You can try line-height
(may need display:block;
or display:inline-block;
) or top
and bottom padding
also. If none of those work, that's pretty much it - use a graphic, position the input
in the center and set border:none;
so it looks like the form control is big but it actually isn't...
<select id="message_tag">
<optgroup>
<option>
....
....
</option>
</optgroup>
here i just removed bootstrap css for only "select" element. using following css code.
#message_tag_chzn{
display: none;
}
#message_tag{
display: inline !important;
}
The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.
If it's important you really need to benchmark both options!
Having said that, I have always used the exception method, the reasoning being it's better to only hit the database once.
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
Assuming you've got access to a standard Unix shell and/or cygwin environment:
tr -s ' ' '\n' < yourfile | sort | uniq -d -c
^--space char
Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Initializing a simple array :
<?php $array1=array(10,20,30,40,50); ?>
Initializing array within array :
<?php $array2=array(6,"santosh","rahul",array("x","y","z")); ?>
Source : Sorce for the code
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
LatLng hello = new LatLng(X, Y); // whereX & Y are coordinates
Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.university); // where university is the icon name that is used as a marker.
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));
SimpleORM, because it is straight-forward and no-magic. It defines all meta data structures in Java code and is very flexible.
SimpleORM provides similar functionality to Hibernate by mapping data in a relational database to Java objects in memory. Queries can be specified in terms of Java objects, object identity is aligned with database keys, relationships between objects are maintained and modified objects are automatically flushed to the database with optimistic locks.
But unlike Hibernate, SimpleORM uses a very simple object structure and architecture that avoids the need for complex parsing, byte code processing etc. SimpleORM is small and transparent, packaged in two jars of just 79K and 52K in size, with only one small and optional dependency (Slf4j). (Hibernate is over 2400K plus about 2000K of dependent Jars.) This makes SimpleORM easy to understand and so greatly reduces technical risk.
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
http://www.gnu.org/software/hello/manual/libc/Variable-Arguments-Output.html gives the following example to print to stderr. You can modify it to use your log function instead:
#include <stdio.h>
#include <stdarg.h>
void
eprintf (const char *template, ...)
{
va_list ap;
extern char *program_invocation_short_name;
fprintf (stderr, "%s: ", program_invocation_short_name);
va_start (ap, template);
vfprintf (stderr, template, ap);
va_end (ap);
}
Instead of vfprintf you will need to use vsprintf where you need to provide an adequate buffer to print into.
Quickest solution-
The best way is to create a virtual env. first and then do pip install , everything will work fine
YOu can also rewrite it like this
FROM Resource r WHERE r.ResourceNo IN
(
SELECT m.ResourceNo FROM JobMember m
JOIN Job j ON j.JobNo = m.JobNo
WHERE j.ProjectManagerNo = @UserResourceNo
OR
j.AlternateProjectManagerNo = @UserResourceNo
Union All
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
Also a return table is expected in your RETURN statement
float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.
double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.
Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.
The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.
https://deis.com/blog/2016/connecting-docker-containers-1/
The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.
Example:
you named the db container db1
and the webserver container web0
. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.
So if you have a web config file for your app, then for DB host you will use the name db1
.
if you are using an older version of docker, then you should use --link.
Example:
Step 1: docker run --name db1 oracle/database:12.1.0.2-ee
then when you start the web app. use:
Step 2: docker run --name web0 --link db1 webapp/webapp:3.0
and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.
I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites
an example setup is like this:
file name is base.yml
version: "2"
services:
webserver:
image: "moodlehq/moodle-php-apache:7.1
depends_on:
- db
volumes:
- "/var/www/html:/var/www/html"
- "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
environment:
MOODLE_DOCKER_DBTYPE: pgsql
MOODLE_DOCKER_DBNAME: moodle
MOODLE_DOCKER_DBUSER: moodle
MOODLE_DOCKER_DBPASS: "m@0dl3ing"
HTTP_PROXY: "${HTTP_PROXY}"
HTTPS_PROXY: "${HTTPS_PROXY}"
NO_PROXY: "${NO_PROXY}"
db:
image: postgres:9
environment:
POSTGRES_USER: moodle
POSTGRES_PASSWORD: "m@0dl3ing"
POSTGRES_DB: moodle
HTTP_PROXY: "${HTTP_PROXY}"
HTTPS_PROXY: "${HTTPS_PROXY}"
NO_PROXY: "${NO_PROXY}"
this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.
IE docker-compose --name setup1 up base.yml
NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down
this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.
Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command
best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.
Example:
db.yml
version: "2"
services:
webserver:
environment:
MOODLE_DOCKER_DBTYPE: oci
MOODLE_DOCKER_DBNAME: XE
db:
image: moodlehq/moodle-db-oracle
Then call docker-compose --name setup1 up base.yml db.yml
This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.
I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.
NOTE: I did not use the --port
command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.
UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.
Example:
docker network create test_network
The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network
switch operator.
Example:
docker run \
--detach \
--name db1 \
--network test_network \
-e MYSQL_ROOT_PASSWORD="${DBPASS}" \
-e MYSQL_DATABASE="${DBNAME}" \
-e MYSQL_USER="${DBUSER}" \
-e MYSQL_PASSWORD="${DBPASS}" \
--tmpfs /var/lib/mysql:rw \
mysql:5
Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1
. You just have to make sure all containers are connected to the same network, and you are good to go.
For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh
Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:
<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:
var context = new Entity("EntityV2");
Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.
Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).
// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);
How about something like this:
Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection =
string.Format(
"metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
contextType.Name,
innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities;
... with the following in your machine.config:
<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
This way, you can use a single connection string for every context in every project on the machine.
This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.
public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
{
var settings = new XmlWriterSettings
{
Indent = true
};
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement(keyFather);
foreach (var objeto in anyObject)
{
writer.WriteStartElement(keySon);
foreach (PropertyDescriptor item in props)
{
writer.WriteStartElement(item.DisplayName);
writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteFullEndElement();
writer.WriteEndDocument();
writer.Flush();
return builder.ToString();
}
}
I had the same error, as Bombe said I had no local branch named master in my config, although git branch
did list a branch named master...
To fix it just add this to your .git/config
[branch "master"]
remote = origin
merge = refs/heads/master
Kinda hacky but does the job
You're looking for absolute value, mate. Math.abs(-5)
returns 5...
Maybe useful Andround Unused Resources is a Java application that will scan your project for unused resources. Unused resources needlessly take up space, increase the build time, and clutter the IDE's autocomplete list.
To use it, ensure your working directory is the root of your Android project, and run:
java -jar AndroidUnusedResources.jar
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
def nested1(num1):
print "nested1 has",num1
def nested2(num2):
print "nested2 has",num2,"and it can reach to",num1
return num1+num2 #num1 referenced for reading here
return nested2
Gives:
In [17]: my_func=nested1(8)
nested1 has 8
In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13
This is an example of what a closure is and how it can be used.
Since Bootstrap 3 doesn't have a style for checkboxes I found a custom made that goes really well with Bootstrap style.
.checkbox label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="">_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked checkbox -->_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled checkbox -->_x000D_
<div class="checkbox disabled">_x000D_
<label>_x000D_
<input type="checkbox" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 13%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option one_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked radio -->_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option two is checked by default_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled radio -->_x000D_
<div class="radio disabled">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" disabled>_x000D_
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
Option three is disabled_x000D_
</label>_x000D_
</div>
_x000D_
You can choose your own icon between the ones from Bootstrap or Font Awesome by changing [icon name]
with your icon.
<span class="cr"><i class="cr-icon [icon name]"></i>
For example:
glyphicon glyphicon-remove
for Bootstrap, orfa fa-bullseye
for Font Awesome.checkbox label:after,_x000D_
.radio label:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
border: 1px solid #a9a9a9;_x000D_
border-radius: .25em;_x000D_
width: 1.3em;_x000D_
height: 1.3em;_x000D_
float: left;_x000D_
margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
position: absolute;_x000D_
font-size: .8em;_x000D_
line-height: 0;_x000D_
top: 50%;_x000D_
left: 15%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<div class="checkbox">_x000D_
<label>_x000D_
<input type="checkbox" value="" checked>_x000D_
<span class="cr"><i class="cr-icon glyphicon glyphicon-remove"></i></span>_x000D_
Bootstrap - Custom icon checkbox_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="" checked>_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio checked by default_x000D_
</label>_x000D_
</div>_x000D_
<div class="radio">_x000D_
<label>_x000D_
<input type="radio" name="o3" value="">_x000D_
<span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
Font Awesome - Custom icon radio_x000D_
</label>_x000D_
</div>
_x000D_
Made an app with two labels in IB and the following:
@IBOutlet var label1: UILabel!
@IBOutlet var label2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label1.textColor = UIColor.redColor() // in Swift 3 it's UIColor.red
label2.textColor = label1.textColor
}
label2 color changed as expected, so your line works. Try println(otherLabel.textColor)
right before you set myLabel.textColor to see if the color's what you expect.
If the body of the arrow function is wrapped in curly braces, it is not implicitly returned. Wrap the object in parentheses. It would look something like this.
p => ({ foo: 'bar' })
By wrapping the body in parens, the function will return { foo: 'bar }
.
Hopefully, that solves your problem. If not, I recently wrote an article about Arrow functions which covers it in more detail. I hope you find it useful. Javascript Arrow Functions
Create a new C# Windows application and call this method from main:
public static void RunBatchFile(string filename)
{
Process process = new Process();
process.StartInfo.FileName = filename;
// suppress output (command window still gets created)
process.StartInfo.Arguments = "> NULL";
process.Start();
process.WaitForExit();
}
I went through most of the solutions posted on this thread. While this question might be old, it is still very applicable to new projects even now, so I spent quite a lot of time reading up on the answers presented here as well as else where.
As @Marco pointed out the different cases under which a 404 can happen, I checked the solution I compiled together against that list. In addition to his list of requirements, I also added one more.
This solution is 2 fold:
First part of it comes from @Guillaume at https://stackoverflow.com/a/27354140/2310818. Their solution takes care of any 404 that were caused due to invalid route, invalid controller and invalid action.
The idea is to create a WebForm and then make it call the NotFound action of your MVC Errors Controller. It does all of this without any redirect so you will not see a single 302 in Fiddler. The original URL is also preserved, which makes this solution fantastic!
Second part of it comes from @Germán at https://stackoverflow.com/a/5536676/2310818. Their solution takes care of any 404 returned by your actions in the form of HttpNotFoundResult() or throw new HttpException()!
The idea is to have a filter look at the response as well as the exception thrown by your MVC controllers and to call the appropriate action in your Errors Controller. Again this solution works without any redirect and the original url is preserved!
As you can see, both of these solutions together offer a very robust error handling mechanism and they achieve all the requirements listed by @Marco as well as my requirements. If you would like to see a working sample or a demo of this solution, please leave in the comments and I would be happy to put it together.
Via Jquery:
$(location).attr('href','http://example.com/Registration/Success/');
I always just convert a matrix:
x <- as.data.frame(matrix(nrow = 100, ncol = 10))
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.
However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:
Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).
Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.
Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
Black Box
1 Focuses on the functionality of the system Focuses on the structure (Program) of the system
2 Techniques used are :
· Equivalence partitioning
· Boundary-value analysis
· Error guessing
· Race conditions
· Cause-effect graphing
· Syntax testing
· State transition testing
· Graph matrix
Tester can be non technical
Helps to identify the vagueness and contradiction in functional specifications
White Box
Techniques used are:
· Basis Path Testing
· Flow Graph Notation
· Control Structure Testing
Condition Testing
Data Flow testing
· Loop Testing
Simple Loops
Nested Loops
Concatenated Loops
Unstructured Loops
Tester should be technical
Helps to identify the logical and coding issues.
All saved Authentication Data for all projects is deleted.
You will have to re-enter credentials to reconnect.
Store them as two fields for phone numbers - a "number" and a "mask" as TinyText
types which do not need more than 255 items.
Before we store the files we parse the phone number to get the formatting that has been used and that creates the mask, we then store the number a digits only e.g.
Input: (0123) 456 7890
Number: 01234567890
Mask: (nnnn)_nnn_nnnn
Theoretically this allows us to perform comparison searches on the Number field such as getting all phone numbers that begin with a specific area code, without having to worry how it was input by the users
The best solution to your problem is to move your project folder to other directory with no non-ASCII characters and blank spaces.
For example ?:\Android\PROJECT-FOLDER
.
You can create the directory in C:\
using the name that you want.
I think it's a little simpler to use the dplyr
functions select
and left_join
; at least it's easier for me to understand. The join function from dplyr
are made to mimic sql arguments.
library(tidyverse)
DF2 <- DF2 %>%
select(client, LO)
joined_data <- left_join(DF1, DF2, by = "Client")
You don't actually need to use the "by" argument in this case because the columns have the same name.
I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.
Their quick explanation: Lambdas are a way to treat code (functions) as data.
document.location
is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.
Shortcut for solution: document.location.toString().substring(2,3);
Or use document.location.href
or window.location.href
if you just want to check if one or the other element are present you can use this custom helper
Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
like this
{{#if_or elem1 elem2}}
{{elem1}} or {{elem2}} are present
{{else}}
not present
{{/if_or}}
if you also need to be able to have an "or" to compare function return values I would rather add another property that returns the desired result.
The templates should be logicless after all!
from __future__ import with_statement
with open('file.txt','r+') as f:
counter = str(int(f.read().strip())+1)
f.seek(0)
f.write(counter)
If you do not want to worry about execution policy, you can use the following and put into a batch script. I use this a lot when having techs at sites run my scripts since half the time they say script didnt work but really it's cause execution policy was undefined our restricted. This will run script even if execution policy would normally block a script to run.
If you want it to run at startup. Then you can place in either shell:startup for a single user or shell:common startup for all users who log into the PC.
cmd.exe /c Powershell.exe -ExecutionPolicy ByPass -File "c:\path\to\script.ps1"
Obviously, making a GPO is your best method if you have a domain and place in Scripts (Startup/Shutdown); under either Computer or User Configurations\Windows Settings\Scripts (Startup/Shutdown). If you go that way make a directory called Startup or something under **
\\yourdomain.com\netlogon\
and put it there to reference in the GPO. This way you know the DC has rights to execute it. When you browse for the script on the DC you will find it under
C:\Windows\SYSVOL\domain\scripts\Startup\
since this is the local path of netlogon.
I also had problem understanding next() , but this helped
var app = require("express")();
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write("Hello");
next(); //remove this and see what happens
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write(" World !!!");
httpResponse.end();
});
app.listen(8080);
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
1. You can remove brackets and line breaks.
if (city.getName() != null) name = city.getName(); else name = "N/A";
2. You can use ?: operators in java.
Syntax:
Variable = Condition ? BlockTrue : BlockElse;
So in your code you can do like this:
name = city.getName() == null ? "N/A" : city.getName();
3. Assign condition result for Boolean
boolean hasName = city.getName() != null;
EXTRA: for curious
In some languages based in JAVA
like Groovy
, you can use this syntax:
name = city.getName() ?: "N/A";
The operator ?:
assign the value returned from the variable which we are asking for. In this case, the value of city.getName()
if it's not null
.
Magic:
$ git svn clone http://svn/repo/here/trunk
Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn git-svn
. The git-svn
main page has a good examples section:
$ git svn --help
There are a few ways depending on what version you have - see the oracle documentation on string aggregation techniques. A very common one is to use LISTAGG
:
SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description
FROM B GROUP BY pid;
Then join to A
to pick out the pids
you want.
Note: Out of the box, LISTAGG
only works correctly with VARCHAR2
columns.
You should be able to do it using the text-shadow, erm somethink like this:
.inner_text_shadow
{
text-shadow: 1px 1px white, -1px -1px #444;
}
here's an example: http://jsfiddle.net/ekDNq/
You can press OK and install xampp to C:\xampp and not into program files
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
Since version 3.0 of Jquery you might get an error
TypeError: url.indexOf is not a function
Which can be easily fix by doing
$('#iframe').on('load', function() {
alert('frame has (re)loaded ');
});
First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.
Recommendations:
Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.
Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.
Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.
Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.
Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.
Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.
Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:
Counting sort: When you are sorting integers with a limited range.
Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.
Bucket sort: When you can guarantee that your input is approximately uniformly distributed.
Finding Object by reference without, strings, Note make sure the object you pass in is cloned , i use cloneDeep from lodash for that
if object looks like
const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]
path looks like
const objectPath = ['data',1,'person',name','last']
then call below method and it will return the sub object by path given
const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"
const findObjectByPath = (objectIn: any, path: any[]) => {
let obj = objectIn
for (let i = 0; i <= path.length - 1; i++) {
const item = path[i]
// keep going up to the next parent
obj = obj[item] // this is by reference
}
return obj
}
Based on Elmer's example I've prepared my own solution. After elements click with defined download class it lets to show custom message on the screen. I've used focus trigger to hide the message.
JavaScript
$(function(){$('.download').click(function() { ShowDownloadMessage(); }); })
function ShowDownloadMessage()
{
$('#message-text').text('your report is creating, please wait...');
$('#message').show();
window.addEventListener('focus', HideDownloadMessage, false);
}
function HideDownloadMessage(){
window.removeEventListener('focus', HideDownloadMessage, false);
$('#message').hide();
}
HTML
<div id="message" style="display: none">
<div id="message-screen-mask" class="ui-widget-overlay ui-front"></div>
<div id="message-text" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable waitmessage">please wait...</div>
</div>
Now you should implement any element to download:
<a class="download" href="file://www.ocelot.com.pl/prepare-report">Download report</a>
or
<input class="download" type="submit" value="Download" name="actionType">
After each download click you will see message your report is creating, please wait...
$(".container > #first");
or
$(".container").children("#first");
or since IDs should be unique within a single document:
$("#first");
The last one is of course the fastest.
Since you're saying that you don't know their ID top couple of the upper selectors (where #first
is written), can be changed to:
$(".container > div");
$(".container").children("div");
The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.
If you also need to filter out only those child DIV
elements that define ID attribute you'd write selectors down this way:
$(".container > div[id]");
$(".container").children("div[id]");
Add the following code to attach click handler to any of your preferred selector:
// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
// if you need element's ID
var divID = this.id;
cache your element if you intend to use it multiple times
var clickedDiv = $(this);
// add CSS class to it
clickedDiv.addClass("add-some-class");
// do other stuff that needs to be done
});
I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.
I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:
$(".container > div[id]").each(function(){
var context = $(this);
// get menu parent element: Sub: Show Grid
// maybe I'm not appending to the correct element here but you should know
context.appendTo(context.parent().parent());
context.text("Show #" + this.id);
context.attr("href", "");
context.click(function(evt){
evt.preventDefault();
$(this).toggleClass("showgrid");
})
});
the last thee context
usages could be combined into a single chained one:
context.text(...).attr(...).click(...);
You can always get the underlaying DOM element from the jQuery result set.
$(...).get(0)
// or
$(...)[0]
will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.
But when I used .each()
function and provided an anonymous function that will be called on each element in the set, this
keyword actually refers to the DOM element.
$(...).each(function(){
var DOMelement = this;
var jQueryElement = $(this);
...
});
I hope this clears some things for your.
Always use :::
. There are two reasons: efficiency and type safety.
Efficiency
x ::: y ::: z
is faster than x ++ y ++ z
, because :::
is right associative. x ::: y ::: z
is parsed as x ::: (y ::: z)
, which is algorithmically faster than (x ::: y) ::: z
(the latter requires O(|x|) more steps).
Type safety
With :::
you can only concatenate two List
s. With ++
you can append any collection to List
, which is terrible:
scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)
++
is also easy to mix up with +
:
scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab
Just make a comparison function/functor:
bool my_cmp(const data& a, const data& b)
{
// smallest comes first
return a.word.size() < b.word.size();
}
std::sort(info.begin(), info.end(), my_cmp);
Or provide an bool operator<(const data& a) const
in your data
class:
struct data {
string word;
int number;
bool operator<(const data& a) const
{
return word.size() < a.word.size();
}
};
or non-member as Fred said:
struct data {
string word;
int number;
};
bool operator<(const data& a, const data& b)
{
return a.word.size() < b.word.size();
}
and just call std::sort()
:
std::sort(info.begin(), info.end());
The absolutely best way: Just let your activity implement View.OnClickListener
, and write your onClick
method like this:
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.button1:
// your code for button1 here
break;
case R.id.button2:
// your code for button2 here
break;
// even more buttons here
}
}
Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick
:
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.
A nice solution without using interop:
As always, simply enable DoubleBuffered=true on your CustomControl. Then, if you have any containers like FlowLayoutPanel or TableLayoutPanel, derive a class from each of these types and in the constructors, enable double buffering. Now, simply use your derived Containers instead of the Windows.Forms Containers.
class TableLayoutPanel : System.Windows.Forms.TableLayoutPanel
{
public TableLayoutPanel()
{
DoubleBuffered = true;
}
}
class FlowLayoutPanel : System.Windows.Forms.FlowLayoutPanel
{
public FlowLayoutPanel()
{
DoubleBuffered = true;
}
}
{{#each array}}
{{@index}}
{{/each}}
It is the ternary conditional operator.
If the condition in the parenthesis before the ?
is true, it returns the value to the left of the :
, otherwise the value to the right.
In Swift 4.1 and Xcode 9.4.1
I have two apps 1)PageViewControllerExample and 2)DelegateExample. Now i want to open DelegateExample app with PageViewControllerExample app. When i click open button in PageViewControllerExample, DelegateExample app will be opened.
For this we need to make some changes in .plist files for both the apps.
Step 1
In DelegateExample app open .plist file and add URL Types and URL Schemes. Here we need to add our required name like "myapp".
Step 2
In PageViewControllerExample app open .plist file and add this code
<key>LSApplicationQueriesSchemes</key>
<array>
<string>myapp</string>
</array>
Now we can open DelegateExample app when we click button in PageViewControllerExample.
//In PageViewControllerExample create IBAction
@IBAction func openapp(_ sender: UIButton) {
let customURL = URL(string: "myapp://")
if UIApplication.shared.canOpenURL(customURL!) {
//let systemVersion = UIDevice.current.systemVersion//Get OS version
//if Double(systemVersion)! >= 10.0 {//10 or above versions
//print(systemVersion)
//UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
//} else {
//UIApplication.shared.openURL(customURL!)
//}
//OR
if #available(iOS 10.0, *) {
UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(customURL!)
}
} else {
//Print alert here
}
}
The method getContentAsByteArray() of the Spring class ContentCachingRequestWrapper reads the body multiple times, but the methods getInputStream() and getReader() of the same class do not read the body multiple times:
"This class caches the request body by consuming the InputStream. If we read the InputStream in one of the filters, then other subsequent filters in the filter chain can't read it anymore. Because of this limitation, this class is not suitable in all situations."
In my case more general solution that solved this problem was to add following three classes to my Spring boot project (and the required dependencies to the pom file):
CachedBodyHttpServletRequest.java:
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
InputStream requestInputStream = request.getInputStream();
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new CachedBodyServletInputStream(this.cachedBody);
}
@Override
public BufferedReader getReader() throws IOException {
// Create a reader from cachedContent
// and return it
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
}
}
CachedBodyServletInputStream.java:
public class CachedBodyServletInputStream extends ServletInputStream {
private InputStream cachedBodyInputStream;
public CachedBodyServletInputStream(byte[] cachedBody) {
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
}
@Override
public boolean isFinished() {
try {
return cachedBodyInputStream.available() == 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException();
}
@Override
public int read() throws IOException {
return cachedBodyInputStream.read();
}
}
ContentCachingFilter.java:
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(filterName = "ContentCachingFilter", urlPatterns = "/*")
public class ContentCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("IN ContentCachingFilter ");
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(httpServletRequest);
filterChain.doFilter(cachedBodyHttpServletRequest, httpServletResponse);
}
}
I also added the following dependencies to pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
A tuturial and full source code is located here: https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times
A possible reason for an empty $_POST
is that the request is not POST
, or not POST
anymore... It may have started out as post, but encountered a 301
or 302
redirect somewhere, which is switched to GET
!
Inspect $_SERVER['REQUEST_METHOD']
to check if this is the case.
See https://stackoverflow.com/a/19422232/109787 for a good discussion of why this should not happen but still does.
The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.
SO uses a hidden field for the upvote click.
<input value="16293741" name="postId" type="hidden">
Using this value, the server-side script can store the upvote.
you can also use flask_api for sending response
from flask_api import status
@app.route('/your-api/')
def empty_view(self):
content = {'your content here'}
return content, status.HTTP_201_CREATED
you can find reference here http://www.flaskapi.org/api-guide/status-codes/
I got this problem. The debug.keystore
file was missing.
So the only step that created a correct file for me was creating a new Android project in Android Studio.
It created me a new debug.keystore
under path C:\Users\username\.android\
.
This solution probably works only when you have not created any projects yet.
For me, my Eclipse installation was hosed - I think because I'd installed struts. After trying a dozen remedies for this error, I re-installed Eclipse, made a new workspace and it was OK. Using Kepler-64-Windows, Tomcat 7, Windows 7.
Sometimes it is possible to solve it in the model like this: Suppose you have 3 boolean properties OptionA, OptionB, OptionC.
XAML:
<RadioButton IsChecked="{Binding OptionA}"/>
<RadioButton IsChecked="{Binding OptionB}"/>
<RadioButton IsChecked="{Binding OptionC}"/>
CODE:
private bool _optionA;
public bool OptionA
{
get { return _optionA; }
set
{
_optionA = value;
if( _optionA )
{
this.OptionB= false;
this.OptionC = false;
}
}
}
private bool _optionB;
public bool OptionB
{
get { return _optionB; }
set
{
_optionB = value;
if( _optionB )
{
this.OptionA= false;
this.OptionC = false;
}
}
}
private bool _optionC;
public bool OptionC
{
get { return _optionC; }
set
{
_optionC = value;
if( _optionC )
{
this.OptionA= false;
this.OptionB = false;
}
}
}
You get the idea. Not the cleanest thing, but easy.
There is actually a python library called dataframe_image Just do a
pip install dataframe_image
Do the imports
import pandas as pd
import numpy as np
import dataframe_image as dfi
df = pd.DataFrame(np.random.randn(6, 6), columns=list('ABCDEF'))
and style your table if you want by:
df_styled = df.style.background_gradient() #adding a gradient based on values in cell
and finally:
dfi.export(df_styled,"mytable.png")
This "tuple" feature it is called destructuring in EcmaScript2015 and is soon to be supported by up to date browsers. For the time being, only Firefox and Chrome support it.
But hey, you can use a transpiler.
The code would look as nice as python:
let tuple = ["Bob", 24]
let [name, age] = tuple
console.log(name)
console.log(age)
I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.
For example, I have a revealing module declared with var knockoutUtilityModule = function() {...}
within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.
Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript).
This can however be a pain for some things. (which is why libraries were invented in the first place).
Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources.
The articles on this website are pretty good: http://www.htmlgoodies.com/primers/jsp/
And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command
grep -r --color foo /opt
with no issue. With Cygwin /
represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.
Uninstall what Git you have and install the Cygwin git package, save yourself the headache.
In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:
cat input.json | jq -r 'keys'
From jq help:
-r output raw strings, not JSON texts;
If you prefer to use annotations to selectively silence rules, this is now possible using the @SuppressWarnings
annotation, starting with Checkstyle 5.7 (and supported by the Checkstyle Maven Plugin 2.12+).
First, in your checkstyle.xml
, add the SuppressWarningsHolder
module to the TreeWalker
:
<module name="TreeWalker">
<!-- Make the @SuppressWarnings annotations available to Checkstyle -->
<module name="SuppressWarningsHolder" />
</module>
Next, enable the SuppressWarningsFilter
there (as a sibling to TreeWalker
):
<!-- Filter out Checkstyle warnings that have been suppressed with the @SuppressWarnings annotation -->
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
...
Now you can annotate e.g. the method you want to exclude from a certain Checkstyle rule:
@SuppressWarnings("checkstyle:methodlength")
@Override
public boolean equals(Object obj) {
// very long auto-generated equals() method
}
The checkstyle:
prefix in the argument to @SuppressWarnings
is optional, but I like it as a reminder where this warning came from. The rule name must be lowercase.
Lastly, if you're using Eclipse, it will complain about the argument being unknown to it:
Unsupported @SuppressWarnings("checkstyle:methodlength")
You can disable this Eclipse warning in the preferences if you like:
Preferences:
Java
--> Compiler
--> Errors/Warnings
--> Annotations
--> Unhandled token in '@SuppressWarnings': set to 'Ignore'
I know that I'm being a bit of a necromancer here, but I stumbled across this question and the accepted solution didn't work for me for all cases Thought it might be useful to submit anyway. In particular, the "executable" mode detection, and the requirement of supplying the file extension. Furthermore, both python3.3's shutil.which
(uses PATHEXT
) and python2.4+'s distutils.spawn.find_executable
(just tries adding '.exe'
) only work in a subset of cases.
So I wrote a "super" version (based on the accepted answer, and the PATHEXT
suggestion from Suraj). This version of which
does the task a bit more thoroughly, and tries a series of "broadphase" breadth-first techniques first, and eventually tries more fine-grained searches over the PATH
space:
import os
import sys
import stat
import tempfile
def is_case_sensitive_filesystem():
tmphandle, tmppath = tempfile.mkstemp()
is_insensitive = os.path.exists(tmppath.upper())
os.close(tmphandle)
os.remove(tmppath)
return not is_insensitive
_IS_CASE_SENSITIVE_FILESYSTEM = is_case_sensitive_filesystem()
def which(program, case_sensitive=_IS_CASE_SENSITIVE_FILESYSTEM):
""" Simulates unix `which` command. Returns absolute path if program found """
def is_exe(fpath):
""" Return true if fpath is a file we have access to that is executable """
accessmode = os.F_OK | os.X_OK
if os.path.exists(fpath) and os.access(fpath, accessmode) and not os.path.isdir(fpath):
filemode = os.stat(fpath).st_mode
ret = bool(filemode & stat.S_IXUSR or filemode & stat.S_IXGRP or filemode & stat.S_IXOTH)
return ret
def list_file_exts(directory, search_filename=None, ignore_case=True):
""" Return list of (filename, extension) tuples which match the search_filename"""
if ignore_case:
search_filename = search_filename.lower()
for root, dirs, files in os.walk(path):
for f in files:
filename, extension = os.path.splitext(f)
if ignore_case:
filename = filename.lower()
if not search_filename or filename == search_filename:
yield (filename, extension)
break
fpath, fname = os.path.split(program)
# is a path: try direct program path
if fpath:
if is_exe(program):
return program
elif "win" in sys.platform:
# isnt a path: try fname in current directory on windows
if is_exe(fname):
return program
paths = [path.strip('"') for path in os.environ.get("PATH", "").split(os.pathsep)]
exe_exts = [ext for ext in os.environ.get("PATHEXT", "").split(os.pathsep)]
if not case_sensitive:
exe_exts = map(str.lower, exe_exts)
# try append program path per directory
for path in paths:
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
# try with known executable extensions per program path per directory
for path in paths:
filepath = os.path.join(path, program)
for extension in exe_exts:
exe_file = filepath+extension
if is_exe(exe_file):
return exe_file
# try search program name with "soft" extension search
if len(os.path.splitext(fname)[1]) == 0:
for path in paths:
file_exts = list_file_exts(path, fname, not case_sensitive)
for file_ext in file_exts:
filename = "".join(file_ext)
exe_file = os.path.join(path, filename)
if is_exe(exe_file):
return exe_file
return None
Usage looks like this:
>>> which.which("meld")
'C:\\Program Files (x86)\\Meld\\meld\\meld.exe'
The accepted solution did not work for me in this case, since there were files like meld.1
, meld.ico
, meld.doap
, etc also in the directory, one of which were returned instead (presumably since lexicographically first) because the executable test in the accepted answer was incomplete and giving false positives.