You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:
import httplib2 as http
import json
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
uri = 'http://yourservice.com'
path = '/path/to/resource/'
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
# If you need authentication some example:
if auth:
h.add_credentials(auth.user, auth.password)
response, content = h.request(
target.geturl(),
method,
body,
headers)
# assume that content is a json reply
# parse content with the json module
data = json.loads(content)
I had this problem when trying to connect to my SQL Server 2017 instance via L2TP VPN on a domain-joined Windows 10 machine.
The problem ended up being in my VPN settings. In the security settings, in Authentication, using EAP-MSCHAPv2 and in the Properties dialog, I had selected Automatically use my Windows logon name and password (and domain if any).
I turned this off and then re-connected my VPN and then I was able to connect to SQL Server successfully.
I believe this was causing my SQL login (with Windows account security) to use Kerberos instead of NTLM, causing the SSPI error.
Consider adding
[appdefaults]
validate=false
to your /etc/krb5.conf. This can work around mismatching DNS.
Because you may include two same libs in your project. check your build.gradle file.
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile files('libs/android-support-v4.jar')
}
if your file includes compile 'com.android.support:appcompat-v7:+'
and compile files('libs/android-support-v4.jar')
, it will have this problems.
delete this sentence: compile files('libs/android-support-v4.jar')
That's how I fix this problem.
I tried following the above tutorial. Thing is tensorflow changes a lot and so do the NVIDIA versions needed for running on a GPU. The next issue is that your driver version determines your toolkit version etc. As of today this information about the software requirements should shed some light on how they interplay:
NVIDIA® GPU drivers —CUDA 9.0 requires 384.x or higher.
CUDA® Toolkit —TensorFlow supports CUDA 9.0.
CUPTI ships with the CUDA Toolkit.
cuDNN SDK (>= 7.2) Note: Make sure your GPU has compute compatibility >3.0
(Optional) NCCL 2.2 for multiple GPU support.
(Optional) TensorRT 4.0 to improve latency and throughput for inference on some models.
And here you'll find the up-to-date requirements stated by tensorflow (which will hopefully be updated by them on a regular basis).
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
Most of the time you need to create a Service to perform something in the background, and your visible Activity
simply controls this Service
. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity
can finish
as usual and the Service
will still be running.
A simpler approach is to capture the Back
button press and call moveTaskToBack(true) as follows:
// 2.0 and above
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack
can be used as a quick alternative on occasion.
NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed
method, and these recommendations on how to handle the Back button.
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.
AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.
AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.
In Java 8 or later:
String listString = String.join(", ", list);
In case the list
is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :
Note: Make sure your date is allready made by the format : dd/MM/YYYY
/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
return Integer.parseInt(dateFormat.format(date));
}
/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return Integer.parseInt(dateFormat.format(date));
}
To show vertical scroll bar in your div you need to add
height: 100px;
overflow-y : scroll;
or
height: 100px;
overflow-y : auto;
zlists = [[0] * i for i in range(10)]
zlists[0]
is a list of 0 zeroes, zlists[1]
is a list of 1 zero, zlists[2]
is a list of 2 zeroes, etc.
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp
class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone
is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime
as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp
without time zone, retrieve a LocalDateTime
instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd
.
I wasn’t sure what you meant by the xx
in HH:MM xx
. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
The correct solution is a FullText Search (if you can use it) https://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
This nearly does what you want:
SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100)+.*(Stylus|2100)+';
SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*';
But this will also match "210021002100" which is not great.
You can use basic Random Functions of C#
Random ran = new Random();
int randomno = ran.Next(0,100);
you can now use the value in the randomno in anything you want but keep in mind that this will generate a random number between 0
and 100
Only and you can extend that to any figure.
Take care not to include
#include <string.h>
but only
#include <string>
It took me 1 hour to find this in my code.
Hope this can help
You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.
If you're interested, I've written a bit about my experience using Haxe/NME: link
This happens to me whenever I do autoload stuff in autoload.php like the 'database'
To resolve this, If you're using Windows OS
Open your php.ini.
Search and uncomment this line - extension=php_mysql.dll
(Please also check If the PHP directive points to where your extensions is located.
Mine is extension_dir = "C:\php-5.4.8-Win32-VC9-x86\ext"
)
Restart Apache and refresh your page
you have to git add css/mobile.css
the new file and git rm css/iphone.css
, so git knows about it. then it will show the same output in git status
you can see it clearly in the status output (the new name of the file):
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
and (the old name):
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
i think behind the scenes git mv
is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name
If you are using an inside form, add the attribute type="reset" along with the button element. It will prevent the form action.
<button type="reset" onclick="location.href='http://www.example.com'">
www.example.com
</button>
2017 I know... but someone is facing this problem during their code maintenance.
This error happened when I tried:
maskedbox.Mask = "#.###"
maskedbox.Text = "12345678"
To fix that, just set PromptInclude property to "false".
If you already have Jackson in your project, you can use com.fasterxml.jackson.core.Version
:
import com.fasterxml.jackson.core.Version;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class VersionTest {
@Test
public void shouldCompareVersion() {
Version version1 = new Version(1, 11, 1, null, null, null);
Version version2 = new Version(1, 12, 1, null, null, null);
assertTrue(version1.compareTo(version2) < 0);
}
}
If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)
AngularJS pass string, numbers and booleans by value while it passes arrays and objects by reference. So you can create an empty object and make your date a property of that object. In that way angular will detect model changes.
In controller
app.module('yourModule').controller('yourController',function($scope){
$scope.vm={selectedDate:''}
});
In html
<div ng-controller="yourController">
<input id="selectedDueDate" type="text" ng-model="vm.selectedDate" />
</div>
Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.
// https://classroom.synonym.com/calculate-trendline-2709.html
package main
import (
"fmt"
"math"
)
func main() {
graph := [][]float64{
{1, 3},
{2, 5},
{3, 6.5},
}
n := len(graph)
// get the slope
var a float64
var b float64
var bx float64
var by float64
var c float64
var d float64
var slope float64
for _, point := range graph {
a += point[0] * point[1]
bx += point[0]
by += point[1]
c += math.Pow(point[0], 2)
d += point[0]
}
a *= float64(n) // 97.5
b = bx * by // 87
c *= float64(n) // 42
d = math.Pow(d, 2) // 36
slope = (a - b) / (c - d) // 1.75
// calculating the y-intercept (b) of the Trendline
var e float64
var f float64
e = by // 14.5
f = slope * bx // 10.5
intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3
// output
fmt.Println(slope)
fmt.Println(intercept)
}
Update with Java 9+ with takeWhile
:
MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
// doing something.
if (...) { // want to break;
ongoing.setFalse();
}
});
I normally have all of my work in a dropbox folder. This ensures me that I would have the current folder available outside my local machine and Github. I think it's my other step to guarantee a "version control" other than git. You can follow this in order to revert your file to previous versions of your dropbox files
Hope this helps.
As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:
var property in obj.GetType().GetProperties()
From there you can access like so:
property.Name
property.GetValue(obj, null)
With GetValue
the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.
This:
lst = [8 for i in range(9)]
creates a list, elements are initialized 8
but this:
lst = [0] * 7
would create 7 lists which have one element
h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:
<h:form>
<h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>
this code generates the follwing html:
<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">
whereas the h:button is simpler and just used for static or rule based navigation as follows
<h:button outcome="page.xhtml" value="button"/>
the generated html is
<title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />
Following steps has fixed my issue.
(1) Moved the website to a Dedicated application pool.
(2) Changed the Managed Pipeline Mode from integrated to Classic.
(3) Set Enable 32-Bit Applications from false to true.
ASP pages are working fine now!
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
If you want to post string as raw body in request
return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
return (mutableRequest, nil)
}))
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:
cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
print("At least " + str(nr_conds) + " conditions are fullfilled")
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
print("All conditions are fullfilled")
This means you can just change in the two initial lists, at least for me this makes it easier.
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
Due to comments
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand() / 100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000
.
If you are in a browser environment you can also use btoa.
btoa
is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.
Example:
> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="
You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=
to the authorization
header.
Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.
This security.stackexchange.com answer gives a good overview of some of the downsides.
Here is RxJava
solution to the problem
String title = "this is a title";
StringBuilder stringBuilder = new StringBuilder();
Observable.fromArray(title.trim().split("\\s"))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
.toList()
.map(wordList -> {
for (String word : wordList) {
stringBuilder.append(word).append(" ");
}
return stringBuilder.toString();
})
.subscribe(result -> System.out.println(result));
I don't yet like the for loop inside map though.
file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))
This is solve your encode error
also.
I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:
https://github.com/Heras/Responsive-Breakpoints
Just add class responsive-breakpoints
to any element, and it will automagically add xs sm md lg xl
classes to those elements.
Please use kafka-topics.sh --list --bootstrap-server localhost:9092
to list down all topics
<i class="fa" v-bind:class="cravings"></i>
and add in computed :
computed: {
cravings: function() {
return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
}
}
Firstly, I would try a non-secure websocket connection. So remove one of the s
's from the connection address:
conn = new WebSocket('ws://localhost:8080');
If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080
both in TCP_IN
and TCP_OUT
.
If working in Java 1.8 you can leverage the DateTimeFormatterBuilder
public static boolean isTimeStampValid(String inputString)
{
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm:ss.SSSZ]" + "[yyyy-MM-dd]"));
DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
try {
dateTimeFormatter.parse(inputString);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
See post: Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?
It would be better to choose JSON-RPC between REST and JSON-RPC to develop an API for a web application that is easier to understand. JSON-RPC is preferred because its mapping to method calls and communications can be easily understood.
Choosing the most suitable approach depends on the constraints or principal objective. For example, as far as performance is a major trait, it is advisable to go for JSON-RPC (for example, High Performance Computing). However, if the principal objective is to be agnostic in order to offer a generic interface to be inferred by others, it is advisable to go for REST. If you both goals are needed to be achieved, it is advisable to include both protocols.
The fact which actually splits REST from JSON-RPC is that it trails a series of carefully thought out constraints- confirming architectural flexibility. The constraints take in ensuring that the client as well as server are able to grow independently of each other (changes can be made without messing up with the application of client), the calls are stateless (the state is regarded as hypermedia), a uniform interface is offered for interactions, the API is advanced on a layered system (Hall, 2010). JSON-RPC is rapid and easy to consume, however as mentioned resources as well as parameters are tightly coupled and it is likely to depend on verbs (api/addUser, api/deleteUser) using GET/ POST whereas REST delivers loosely coupled resources (api/users) in a HTTP. REST API depends up on several HTTP methods such as GET, PUT, POST, DELETE, PATCH. REST is slightly tougher for inexperienced developers to implement.
JSON (denoted as JavaScript Object Notation) being a lightweight data-interchange format, is easy for humans to read as well as write. It is hassle free for machines to parse and generate. JSON is a text format which is entirely language independent but practices conventions that are acquainted to programmers of the family of languages, consisting of C#, C, C++, Java, Perl, JavaScript, Python, and numerous others. Such properties make JSON a perfect data-interchange language and a better choice to opt for.
Just use <c:url>
-tag with an application context relative path.
When the value
parameter starts with an /
, then the tag will treat it as an application relative url, and will add the application-name to the url.
Example:
jsp:
<c:url value="/templates/style/main.css" var="mainCssUrl" />`
<link rel="stylesheet" href="${mainCssUrl}" />
...
<c:url value="/home" var="homeUrl" />`
<a href="${homeUrl}">home link</a>
will become this html, with an domain relative url:
<link rel="stylesheet" href="/AppName/templates/style/main.css" />
...
<a href="/AppName/home">home link</a>
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.
For objects, their default constructor is called. For example, for std::string
, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.
For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.
For references (e.g. std::string&
), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.
So, in your specific case, if they are not explicitly initialized:
int *ptr; // Contains junk
string name; // Empty string
string *pname; // Contains junk
string &rname; // Compile error
const string &crname; // Compile error
int age; // Contains junk
The link below works for Xcode 6, especially if you are getting an error after trying to rename your project. Basically, just try building a new scheme of your app.
The C++20 draft contains the convenience function std::erase_if
.
So you can use that function to do it as a one-liner.
std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});
set timing on <br>
set linesize 180<br>
spool template.log
/*<br>
##########################################################################<br>
-- Name : Template.sql<br>
-- Date : (sysdate) <br>
-- Author : Duncan van der Zalm - dvdzalm<br>
-- Company : stanDaarD-Z.nl<br>
-- Purpose : <br>
-- Usage sqlplus <br>
-- Impact :<br>
-- Required grants : sel on A, upd on B, drop on C<br>
-- Called by : some other process<br
##########################################################################<br>
-- ver user date change <br>
-- 1.0 DDZ 20110622 initial<br>
##########################################################################<br>
*/<br>
sho user<br>
select name from v$database;
select to_char(sysdate, 'Day DD Month yyyy HH24:MI:SS') "Start time"
from dual
;
-- script
select to_char(sysdate, 'Day DD Month yyyy HH24:MI:SS') "End time"
from dual
;
spool off
The best way to protect your input it's use htmlentities
function.
Example:
htmlentities($target, ENT_QUOTES, 'UTF-8');
You can get more information here.
This is a solution that I've used in the past. Although the example here is in VB.net - I've used this technique with c and c++. It bypasses all the issues with Process IDs & Process handles, and return codes. Windows is very faithful in releasing the mutex no matter how Process2 is terminated. I hope it is helpful to someone...
**PROCESS1 :-**
Randomize()
mutexname = "myprocess" & Mid(Format(CDbl(Long.MaxValue) * Rnd(), "00000000000000000000"), 1, 16)
hnd = CreateMutex(0, False, mutexname)
' pass this name to Process2
File.WriteAllText("mutexname.txt", mutexname)
<start Process2>
<wait for Process2 to start>
pr = WaitForSingleObject(hnd, 0)
ReleaseMutex(hnd)
If pr = WAIT_OBJECT_0 Then
<Process2 not running>
Else
<Process2 is running>
End If
...
CloseHandle(hnd)
EXIT
**PROCESS2 :-**
mutexname = File.ReadAllText("mutexname.txt")
hnd = OpenMutex(MUTEX_ALL_ACCESS Or SYNCHRONIZE, True, mutexname)
...
ReleaseMutex(hnd)
CloseHandle(hnd)
EXIT
You can also use a simple filtering function without any plugins. This is not exactly what you want but the result is the same:
$('a').data("user", {name: {first:"Tom",last:"Smith"},username: "tomsmith"});
$('a').filter(function() {
return $(this).data('user') && $(this).data('user').name.first === "Tom";
});
For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...
Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).
When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.
At that point you'll get a tiny dialog to confirm with:
Java SDK: 1.7 (e.g.)
Build target: Android 6.0 (e.g.)
You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:
Android API 23 Platform (java version "1.7.0_67")
If you are using the latest Skype, go to:
Tools -> Options -> Advanced -> connection.
Disable the 'Use port 80 and 443 for alternatve.. '
Sign Out and Close all Skype windows. Try restart your Apache again.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array(),
array('id' => 'ASC')
);
I struggled with the same permission denied error apparently due to
key_parse_private2: missing begin marker
In my situation the cause was the ssh config file of the current user (~/.ssh/config).
Using the following:
ssh -i ~/myKey.pem ec2-user@<IP address> -v 'exit'
The initial output showed:
debug1: Reading configuration data /home/ec2-user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Hostname has changed; re-reading configuration
debug1: Reading configuration data /home/ec2-user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
... many debug lines cut here ...
debug1: Next authentication method: publickey
debug1: Trying private key: /home/ec2-user/somekey.pem
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
The third line above is where the problem actual was identified; however, I looked for at the debug message four lines from the bottom (above) and was misled. There isn't a problem with the key but I tested it and compared other configurations.
My user ssh config file reset the host via an unintended global setting as shown below. The first Host line should not have been a comment.
$ cat config
StrictHostKeyChecking=no
#Host myAlias
user ec2-user
Hostname bitbucket.org
# IdentityFile ~/.ssh/somekey
# IdentitiesOnly yes
Host my2ndAlias
user myOtherUser
Hostname bitbucket.org
IdentityFile ~/.ssh/my2ndKey
IdentitiesOnly yes
I hope someone else finds this helpful.
If your Architectures and Valid Architectures are all right, you may check whether you have added $(inherited)
, which will add linker flags generated in pods, to Other Linker Flags as below:
Javascript:
var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);
The regex is not allowed for:
[email protected]
[email protected]..
Allowed for:
[email protected]
[email protected]
Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
If you load a 32 bit version of your dll with a 64 bit JRE you could have this issue. This was my case.
I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.
in global.asax hook the OnSessionStart event
void OnSessionStart(...)
{
HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}
From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.
public static MySessionObject GetMySessionObject(this HttpContext current)
{
return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}
This way you can in code
void OnLoad(...)
{
var sessionObj = HttpContext.Current.GetMySessionObject();
// do something with 'sessionObj'
}
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
Where A
is your 2D array:
import numpy as np
A[np.isnan(A)] = 0
The function isnan
produces a bool array indicating where the NaN
values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.
in laravel 5 first we need to create migration and then run the migration
Step 1.
php artisan make:migration create_users_table --create=users
Step 2.
php artisan migrate
I found the answer :
{% for key,value in array_path %}
Key : {{ key }}
Value : {{ value }}
{% endfor %}
Yes. Importing CSS file into another CSS file is possible.
It must be the first rule in the style sheet using the @import rule.
@import "mystyle.css";
@import url("mystyle.css");
The only caveat is that older web browsers will not support it. In fact, this is one of the CSS 'hack' to hide CSS styles from older browsers.
Refer to this list for browser support.
SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.
It is probably not the best thing to do. You need to at least check out your PHP error log for things going wrong ;)
# PHP error handling for development servers
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0
I wanted to do this so wrote a simple function. It works great for me and is quite versatile (supports years to microseconds, and any granularity level, e.g. you can pick between '2 days, 4 hours, 48 minutes' and '2 days, 4 hours' and '2 days, 4.8 hours', etc.
def pretty_print_timedelta(t, max_components=None, max_decimal_places=2):
'''
Print a pretty string for a timedelta.
For example datetime.timedelta(days=2, seconds=17280) will be printed as '2 days, 4 hours, 48 minutes'. Setting max_components to e.g. 1 will change this to '2.2 days', where the
number of decimal points can also be set.
'''
time_scales = [timedelta(days=365), timedelta(days=1), timedelta(hours=1), timedelta(minutes=1), timedelta(seconds=1), timedelta(microseconds=1000), timedelta(microseconds=1)]
time_scale_names_dict = {timedelta(days=365): 'year',
timedelta(days=1): 'day',
timedelta(hours=1): 'hour',
timedelta(minutes=1): 'minute',
timedelta(seconds=1): 'second',
timedelta(microseconds=1000): 'millisecond',
timedelta(microseconds=1): 'microsecond'}
count = 0
txt = ''
first = True
for scale in time_scales:
if t >= scale:
count += 1
if count == max_components:
n = t / scale
else:
n = int(t / scale)
t -= n*scale
n_txt = str(round(n, max_decimal_places))
if n_txt[-2:]=='.0': n_txt = n_txt[:-2]
txt += '{}{} {}{}'.format('' if first else ', ', n_txt, time_scale_names_dict[scale], 's' if n>1 else '', )
if first:
first = False
if len(txt) == 0:
txt = 'none'
return txt
var stringToSplit = "0, 10, 20, 30, 100, 200";
// To parse your string
var elements = test.Split(new[]
{ ',' }, System.StringSplitOptions.RemoveEmptyEntries);
// To Loop through
foreach (string items in elements)
{
// enjoy
}
I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...
string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
//You have it ...
}
In practice the question often arises together with some constraints. In that case following solution template may come in handy.
cd dir1
find . \( -name '*.txt' -o -iname '*.md' \) | xargs -i diff -u '{}' 'dir2/{}'
If you are using CentOS or another Linux flavour then just do Ctrl
+R
at the prompt and type git
.
If you keep hitting Ctrl
+R
this will do a reverse search through your history for commands that start with git
Use below snippet.
.a{
color: $brn-acc-clr;
background-color: transparent;
border-color: #888888;
&:hover:active{
outline: none;
color: #888888;
border-color: #888888;
}
&:fill{
background-color: #888888;
color: #fff;
box-shadow: 0 3px 10px rgba(#888888, 0.5);
&:hover:active{
color: #fff;
}
&:hover:not(:disabled){
transform: translateY(-2px);
background-color: darken(#888888, 4);
}
}
}
When executing DML statement , you should use executeUpdate
/execute
rather than executeQuery
.
Here is a brief comparison :
You can also try the Regex
class.
var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );
try..
Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry
mylist = sortedList.ToList
If you are looking for the folder such as brushes, curves, etc. you can try:
/home/<username>/.gimp-2.8
This folder will contain all the gimp folders
.
Good Luck.
From the documentation, "the right way is to define a separate server for example.org":
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
...
}
For those who want a solution including https://
...
server {
listen 80;
server_name www.domain.com;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://domain.com$request_uri;
}
server {
listen 80;
server_name domain.com;
# here goes the rest of your config file
# example
location / {
rewrite ^/cp/login?$ /cp/login.php last;
# etc etc...
}
}
Note: I have not originally included https://
in my solution since we use loadbalancers and our https:// server is a high-traffic SSL payment server: we do not mix https:// and http://.
To check the nginx version, use nginx -v
.
Strip www from url with nginx redirect
server {
server_name www.domain.com;
rewrite ^(.*) http://domain.com$1 permanent;
}
server {
server_name domain.com;
#The rest of your configuration goes here#
}
So you need to have TWO server codes.
Add the www to the url with nginx redirect
If what you need is the opposite, to redirect from domain.com to www.domain.com, you can use this:
server {
server_name domain.com;
rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
server_name www.domain.com;
#The rest of your configuration goes here#
}
As you can imagine, this is just the opposite and works the same way the first example. This way, you don't get SEO marks down, as it is complete perm redirect and move. The no WWW is forced and the directory shown!
server {
server_name www.google.com;
rewrite ^(.*) http://google.com$1 permanent;
}
server {
listen 80;
server_name google.com;
index index.php index.html;
####
# now pull the site from one directory #
root /var/www/www.google.com/web;
# done #
location = /favicon.ico {
log_not_found off;
access_log off;
}
}
If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
and client side JavaScript/jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.
Yes, await / async was a great concept, but the implementation is completely broken.
For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.
Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.
This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.
If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.
So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...
There is two steps to extract year for all the dataframe without using method apply.
Step1
convert the column to datetime :
df['ArrivalDate']=pd.to_datetime(df['ArrivalDate'], format='%Y-%m-%d')
Step2
extract the year or the month using DatetimeIndex()
method
pd.DatetimeIndex(df['ArrivalDate']).year
Here is a way to change the owner on ALL DBS (excluding System)
EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
exec sp_changedbowner ''sa''
END
'
this worked for me /properties/maven uncheck resolve dependencies from Workspace projects.
If you are unable to install with either of these:
sudo apt-get install python-distutils
sudo apt-get install python3-distutils
Try this instead:
sudo apt-get install python-distutils-extra
Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro
I found the way to fix this problem was to rename the project. If you give it a name with strange characters (in my case, :), it will have trouble locating your class. I don't know if this rule applies to numbers, but try renaming the project or making a new one and copying the files. Name it without any numbers or special characters.
I assume you have already read Wikipedia and other academic resources on this, so I won't recycle any of that information. I must also caveat that I am not a computer science expert by any means, but I'll share my two cents on my understanding of these topics...
Breaks the problem down into discrete subproblems. The recursive algorithm for the Fibonacci sequence is an example of Dynamic Programming, because it solves for fib(n) by first solving for fib(n-1). In order to solve the original problem, it solves a different problem.
These algorithms typically solve similar pieces of the problem, and then put them together at the end. Mergesort is a classic example of divide and conquer. The main difference between this example and the Fibonacci example is that in a mergesort, the division can (theoretically) be arbitrary, and no matter how you slice it up, you are still merging and sorting. The same amount of work has to be done to mergesort the array, no matter how you divide it up. Solving for fib(52) requires more steps than solving for fib(2).
it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit
if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte
when in doubt, use VARCHAR2(1 CHAR)
same thing answered here Difference between BYTE and CHAR in column datatypes
Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB
in Oracle, don't use VARCHAR
Thanks for the original answer here. With python 3 the following line of code:
print(json.dumps(result_dict,ensure_ascii=False))
was ok. Consider trying not writing too much text in the code if it's not imperative.
This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html
basically install he_IL or whatever language locale on ubuntu check it is not installed
locale -a
install it where XX is your language
sudo apt-get install language-pack-XX
For example:
sudo apt-get install language-pack-he
add the following text to /etc/apache2/envvrs
export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'
Than you would hopefully not get python errors on from apache like:
print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)
Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?
Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation
I just made my own UniqueList in my own little library like this:
package com.bprog.collections;//my own little set of useful utilities and classes
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Jonathan
*/
public class UniqueList {
private HashSet masterSet = new HashSet();
private ArrayList growableUniques;
private Object[] returnable;
public UniqueList() {
growableUniques = new ArrayList();
}
public UniqueList(int size) {
growableUniques = new ArrayList(size);
}
public void add(Object thing) {
if (!masterSet.contains(thing)) {
masterSet.add(thing);
growableUniques.add(thing);
}
}
/**
* Casts to an ArrayList of unique values
* @return
*/
public List getList(){
return growableUniques;
}
public Object get(int index) {
return growableUniques.get(index);
}
public Object[] toObjectArray() {
int size = growableUniques.size();
returnable = new Object[size];
for (int i = 0; i < size; i++) {
returnable[i] = growableUniques.get(i);
}
return returnable;
}
}
I have a TestCollections class that looks like this:
package com.bprog.collections;
import com.bprog.out.Out;
/**
*
* @author Jonathan
*/
public class TestCollections {
public static void main(String[] args){
UniqueList ul = new UniqueList();
ul.add("Test");
ul.add("Test");
ul.add("Not a copy");
ul.add("Test");
//should only contain two things
Object[] content = ul.toObjectArray();
Out.pl("Array Content",content);
}
}
Works fine. All it does is it adds to a set if it does not have it already and there's an Arraylist that is returnable, as well as an object array.
You need to use ajax.
http://api.jquery.com/jQuery.ajax/
<code>
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
</code>
Suppose
letter= ['a','','b','c']
for i in range(len(letter)):
if letter[i] =='':
print(str(i) + ' is empty')
output- 1 is emtpy
So we can see index 1 is empty.
Or use this for different types of errors
function isError(val) {
return (!!val && typeof val === 'object')
&& ((Object.prototype.toString.call(val) === '[object Error]')
|| (typeof val.message === 'string' && typeof val.name === 'string'))
}
Finally I found answer myself. To add new icons in 2.3.2 bootstrap we have to add Font Awsome css in you file. After doing this we can override the styles with css to change the color and size.
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
CSS
.brown{color:#9b846b}
If we want change the color of icon then just add brown class and icon will turn in brown color. It also provide icon of various size.
HTML
<p><i class="icon-camera-retro icon-large brown"></i> icon-camera-retro</p> <!--brown class added-->
<p><i class="icon-camera-retro icon-2x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-3x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-4x"></i> icon-camera-retro</p>
You can also use TempVars - note '!' syntax is essential
Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
You need to use delimiters with regexes in PHP. You can use the often used /
, but PHP lets you use any matching characters, so @
and #
are popular.
If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote()
.
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});
Edit:
Since node v10.0.0
we could use fs.promises.access(...)
Example async code that checks if file exists:
async function checkFileExists(file) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false)
}
An alternative for stat might be using the new fs.access(...)
:
minified short promise function for checking:
s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
Sample usage:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
expanded Promise way:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.constants.F_OK, error => {
resolve(!error);
});
});
}
or if you wanna do it synchronously:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.constants.F_OK);
}catch(e){
flag = false;
}
return flag;
}
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
def GetNFirstItems(self):
self.dict = {f'Item{i + 1}': round(uniform(20.40, 50.50), 2) for i in range(10)}#Example Dict
self.get_items = int(input())
for self.index,self.item in zip(range(len(self.dict)),self.dict.items()):
if self.index==self.get_items:
break
else:
print(self.item,",",end="")
Unusual approach, as it gives out intense O(N) time complexity.
There are also these 'ways':
>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}
document
.getElementById("range-calculator")
.scrollIntoView({ behavior: "smooth" });
Browser support is a bit issue, but modern browsers support it.
In React Native , This worked for me
name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user
Just add textview in ScrollView
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="20dp"
android:fillViewport="true">
<TextView
android:id="@+id/txtquestion"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="@drawable/abs__dialog_full_holo_light"
android:lines="20"
android:scrollHorizontally="false"
android:scrollbars="vertical"
android:textSize="15sp" />
</ScrollView>
echo -n
works and is unlikely to ever disappear due to massive historical usage, however per recent versions of the POSIX standard, new conforming applications are "encouraged to use printf
".
Old Question but maybe it helps someone.
Go to Project settings > Time and Try dividing the fixed timestep and maximum allowed timestep by two or by four.
I had the problem that my player was able to squeeze through openings smaller than the players collider and that solved it. It also helps with stopping fast moving objects.
Or you can use std::advance
vector<int>::iterator i = L.begin();
advance(i, 2);
The construct for this is:
<c:choose>
<c:when test="${..}">...</c:when> <!-- if condition -->
<c:when test="${..}">...</c:when> <!-- else if condition -->
<c:otherwise>...</c:otherwise> <!-- else condition -->
</c:choose>
If the condition isn't expensive, I sometimes prefer to simply use two distinct <c:if
tags - it makes it easier to read.
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
ulimit -c <value>
sets the core file size limit on unix. By default, the core file size limit is 0. You can see your ulimit
values with ulimit -a
.
also, if you run your program from within gdb, it will halt your program on "segmentation violations" (SIGSEGV
, generally when you accessed a piece of memory that you hadn't allocated) or you can set breakpoints.
ddd and nemiver are front-ends for gdb which make working with it much easier for the novice.
Within vim
, look at the file format — DOS or Unix:
:set filetype=unix
:set fileformat=unix
The file will be written back without carriage return (CR, ^M) characters.
Use ave
, ddply
, dplyr
or data.table
:
df$num <- ave(df$val, df$cat, FUN = seq_along)
or:
library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))
or:
library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())
or (the most memory efficient, as it assigns by reference within DT
):
library(data.table)
DT <- data.table(df)
DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]
This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php
And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2
I haven't tried either method, but this may save you some time if it's what you need to do...
git show-ref --tags
For example, git show-ref --abbrev=7 --tags
will show you something like the following:
f727215 refs/tags/v2.16.0
56072ac refs/tags/v2.17.0
b670805 refs/tags/v2.17.1
250ed01 refs/tags/v2.17.2
The way I have done this is by using my own class loader
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);
And create the following class:
public class DynamicURLClassLoader extends URLClassLoader {
public DynamicURLClassLoader(URLClassLoader classLoader) {
super(classLoader.getURLs());
}
@Override
public void addURL(URL url) {
super.addURL(url);
}
}
Works without any reflection
If you also need to disable the drop-down (not to hide the text) then set the lengthChange
option to false
$('#datatable').dataTable( {
"lengthChange": false
} );
Works for DataTables 1.10+
Read more in the official documentation
Redirected stderr to stdout, stdout to /dev/null, and then use the backticks or $()
to capture the redirected stderr:
ERROR=$(./useless.sh 2>&1 >/dev/null)
What I found helpful is this condition that is below.
String tempEmail = "";
JTextField tf1 = new JTextField();
tf1.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent evt){
tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
}
});
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
The Enterprise Library configuration editor can help you do this. It allows you to create a base config file and then deltas for each environment. You can then merge the base config and the delta to create an environment-specific web.config. Take a look at the information here which takes you through it better than I can.
Based on the example pointed by RedEye, here's a class that needs less code :
it assumes that columns are always sorted in the same way, so it handles the
ColumnClick event sink internally :
public class ListViewColumnSorterExt : IComparer {
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int ColumnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder OrderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
private CaseInsensitiveComparer ObjectCompare;
private ListView listView;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public ListViewColumnSorterExt(ListView lv) {
listView = lv;
listView.ListViewItemSorter = this;
listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick);
// Initialize the column to '0'
ColumnToSort = 0;
// Initialize the sort order to 'none'
OrderOfSort = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
ObjectCompare = new CaseInsensitiveComparer();
}
private void listView_ColumnClick(object sender, ColumnClickEventArgs e) {
ReverseSortOrderAndSort(e.Column, (ListView)sender);
}
/// <summary>
/// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison.
/// </summary>
/// <param name="x">First object to be compared</param>
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
public int Compare(object x, object y) {
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
// Compare the two items
compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending) {
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending) {
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else {
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
private int SortColumn {
set {
ColumnToSort = value;
}
get {
return ColumnToSort;
}
}
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
private SortOrder Order {
set {
OrderOfSort = value;
}
get {
return OrderOfSort;
}
}
private void ReverseSortOrderAndSort(int column, ListView lv) {
// Determine if clicked column is already the column that is being sorted.
if (column == this.SortColumn) {
// Reverse the current sort direction for this column.
if (this.Order == SortOrder.Ascending) {
this.Order = SortOrder.Descending;
}
else {
this.Order = SortOrder.Ascending;
}
}
else {
// Set the column number that is to be sorted; default to ascending.
this.SortColumn = column;
this.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
lv.Sort();
}
}
Assuming you're happy with the sort options, the class properties are private.
The only code you need to write is :
in Form declarations
private ListViewColumnSorterExt listViewColumnSorter;
in Form constructor
listViewColumnSorter = new ListViewColumnSorterExt(ListView1);
... and you're done.
And what about a single sorter that handles multiple ListViews ?
public class MultipleListViewColumnSorter {
private List<ListViewColumnSorterExt> sorters;
public MultipleListViewColumnSorter() {
sorters = new List<ListViewColumnSorterExt>();
}
public void AddListView(ListView lv) {
sorters.Add(new ListViewColumnSorterExt(lv));
}
}
in Form declarations
private MultipleListViewColumnSorter listViewSorter = new MultipleListViewColumnSorter();
in Form constructor
listViewSorter.AddListView(ListView1);
listViewSorter.AddListView(ListView2);
// ... and so on ...
For people getting the windows store window when writing python in the console, all you have to do is go to configuration -> Manage app execution aliases
and disable the toggles that say python.
then, add the following folders to the PATH.
C:\Users\alber\AppData\Local\Programs\Python\Python39\
C:\Users\alber\AppData\Local\Programs\Python\Python39\Scripts\
Without any configuration, you can simply issue the following command (modifying myusername
and mydomain
with your own information):
cntlm -u myusername -d mydomain -H
or
cntlm -u myusername@mydomain -H
It will ask you the password of myusername
and will give you the following output:
PassLM 1AD35398BE6565DDB5C4EF70C0593492
PassNT 77B9081511704EE852F94227CF48A793
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC # Only for user 'myusername', domain 'mydomain'
Then create the file cntlm.ini
(or cntlm.conf
on Linux using default path) with the following content (replacing your myusername
, mydomain
and A8FC9092D566461E6BEA971931EF1AEC
with your information and the result of the previous command):
Username myusername
Domain mydomain
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:5865
Gateway yes
SOCKS5Proxy 5866
Auth NTLMv2
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC
Then you will have a local open proxy on local port 5865
and another one understanding SOCKS5 protocol at local port 5866
.
You Should uninstall the existed python,then download new version.
I use structs for packing or unpacking any sort of binary communication format. That includes reading or writing to disk, DirectX vertex lists, network protocols, or dealing with encrypted/compressed data.
The three guidelines you list haven't been useful for me in this context. When I need to write out four hundred bytes of stuff in a Particular Order, I'm gonna define a four-hundred-byte struct, and I'm gonna fill it with whatever unrelated values it's supposed to have, and I'm going to set it up whatever way makes the most sense at the time. (Okay, four hundred bytes would be pretty strange-- but back when I was writing Excel files for a living, I was dealing with structs of up to about forty bytes all over, because that's how big some of the BIFF records ARE.)
Comparable lets a class implement its own comparison:
By comparison, Comparator is an external comparison:
In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.
As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(
Comparable<Object>
lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.Comparable<Itself>
is very strict on the contrary.Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).
v1
, v2
.v3
.v4
first = [1, 2, 3, 1]
second = [4, 5, 6]
output: [5, 7, 9, 1]
If you have an unknown number of lists of the same length, you can use the function v5
.
v6
- The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y)
is equivalent to the expression x+y
.
v7
- Assuming both lists first
and second
have same length, you do not need zip or anything else.
################
first = [1, 2, 3]
second = [4, 5, 6]
####### v1 ########
third1 = [sum(i) for i in zip(first,second)]
####### v2 ########
third2 = [x + y for x, y in zip(first, second)]
####### v3 ########
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
third3 = [sum(x) for x in zip(*lists_of_lists)]
####### v4 ########
from itertools import zip_longest
third4 = list(map(sum, zip_longest(first, second, fillvalue=0)))
####### v5 ########
def sum_lists(*args):
return list(map(sum, zip(*args)))
third5 = sum_lists(first, second)
####### v6 ########
import operator
third6 = list(map(operator.add, first,second))
####### v7 ########
third7 =[first[i]+second[i] for i in range(len(first))]
####### v(i) ########
print(third1) # [5, 7, 9]
print(third2) # [5, 7, 9]
print(third3) # [5, 7, 9]
print(third4) # [5, 7, 9]
print(third5) # [5, 7, 9]
print(third6) # [5, 7, 9]
print(third7) # [5, 7, 9]
In VB
: This should work
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
In C#
it would be (as per comment of Ala)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
The Operating System is a generic name given to all of the elements (user interface, libraries, resources) which make up the system as a whole.
The kernel is "brain" of the operating system, which controls everything from access to the hard disk to memory management. Whenever you want to do anything, it goes though the kernel.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
I'm not sure what you want to accomplish, but in this case just adding width: 100%;
to your ul#slideshow li
will do the trick.
The img
tags are inline-block elements. This means that they flow inline like text, but also have a width and height like block elements. In your css there are two text-align: center;
rules applied to the <body>
and to the #slideshowWrapper
(which is redundant btw) this makes all inline and inline-block child elements to be centered in their closest block elements, in your code these are li
tags. All block elements have width: 100%
if they are the static flow (position: static;
), which is default. The problem is that when you tell li
tags to be position: absolute;
, you take them out of normal static flow, and this causes them to shrink their size to just fit their inner content, in other words they kind of "lose" their width: 100%
property.
df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))
Just using base R
POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString()
and Object.equals()
.
Java Beans : See Wiki link.
Normal Class : Any java Class.
Also, if you use Tampermonkey, you can add a script that will add preview with http://htmlpreview.github.com/
button into actions menu beside 'raw', 'blame' and 'history' buttons.
Script like this one: https://gist.github.com/vanyakosmos/83ba165b288af32cf85e2cac8f02ce6d
Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx
Try add -H tcp://0.0.0.0:2375
(at end of Execstart
line) instead of -H 0.0.0.0:2375
.
It looks like {{ data.0 }}
. See Variables and lookups.
import sys
def is_power2(x):
return x > 0 and ((x & (x - 1)) == 0)
def find_nearest_power2(x):
if x <= 0:
raise ValueError("invalid input")
if is_power2(x):
return x
else:
bits = get_bits(x)
upper = 1 << (bits)
lower = 1 << (bits - 1)
mid = (upper + lower) // 2
if (x - mid) > 0:
return upper
else:
return lower
def get_bits(x):
"""return number of bits in binary representation"""
if x < 0:
raise ValueError("invalid input: input should be positive integer")
count = 0
while (x != 0):
try:
x = x >> 1
except TypeError as error:
print(error, "input should be of type integer")
sys.exit(1)
count += 1
return count
UPDATE test SET log = REPLACE(REPLACE(log, '\r', ''), '\n', '');
worked for me.
while its similar, it'll also get rid of \r\n
No, this is not possible. In documents that make use of CSS, an inline style
attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:
The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:
declaration-list : S* declaration? [ ';' S* declaration? ]* ;
Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.
Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style
attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).
Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important
notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.
Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.
I'm rusty on SQL but I think you could use select as to make your own temporary query columns.
select field1, field2, 'example' as newfield from table1
That would only exist in your query results, of course. You're not actually modifying the table.
I think you might be able to use the ExpandProperty
parameter of Select-Object
.
For example, to get the list of the current directory and just have the Name property displayed, one would do the following:
ls | select -Property Name
This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm
).
ls | select -Property Name | gm
So, to expand the object to be that of the type of property you're looking at, you can do the following:
ls | select -ExpandProperty Name
In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:
$objects = ls | select -ExpandProperty Name
You MUST add below part to enable NameVirtualHost
functionality with given IP.
NameVirtualHost IP_Address:443
Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.
Example of parsing using indexOf
to calculate the position of a string in another string:
String s="What a Beautiful day!";
int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8
paresInt
essentially converts a String
to a Integer
.
String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);
Output:
Constructor method: 9876543 parseInt() method: 9876543
The second one is fastest. Using strlen
will be close if the string is indeed empty, but strlen
will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.
As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
For MSVC you can use the linker.
link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll
foo.pdb needs to be available to get symbols
I am using eclipse and I was stuck on not being able to read files because of a "file not found exception". What I did to solve this problem was I moved the file to the root of my project. Hope this helps.
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
Reducing the image size before output results in something that looks sharper, in my case:
convert -density 300 a.pdf -resize 25% a.png
If you only want the first element of a set (and you are certain there is at least one element) you can do the following:
<c:choose>
<c:when test="${dealership.administeredBy.size() == 1}">
Hello ${dealership.administeredBy.iterator().next().firstName},<br/>
</c:when>
<c:when test="${dealership.administeredBy.size() > 1}">
Hello Administrators,<br/>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
I had same problem and found that you can just apply the [JsonIgnore]
attribute to the navigation property you don't want to be serialised. It will still serialise both the parent and child entities but just avoids the self referencing loop.
This calls exactly for the using the Maven JAR Plugin
For example, if you want to exclude everything under src/test/resources/
from the final jar, put this:
<build>
<plugins>
<!-- configure JAR build -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<excludes>
<exclude>src/test/resources/**</exclude>
</excludes>
</configuration>
</plugin>
...
Files under src/test/resources/
will still be available on class-path, they just won't be in resulting JAR.
For current datetime, you can use now() function in postgresql insert query.
You can also refer following link.
insert statement in postgres for data type timestamp without time zone NOT NULL,.
Probably, a better and more functional way is to wrap exceptions and propagate them further in the stream. Take a look at the Try type of Vavr for example.
Example:
interface CheckedFunction<I, O> {
O apply(I i) throws Exception; }
static <I, O> Function<I, O> unchecked(CheckedFunction<I, O> f) {
return i -> {
try {
return f.apply(i);
} catch(Exception ex) {
throw new RuntimeException(ex);
}
} }
fileNamesToRead.map(unchecked(file -> Files.readAllLines(file)))
OR
@SuppressWarnings("unchecked")
private static <T, E extends Exception> T throwUnchecked(Exception e) throws E {
throw (E) e;
}
static <I, O> Function<I, O> unchecked(CheckedFunction<I, O> f) {
return arg -> {
try {
return f.apply(arg);
} catch(Exception ex) {
return throwUnchecked(ex);
}
};
}
2nd implementation avoids wrapping the exception in a RuntimeException
. throwUnchecked
works because almost always all generic exceptions are treated as unchecked in java.
An alternative is to normalize the data. Below are three sets of data with widely varying ranges. In the top chart you can see the variation in one series clearly, in another not so clearly, and the third not at all.
In the second range, I have adjusted the series names to include the data range, using this formula in cell C15 and copying it to D15:E15
=C2&" ("&MIN(C3:C9)&" to "&MAX(C3:C9)&")"
I have normalized the values in the data range using this formula in C15 and copying it to the entire range C16:E22
=100*(C3-MIN(C$3:C$9))/(MAX(C$3:C$9)-MIN(C$3:C$9))
In the second chart, you can see a pattern: all series have a low in January, rising to a high in March, and dropping to medium-low value in June or July.
You can modify the normalizing formula however you need:
=100*C3/MAX(C$3:C$9)
=C3/MAX(C$3:C$9)
=(C3-AVERAGE(C$3:C$9))/STDEV(C$3:C$9)
etc.
Or you can just create your own MediaTypeFormatter
. I use this for text/html
. If you add text/plain
to it, it'll work for you too:
public class TextMediaTypeFormatter : MediaTypeFormatter
{
public TextMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
}
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
using (var streamReader = new StreamReader(readStream))
{
return await streamReader.ReadToEndAsync();
}
}
public override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override bool CanWriteType(Type type)
{
return false;
}
}
Finally you have to assign this to the HttpMethodContext.ResponseFormatter
property.
$url ="https://yourFile.pdf";
$content = file_get_contents($url);
header('Content-Type: application/pdf');
header('Content-Length: ' . strlen($content));
header('Content-Disposition: inline; filename="YourFileName.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
die($content);
Tested and works fine. If you want the file to download instead, replace
Content-Disposition: inline
with
Content-Disposition: attachment
1) see if the xml files in the Package Explorer tree have an error-icon if they do, fix errors and R-class will be generated.
example hint: FILL_PARENT was renamed MATCH_PARENT in API Level 8; so if you're targeting platform 2.1 (api 7), change all occurences back to "fill_parent"
2) if you added "import android.R;" trying to do a quick-fix, remove that line
table {
border-spacing: 4px;
color: #000;
background: #ccc;
}
td {
padding-left: 4px;
}
$ python -c "import itertools; a=[2,3,5,7,11]; print sum([list(itertools.combinations(a, i)) for i in range(len(a)+1)], [])"
[(), (2,), (3,), (5,), (7,), (11,), (2, 3), (2, 5), (2, 7), (2, 11), (3, 5), (3, 7), (3, 11), (5, 7), (5, 11), (7, 11), (2, 3, 5), (2, 3, 7), (2, 3, 11), (2, 5, 7), (2, 5, 11), (2, 7, 11), (3, 5, 7), (3, 5, 11), (3, 7, 11), (5, 7, 11), (2, 3, 5, 7), (2, 3, 5, 11), (2, 3, 7, 11), (2, 5, 7, 11), (3, 5, 7, 11), (2, 3, 5, 7, 11)]
Pandas: How to replace NaN (nan
) values with the average (mean), median or other statistics of one column
Say your DataFrame is df
and you have one column called nr_items
. This is: df['nr_items']
If you want to replace the NaN
values of your column df['nr_items']
with the mean of the column:
Use method .fillna()
:
mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)
I have created a new df
column called nr_item_ave
to store the new column with the NaN
values replaced by the mean
value of the column.
You should be careful when using the mean
. If you have outliers is more recommendable to use the median
Here is a more straightforward way if all you want to do is save it as a file:
import urllib
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
The second argument is the local path where the file should be saved.
As SergO suggested the code below should work with Python 3.
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
As per updated version(Xcode 8.3.3) I saw that below resolution are required for all fields of AppIcon
sets.
40x40
58x58
60x60
80x80
87x87
120x120
180x180
It comes with hdpi, xhdpi, xxhdpi etc. Hope it will helps others.
Edited to 120x120
As per the question, i have listed the answers in javascript
By Selecting TagName
document.getElementsByTagName('textarea')[0].style.resize = "none";
By Selecting Id
document.getElementById('textArea').style.resize = "none";
This should work in most of the cases.
/^[\d]*[a-z_][a-z\d_]*$/gi
And by most I mean,
abcd True
abcd12 True
ab12cd True
12abcd True
1234 False
^ ... $
- match the pattern starting and ending with[\d]*
- match zero or more digits[a-z_]
- match an alphabet or underscore[a-z\d_]*
- match an alphabet or digit or underscore/gi
- match globally across the string and case-insensitiveThe answer is to set the
autoResize:true
property when creating the dialog. In order for this to work you cannot set any height for the dialog. So if you set a fixed height in pixels for the dialog in its creator method or via any style the autoResize property will not work.
Try these
Q1: this notice means $varname is not defined at current scope of the script.
Q2: Use of isset(), empty() conditions before using any suspicious variable works well.
// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';
// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}
Or, as a quick and dirty solution:
// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);
Note about sessions:
When using sessions, session_start();
is required to be placed inside all files using sessions.
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'
When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift
sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift
Create new Maven file with path as classpath and goal as class name
The best post I've seen on the topic was written by Daniel Olszewski:
Although it might be tempting to consider Optional for not mandatory method parameters, such a solution pale in comparison with other possible alternatives. To illustrate the problem, examine the following constructor declaration:
public SystemMessage(String title, String content, Optional<Attachment> attachment) { // assigning field values }
At first glance it may look as a right design decision. After all, we explicitly marked the attachment parameter as optional. However, as for calling the constructor, client code can become a little bit clumsy.
SystemMessage withoutAttachment = new SystemMessage("title", "content", Optional.empty()); Attachment attachment = new Attachment(); SystemMessage withAttachment = new SystemMessage("title", "content", Optional.ofNullable(attachment));
Instead of providing clarity, the factory methods of the Optional class only distract the reader. Note there’s only one optional parameter, but imagine having two or three. Uncle Bob definitely wouldn’t be proud of such code
When a method can accept optional parameters, it’s preferable to adopt the well-proven approach and design such case using method overloading. In the example of the SystemMessage class, declaring two separate constructors are superior to using Optional.
public SystemMessage(String title, String content) { this(title, content, null); } public SystemMessage(String title, String content, Attachment attachment) { // assigning field values }
That change makes client code much simpler and easier to read.
SystemMessage withoutAttachment = new SystemMessage("title", "content"); Attachment attachment = new Attachment(); SystemMessage withAttachment = new SystemMessage("title", "content", attachment);
Use this :
List<String> splitString = (List<String>) Arrays.asList(jobtype.split(","));
Simple, with CSS:
iframe{
width: 100%;
max-width: 800px /*this can be anything you wish, to show, as default size*/
}
Please, note: But it won't make the content inside it responsive!
2nd EDIT:: There are two types of responsive iframes, depending on their inner content:
one that is when the inside of the iframe only contains a video or an image or many vertically positioned, for which the above two-rows of CSS code is almost completely enough, and the aspect ratio has meaning...
and the other is the:
contact/registration form type of content, where not the aspect ratio do we have to keep, but to prevent the scrollbar from appearing, and the content under-flowing the container. On mobile you don't see the scrollbar, you just scroll until you see the content (of the iframe). Of course you give it at least some kind of height
, to make the content height adapt to the vertical space occurring on a narrower screen - with media queries, like, for example:
@media (max-width: 640px){
iframe{
height: 1200px /*whatever you need, to make the scrollbar hide on testing, and the content of the iframe reveal (on mobile/phone or other target devices) */
}
}
@media (max-width: 420px){
iframe{
height: 1600px /*and so on until and as needed */
}
}
A really common way to see a clear example of the use of the three dots it is present in one of the most famous methods in android AsyncTask ( that today is not used too much because of RXJAVA, not to mention the Google Architecture components), you can find thousands of examples searching for this term, and the best way to understand and never forget anymore the meaning of the three dots is that they express a ...doubt... just like in the common language. Namely it is not clear the number of parameters that have to be passed, could be 0, could be 1 could be more( an array)...
I'm new to PyCharm (using 2018.3.4 CE) and Python so I rotely tried to follow each of the above suggestions to access the PIL (Pillow) package which I knew was in system-site-packages. None worked. I was about to give up for the night when I happened to notice the venv/pyvenv.cfg file under my project in the Project Explorer window. I found the line "include-system-site-packages = false" in that file and so I changed it to "true". Problem solved.
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
Normally HEAD
points to a branch. When it is not pointing to a branch instead when it points to a commit hash like 69e51
it means you have a detached HEAD. You need to point it two a branch to fix the issue. You can do two things to fix it.
hash
HEAD must point to a branch, not a commit hash is the golden rule.
Press CTRL+F11
to rotate the screen.
try using %%
to print % sign .
If you are using Homebrew to install [email protected], the location is
/usr/local/Homebrew/var/mysql
I don't know if the location is the same for other versions.
If you really just want to pick "any" object from the Set
, without any guarantees on the randomness, the easiest is taking the first returned by the iterator.
Set<Integer> s = ...
Iterator<Integer> it = s.iterator();
if(it.hasNext()){
Integer i = it.next();
// i is a "random" object from set
}
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK's programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory "\bin" (where denotes the JDK installed directory, e.g., C:\Program Files\Java\jdk1.8.0_xx). You need to include the "\bin" directory in the PATH.
To edit the PATH environment variable in Windows XP/Vista/7/8:
Control Panel ? System ? Advanced system settings
Switch to "Advanced" tab ? Environment Variables
In "System Variables", scroll down to select "PATH" ? Edit
(( now read the following 3 times before proceeding, THERE IS NO UNDO ))
In "Variable value" field, INSERT "c:\Program Files\Java\jdk1.8.0_xx\bin" (Replace xx with the upgrade number and VERIFY that this is your JDK's binary directory!!!) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK's binary directory from the rest of the existing directories. DO NOT DELETE any existing entries; otherwise, some existing applications may not run.
Variable name : PATH
Variable value : c:\Program Files\Java\jdk1.8.0_xx\bin;[existing entries...]
If you having a common class that is applied to many elements you can create a custom directive that will add that class like ng-show/ng-hide.
This directive will add the class 'active' to the button if it's clicked
module.directive('ngActive', ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
$animate[value ? 'addClass' : 'removeClass'](element, 'active');
});
};
}]);
More info
As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8
method, contains this:
public ByteVector putUTF8(final String stringValue) {
int charLength = stringValue.length();
if (charLength > 65535) {
// If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
throw new IllegalArgumentException("UTF8 string too large");
}
for (int i = 0; i < charLength; ++i) {
char charValue = stringValue.charAt(i);
if (charValue >= '\u0001' && charValue <= '\u007F') {
// Unicode code-point encoding in utf-8 fits in 1 byte.
currentData[currentLength++] = (byte) charValue;
} else {
// doesnt fit in 1 byte.
length = currentLength;
return encodeUtf8(stringValue, i, 65535);
}
}
...
}
But when code-point mapping > 1byte, it calls encodeUTF8
method:
final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
int charLength = stringValue.length();
int byteLength = offset;
for (int i = offset; i < charLength; ++i) {
char charValue = stringValue.charAt(i);
if (charValue >= 0x0001 && charValue <= 0x007F) {
byteLength++;
} else if (charValue <= 0x07FF) {
byteLength += 2;
} else {
byteLength += 3;
}
}
...
}
In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char
count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.
Check your servers error log, typically /var/log/apache2/error.log
.
As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:
var text = document.getElementsByName("textbox1").value;
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
You should be okay to just take the height property out of the CSS.