Using ' and " at the same time works great for me (Windows 10, python 3)
import os
os.system('"some cmd command here"')
for example to open my web browser I can use this:
os.system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"')
(Edit) for an easier way to open your browser I can use this:
import webbrowser
webbrowser.open('website or leave it alone if you only want to open the
browser')
Is to do with IPv6
All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx
Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...
A simple fix would be to use the following CSS property.
input[type=radio]:checked{
background: \*colour*\;
border-radius: 15px;
border: 4px solid #dfdfdf;
}
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
public static String currencyFormat(BigDecimal n) {
return NumberFormat.getCurrencyInstance().format(n);
}
It will use your JVM’s current default Locale
to choose your currency symbol. Or you can specify a Locale
.
NumberFormat.getInstance(Locale.US)
For more info, see NumberFormat
class.
$.fn.outerHtml = function(){
if (this.length) {
var div = $('<div style="display:none"></div>');
var clone =
$(this[0].cloneNode(false)).html(this.html()).appendTo(div);
var outer = div.html();
div.remove();
return outer;
}
else {
return null;
}
};
from http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010
->getSingleScalarResult() will return a single value, instead of an array.
For Angular version 6+
from @docs
Represents options to configure the router.
interface ExtraOptions {
enableTracing?: boolean
useHash?: boolean
initialNavigation?: InitialNavigation
errorHandler?: ErrorHandler
preloadingStrategy?: any
onSameUrlNavigation?: 'reload' | 'ignore'
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
anchorScrolling?: 'disabled' | 'enabled'
scrollOffset?: [number, number] | (() => [number, number])
paramsInheritanceStrategy?: 'emptyOnly' | 'always'
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
urlUpdateStrategy?: 'deferred' | 'eager'
relativeLinkResolution?: 'legacy' | 'corrected'
}
One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
in
Example:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'|'top'
});
And if one requires to manually control the scrolling, No need to use window.scroll(0,0)
Instead from Angular V6 common package has introduced ViewPortScoller
.
abstract class ViewportScroller {
static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
abstract setOffset(offset: [number, number] | (() => [number, number])): void
abstract getScrollPosition(): [number, number]
abstract scrollToPosition(position: [number, number]): void
abstract scrollToAnchor(anchor: string): void
abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}
Usage is pretty Straightforward Example:
import { Router } from '@angular/router';
import { ViewportScroller } from '@angular/common'; //import
export class RouteService {
private applicationInitialRoutes: Routes;
constructor(
private router: Router;
private viewPortScroller: ViewportScroller//inject
)
{
this.router.events.pipe(
filter(event => event instanceof NavigationEnd))
.subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}
Create A .htaccess file in your root DIR and paste the below code. That's it :P
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]
RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
_x000D_
I'd say
concat('This is line 1.', 0xd0a, 'This is line 2.')
or
concat(N'This is line 1.', 0xd000a, N'This is line 2.')
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
It's bad in the sense that structured programming constructs are preferred to (the somewhat unstructured) break and continue statements. They are, by comparison, preferred to "goto" according to this principle.
I'd always recommend making your code as structured as possible... although, as Jon Skeet points out, don't make it more structured than that!
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.
$('div.alldivs :first-child');
Or you can just refer to the id directly:
$('#div1');
As suggested, you might be better of using the child selector:
$('div.alldivs > div:first-child')
If you dont have to use first-child
, you could use :first
as also suggested, or $('div.alldivs').children(0)
.
You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.
.ui-corner-all
{
border-radius: 0px !important;
}
There is another way if all you want is the text up to the first line feed:
x='some
thing'
y=${x%$'\n'*}
After that y
will contain some
and nothing else (no line feed).
What is happening here?
We perform a parameter expansion substring removal (${PARAMETER%PATTERN}
) for the shortest match up to the first ANSI C line feed ($'\n'
) and drop everything that follows (*
).
In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.
Create a temp file first.
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;
I had the same problem with a dummy app that happened to have the same name as my final app and couldn't publish because the App Name is already in use
To fix it, instead of deleting it(which you can't) I just changed the name of the dummy app to something random and hit SAVE. Then I was able to add the new app with the proper name
To avoid including a large framework, I think a simple homemade class can do the trick.
Example of class to handle named parameters:
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String sql) throws SQLException {
int pos;
while((pos = sql.indexOf(":")) != -1) {
int end = sql.substring(pos).indexOf(" ");
if (end == -1)
end = sql.length();
else
end += pos;
fields.add(sql.substring(pos+1,end));
sql = sql.substring(0, pos) + "?" + sql.substring(end);
}
prepStmt = conn.prepareStatement(sql);
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setInt(String name, int value) throws SQLException {
prepStmt.setInt(getIndex(name), value);
}
private int getIndex(String name) {
return fields.indexOf(name)+1;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}
Example of calling the class:
String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();
Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.
After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json))
;
http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef
"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.
/**
* @param filePath
* @param fs
* @return list of absolute file path present in given path
* @throws FileNotFoundException
* @throws IOException
*/
public static List<String> getAllFilePath(Path filePath, FileSystem fs) throws FileNotFoundException, IOException {
List<String> fileList = new ArrayList<String>();
FileStatus[] fileStatus = fs.listStatus(filePath);
for (FileStatus fileStat : fileStatus) {
if (fileStat.isDirectory()) {
fileList.addAll(getAllFilePath(fileStat.getPath(), fs));
} else {
fileList.add(fileStat.getPath().toString());
}
}
return fileList;
}
Quick Example : Suppose you have the following file structure:
a -> b
-> c -> d
-> e
-> d -> f
Using the code above, you get:
a/b
a/c/d
a/c/e
a/d/f
If you want only the leaf (i.e. fileNames), use the following code in else
block :
...
} else {
String fileName = fileStat.getPath().toString();
fileList.add(fileName.substring(fileName.lastIndexOf("/") + 1));
}
This will give:
b
d
e
f
From the Ansible documentation:
Delegation This isn’t actually rolling update specific but comes up frequently in those cases.
If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:
---
- hosts: webservers
serial: 5
tasks:
- name: take out of load balancer pool
command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
delegate_to: 127.0.0.1
- name: actual steps would go here
yum:
name: acme-web-stack
state: latest
- name: add back to load balancer pool
command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
delegate_to: 127.0.0.1
These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:
---
# ...
tasks:
- name: take out of load balancer pool
local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}
# ...
- name: add back to load balancer pool
local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}
A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is an example:
---
# ...
tasks:
- name: recursively copy files from management server to target
local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/
Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync will need to ask for a passphrase.
In your comment on @Kenneth's answer you're saying that ReadAsStringAsync()
is returning empty string.
That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
public static string GetRequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
My minimalistic solution should work for random numbers in range [min, max)
. Use srand(time(NULL))
before invoking the function.
int range_rand(int min_num, int max_num) {
if (min_num >= max_num) {
fprintf(stderr, "min_num is greater or equal than max_num!\n");
}
return min_num + (rand() % (max_num - min_num));
}
Had a good look at many of these supposed answers...
...and bupkis after scouring Stack Overflow as well as other sites for a regex that matches any string with no starting or trailing white-space and only a single space between strictly alpha character words.
^[a-zA-Z]+[(?<=\d\s]([a-zA-Z]+\s)*[a-zA-Z]+$
Thus easily modified to alphanumeric:
^[a-zA-Z0-9]+[(?<=\d\s]([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$
(This does not match single words but just use a switch/if-else with a simple ^[a-zA-Z0-9]+$
if you need to catch single words in addition.)
enjoy :D
You need a table variable:
declare @values table
(
Value varchar(1000)
)
insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')
select blah
from foo
where myField in (select value from @values)
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
Key/index : A key is an aspect of a LOGICAL database design, an index is an aspect of a PHYSICAL database design. A key corresponds to an integrity constraint, an index is a technique of physically recording values that can be usefully applied when enforcing those constraints.
Primary/foreign : A "primary" key is a set of attributes whose values must form a combination that is unique in the entire table. There can be more than one such set (> 1 key), and the word "primary" is a remnant from the earlier days when the designer was then forced to choose one of those multiple keys as being "the most important/relevant one". The reason for this was primarily in combination with foreign keys :
Like a "primary" key, a "foreign" key is also a set of attributes. The values of these attributes must form a combination that is an existing primary key value in the referenced table. I don't know exactly how strict this rule still applies in SQL today. The terminology has remained anyway.
Unique : keyword used to indicate that an index cannot accept duplicate entries. Unique indexes are obviously an excellent means to enforce primary keys. To the extent that the word 'unique' is used in contexts of LOGICAL design, it is superfluous, sloppy, unnecessary and confusing. Keys (primary keys, that is) are unique by definition.
Below are provided steps to fix your issue.
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
try
cat ~/.mysql_history
this will show you all mysql commands ran on the system
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
You can use Random.Next(int maxValue)
:
Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.
var r = new Random();
// print random integer >= 0 and < 100
Console.WriteLine(r.Next(100));
For this case however you could use Random.Next(int minValue, int maxValue)
, like this:
// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);
I just ran into this problem. When I ran npm start
, I got a bunch of duplicate identifier errors.
SOLUTION:
From the project root folder run:
rm -r typings
typings install
npm start
and everything works fine.
There's no need to do this in two commits, you can add the file and mark it executable in a single commit:
C:\Temp\TestRepo>touch foo.sh
C:\Temp\TestRepo>git add foo.sh
C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:
C:\Temp\TestRepo>git update-index --chmod=+x foo.sh
C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
And now the file is mode 0755 (executable).
C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100755 foo.sh
And now we have a single commit with a single executable file.
You have to disable the sandbox for Groovy in your job configuration.
Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178
Over a year later... if what you need is get the auto generated id of a table, you can just
SELECT @ReportOptionId = SCOPE_IDENTITY()
Otherwise, it seems like you are stuck with using a table.
Assuming that EXIT_CODE is referring to System . exit
( exit_code ) then you could do
enum ExitCode
{
NORMAL_SHUTDOWN ( 0 ) , EMERGENCY_SHUTDOWN ( 10 ) , OUT_OF_MEMORY ( 20 ) , WHATEVER ( 30 ) ;
private int value ;
ExitCode ( int value )
{
this . value = value ;
}
public void exit ( )
{
System . exit ( value ) ;
}
}
Then you can put the following at appropriate spots in your code
ExitCode . NORMAL_SHUTDOWN . exit ( ) '
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
r = ((double) rand() / (RAND_MAX)) + 1;
Simple solution for standard observablecollection that I've used:
DO NOT ADD to your property OR CHANGE it's inner items DIRECTLY, instead, create some temp collection like this
ObservableCollection<EntityViewModel> tmpList= new ObservableCollection<EntityViewModel>();
and add items or make changes to tmpList,
tmpList.Add(new EntityViewModel(){IsRowChecked=false}); //Example
tmpList[0].IsRowChecked= true; //Example
...
then pass it to your actual property by assignment.
ContentList=tmpList;
this will change whole property which causes notice the INotifyPropertyChanged as you need.
Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _
underscores.
Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }
EDIT :
Optionally, the Where-Object
command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:
To skip any document files
Dir |
Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
To process only directories (pre-3.0 version)
Dir |
Where-Object { $_.Mode -match "^d" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
PowerShell v3.0 introduced new Dir
flags. You can also use Dir -Directory
there.
To skip any files already containing an underscore (or some other character)
Dir |
Where-Object { -not $_.Name.Contains("_") } |
Rename-Item -NewName { $_.Name -replace " ","_" }
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);
I had solved it on iPad. Try, if it works also on OSX.
body, html { position: fixed; }
Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).
In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content>
can be still scrollable.
This is for Android Studio 1.0.2(Windows7). Right click on the project on project bar and delete.
Then remove the project folder from within your user folder under 'AndroidStudioProject' using Windows explorer.
Close the studio and relaunch you will presented with welcome screen. Click on deleted project from left side pane then select the option to remove from the list. Done!
C# 1.0 with Visual Studio.NET
C# 2.0 with Visual Studio 2005
C# 3.0 with Visual Studio 2008
C# 4.0 with Visual Studio 2010
C# 5.0 with Visual Studio 2012
C# 6.0 with Visual Studio 2015
C# 7.0 with Visual Studio 2017
C# 8.0 with Visual Studio 2019
The following should work
$ad->getcodes()->distinct()->count('pid');
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
Use max()
:
Using itemgetter()
:
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis,key=itemgetter(1))[0] #faster solution
Out[82]: 361
using lambda
:
In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)
In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
timeit
comparison:
In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
Create a base class for your ViewModels
with the following constructor code which will apply the DefaultValueAttributes
when any inheriting model is created.
public abstract class BaseViewModel
{
protected BaseViewModel()
{
// apply any DefaultValueAttribute settings to their properties
var propertyInfos = this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
if (attributes.Any())
{
var attribute = (DefaultValueAttribute) attributes[0];
propertyInfo.SetValue(this, attribute.Value, null);
}
}
}
}
And inherit from this in your ViewModels:
public class SearchModel : BaseViewModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}
Add Label (a QLabel) to the dialog where you want to show the image. This QLabel will actually display the image. Resize it to the size you want the image to appear.
Add the image to your resources in your project.
Now go into QLabel properties and select the image you added to resources for pixmap property. Make sure to check the next property scaledContents to shrink the image in the size you want to see it.
That's all, the image will now show up.
var listItems= "";
var jsonData = jsonObj.d;
for (var i = 0; i < jsonData.Table.length; i++){
listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
$("#<%=DLState.ClientID%>").html(listItems);
Example
<html>
<head></head>
<body>
<select id="DLState">
</select>
</body>
</html>
/*javascript*/
var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
{"stateid" : "3","statename" : "Karnataka"},
{"stateid" : "4","statename" : "Andaman and Nicobar"},
{"stateid" : "5","statename" : "Andhra Pradesh"},
{"stateid" : "6","statename" : "Arunachal Pradesh"}]}
$(document).ready(function(){
var listItems= "";
for (var i = 0; i < jsonList.Table.length; i++){
listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
}
$("#DLState").html(listItems);
});
You are probably behind a firewall. Try cloning via https – that has a higher chance of not being blocked:
git clone https://github.com/angular/angular-phonecat.git
IE8 has much improved developer tools. Until then it's best to write javascript for firefox first and then debug IE using alert() statements.
String-Builder :
int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
System.out.print(sb);
// Prints "One=1, Colour=red" followed by an ASCII newline.
String-Buffer
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.
edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.
I'm not quite fond of Kuhess's accepted answer as the sleep 5
seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe
.
I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/
within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.
As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.
This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh
with this content:
mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql
and this Dockerfile copying that script:
FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/
The easiest way to do this, as noted by Umar is, for example
mysql> SET GLOBAL time_zone = 'America/New_York';
Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:
#1298 - Unknown or incorrect time zone
If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:
mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p
Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your
mysql> SET GLOBAL time_zone = timezone;
if you are using ES6, the you should use the Template literals.
//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`
read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
You can't but you can do it anyway like this. I needed this for jQuery-File-Upload
import json
# get this object
from flask import Response
#example data:
js = [ { "name" : filename, "size" : st.st_size ,
"url" : url_for('show', filename=filename)} ]
#then do this
return Response(json.dumps(js), mimetype='application/json')
I think you can bring specific access to user and command with visudo
something like this:
nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt
and with php:
@exec("sudo /path/to/osascript myscript.scpt ");
supposing nobody
user is running apache.
My issue was due to version conflict. I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
If you don't know the numbers of the clusters k to provide as parameter to k-means so there are four ways to find it automaticaly:
G-means algortithm: it discovers the number of clusters automatically using a statistical test to decide whether to split a k-means center into two. This algorithm takes a hierarchical approach to detect the number of clusters, based on a statistical test for the hypothesis that a subset of data follows a Gaussian distribution (continuous function which approximates the exact binomial distribution of events), and if not it splits the cluster. It starts with a small number of centers, say one cluster only (k=1), then the algorithm splits it into two centers (k=2) and splits each of these two centers again (k=4), having four centers in total. If G-means does not accept these four centers then the answer is the previous step: two centers in this case (k=2). This is the number of clusters your dataset will be divided into. G-means is very useful when you do not have an estimation of the number of clusters you will get after grouping your instances. Notice that an inconvenient choice for the "k" parameter might give you wrong results. The parallel version of g-means is called p-means. G-means sources: source 1 source 2 source 3
x-means: a new algorithm that efficiently, searches the space of cluster locations and number of clusters to optimize the Bayesian Information Criterion (BIC) or the Akaike Information Criterion (AIC) measure. This version of k-means finds the number k and also accelerates k-means.
Online k-means or Streaming k-means: it permits to execute k-means by scanning the whole data once and it finds automaticaly the optimal number of k. Spark implements it.
MeanShift algorithm: it is a nonparametric clustering technique which does not require prior knowledge of the number of clusters, and does not constrain the shape of the clusters. Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. Sources: source1, source2, source3
This is a quick fix and can be even more optimized but it will work fine. This code will replace all non empty tags with "" and strips all html tags form a given input text .You can run it using ./file.py input output
#!/usr/bin/python
import sys
def replace(strng,replaceText):
rpl = 0
while rpl > -1:
rpl = strng.find(replaceText)
if rpl != -1:
strng = strng[0:rpl] + strng[rpl + len(replaceText):]
return strng
lessThanPos = -1
count = 0
listOf = []
try:
#write File
writeto = open(sys.argv[2],'w')
#read file and store it in list
f = open(sys.argv[1],'r')
for readLine in f.readlines():
listOf.append(readLine)
f.close()
#remove all tags
for line in listOf:
count = 0;
lessThanPos = -1
lineTemp = line
for char in lineTemp:
if char == "<":
lessThanPos = count
if char == ">":
if lessThanPos > -1:
if line[lessThanPos:count + 1] != '<>':
lineTemp = replace(lineTemp,line[lessThanPos:count + 1])
lessThanPos = -1
count = count + 1
lineTemp = lineTemp.replace("<","<")
lineTemp = lineTemp.replace(">",">")
writeto.write(lineTemp)
writeto.close()
print "Write To --- >" , sys.argv[2]
except:
print "Help: invalid arguments or exception"
print "Usage : ",sys.argv[0]," inputfile outputfile"
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
bootstrap has added three css classes for text align.
Since the extension will always be the string after a period in a complete/partial file name, just use the built in split function in js, and test the resultant extension for what you want it to do. If split returns only one piece / no pieces, it does not contain an extension.
If you know the kernel file is installed on your machine, then problem is getting emulator.exe to find it.
My fix was based on the post by user2789389. I could launch the AVD from the AVD Manager, but not from the command line. So, using AVD Manager, I selected the avd I wanted to run and clicked "Details". That showed me the path to the avd definition file. Within a folder of the same name, next to this .avd file, I found a config.ini file. In the ini, I found the following line:
image.sysdir.1=system-images\android-19\default\armeabi-v7a\
I looked in the folder C:\Users\XXXX\android-sdks\system-images\android-19, and found that the image.sysdir.1 path was invalid. I had to remove the "default" sub folder, thus changing it to the following:
image.sysdir.1=system-images\android-19\armeabi-v7a\
I saved the ini and tried again to launch the AVD. That fixed the problem!
select *
from Table1 as t1
where
exists (
select *
from Table1 as t2
where t2.Phone = t1.Phone and t2.id <> t1.id
)
You can do this without importing os or other libs.
If you want to get the path of current python script, use: __file__
If you want to get only the filename without .py extension, use this:
__file__.rsplit("/", 1)[1].split('.')[0]
Another alternative that only affects the current connection:
SET SESSION query_cache_type=0;
Often you will want to specify a manifest, like so:
jar -cvfm myJar.jar myManifest.txt myApp.class
Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include. Verbose means print messages about what it's doing.
Note that the name of the manifest file you supply can be anything, as jar
will automatically rename it and put it into the right directory within the jar file.
**If you want hibernate to print generated sql queries with real values instead of question marks.**
**add following entry in hibernate.cfg.xml/hibernate.properties:**
show_sql=true
format_sql=true
use_sql_comments=true
**And add following entry in log4j.properties :**
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
java.net.UnknownHostException: Host is unresolved:
Thrown to indicate that the IP address of a host could not be determined.
This exception is also raised when you are connected to a valid wifi but router does not receive the internet. Its very easy to reproduce this:
You will observe this error!!
You can't really solve this, You can only notify the user gracefully. (something like - "Unable to make a connection")
Lucas's answer about core dumps is good. In my .cshrc I have:
alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'
to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.
Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.
I know its an old question and the Android world has mostly moved on to RecyclerViews, but for anyone interested, you may find this library very interesting.
It uses the BaseAdapter used with the ListView to detect when the list has been scrolled to the last item or when it is being scrolled away from the last item.
It comes with an example project(barely 100 lines of Activity code) that can be used to quickly understand how it works.
Simple usage:
class Boy{
private String name;
private double height;
private int age;
//Other code
}
An adapter to hold Boy objects would look like:
public class BoysAdapter extends EndlessAdapter<Boy>{
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent
.getContext());
holder = new ViewHolder();
convertView = inflater.inflate(
R.layout.list_cell, parent, false);
holder.nameView = convertView.findViewById(R.id.cell);
// minimize the default image.
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Boy boy = getItem(position);
try {
holder.nameView.setText(boy.getName());
///Other data rendering codes.
} catch (Exception e) {
e.printStackTrace();
}
return super.getView(position,convertView,parent);
}
Notice how the BoysAdapter's getView method returns a call to the EndlessAdapter superclass's getView
method. This is 100% essential.
Now to create the adapter, do:
adapter = new ModelAdapter() {
@Override
public void onScrollToBottom(int bottomIndex, boolean moreItemsCouldBeAvailable) {
if (moreItemsCouldBeAvailable) {
makeYourServerCallForMoreItems();
} else {
if (loadMore.getVisibility() != View.VISIBLE) {
loadMore.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onScrollAwayFromBottom(int currentIndex) {
loadMore.setVisibility(View.GONE);
}
@Override
public void onFinishedLoading(boolean moreItemsReceived) {
if (!moreItemsReceived) {
loadMore.setVisibility(View.VISIBLE);
}
}
};
The loadMore
item is a button or other ui element that may be clicked to fetch more data from the url.
When placed as described in the code, the adapter knows exactly when to show that button and when to disable it. Just create the button in your xml and place it as shown in the adapter code above.
Enjoy.
- Register your website at – https://www.google.com/recaptcha/admin
- add js plugin 3.add class and your site-key provived by google
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="your site-key"></div>
Node reverse_rec(Node start) {
if (start == null || start -> next == null) {
return start;
}
Node new_start = reverse(start->next);
start->next->next = start;
start->next = null;
return new_start;
}
Node reverse(Node start) {
Node cur = start;
Node bef = null;
while (cur != null) {
Node nex = cur.next;
cur.next = bef;
bef = cur;
cur = nex;
}
return bef;
}
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
on command line
example$:python
>>> import scipy
>>> scipy.__version__
'0.9.0'
I made a useful code to get the parent module's package.json
function loadParentPackageJson() {
if (!module.parent || !module.parent.filename) return null
let dir = path.dirname(module.parent.filename)
let maxDepth = 5
let packageJson = null
while (maxDepth > 0) {
const packageJsonPath = `${dir}/package.json`
const exists = existsSync(packageJsonPath)
if (exists) {
packageJson = require(packageJsonPath)
break
}
dir = path.resolve(dir, '../')
maxDepth--
}
return packageJson
}
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
Just define the target page in the action
attribute of the <form>
containing the submit button.
So, in page1.jsp
:
<form action="page2.jsp">
<input type="submit">
</form>
Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.
All the random numbers generated after setting particular seed value are same across all the platforms/systems.
You can have it embedded (build action set to Resource
) as well, this is how to retrieve it from there:
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
string resName = "Test.txt";
var file = GetResourceStream(resName);
using (var reader = new StreamReader(file))
{
var line = reader.ReadLine();
MessageBox.Show(line);
}
}
(Some code taken from this answer by Charles)
I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:
query.exec(function (err, results){
if (err) res.writeHead(500, err.message)
else if (!results.length) res.writeHead(404);
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
}
res.end();
});
Java <= 6.x just allows you to catch one exception for each catch block:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Documentation:
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.
For Java 7 you can have multiple Exception caught on one catch block:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Documentation:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
@echo off
del /s /f /q %windir%\temp\*.*
rd /s /q %windir%\temp
md %windir%\temp
del /s /f /q %windir%\Prefetch\*.*
rd /s /q %windir%\Prefetch
md %windir%\Prefetch
del /s /f /q %windir%\system32\dllcache\*.*
rd /s /q %windir%\system32\dllcache
md %windir%\system32\dllcache
del /s /f /q "%SysteDrive%\Temp"\*.*
rd /s /q "%SysteDrive%\Temp"
md "%SysteDrive%\Temp"
del /s /f /q %temp%\*.*
rd /s /q %temp%
md %temp%
del /s /f /q "%USERPROFILE%\Local Settings\History"\*.*
rd /s /q "%USERPROFILE%\Local Settings\History"
md "%USERPROFILE%\Local Settings\History"
del /s /f /q "%USERPROFILE%\Local Settings\Temporary Internet Files"\*.*
rd /s /q "%USERPROFILE%\Local Settings\Temporary Internet Files"
md "%USERPROFILE%\Local Settings\Temporary Internet Files"
del /s /f /q "%USERPROFILE%\Local Settings\Temp"\*.*
rd /s /q "%USERPROFILE%\Local Settings\Temp"
md "%USERPROFILE%\Local Settings\Temp"
del /s /f /q "%USERPROFILE%\Recent"\*.*
rd /s /q "%USERPROFILE%\Recent"
md "%USERPROFILE%\Recent"
del /s /f /q "%USERPROFILE%\Cookies"\*.*
rd /s /q "%USERPROFILE%\Cookies"
md "%USERPROFILE%\Cookies"
This is simple, you don't need such complicated code
DividerItemDecoration divider = new
DividerItemDecoration(mRVMovieReview.getContext(),
DividerItemDecoration.VERTICAL);
divider.setDrawable(
ContextCompat.getDrawable(getBaseContext(), R.drawable.line_divider)
);
mRVMovieReview.addItemDecoration(divider);
Add this in your drawable : line_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="1dp" />
<solid android:color="@android:color/black" />
</shape>
For greater than 24 hours you can include days with the following query. The returned format is days:hh24:mi:ss
Query:
select trunc(trunc(sysdate) + numtodsinterval(9999999, 'second')) - trunc(sysdate) || ':' || to_char(trunc(sysdate) + numtodsinterval(9999999, 'second'), 'hh24:mi:ss') from dual;
Output:
115:17:46:39
In JDK 8 source can be found in /src.zip. Now in some intermediate releases this zip was missing but again it is available.
make sure that you select source as well from installation wizard.
This is a combined answer of the two answers at top, if anyone wants a working implementation.
package com.yourapplication;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
public abstract class OnSwipeListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeListener(Context context){
gestureDetector = new GestureDetector(context, new OnSwipeGestureListener(context));
gestureDetector.setIsLongpressEnabled(false);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class OnSwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
private final int minSwipeDelta;
private final int minSwipeVelocity;
private final int maxSwipeVelocity;
private OnSwipeGestureListener(Context context) {
ViewConfiguration configuration = ViewConfiguration.get(context);
// We think a swipe scrolls a full page.
//minSwipeDelta = configuration.getScaledTouchSlop();
minSwipeDelta = configuration.getScaledPagingTouchSlop();
minSwipeVelocity = configuration.getScaledMinimumFlingVelocity();
maxSwipeVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public boolean onDown(MotionEvent event) {
// Return true because we want system to report subsequent events to us.
return true;
}
// NOTE: see http://stackoverflow.com/questions/937313/android-basic-gesture-detection
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX,
float velocityY) {
boolean result = false;
try {
float deltaX = event2.getX() - event1.getX();
float deltaY = event2.getY() - event1.getY();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (absDeltaX > absDeltaY) {
if (absDeltaX > minSwipeDelta && absVelocityX > minSwipeVelocity
&& absVelocityX < maxSwipeVelocity) {
if (deltaX < 0) {
onSwipeLeft();
} else {
onSwipeRight();
}
}
result = true;
} else if (absDeltaY > minSwipeDelta && absVelocityY > minSwipeVelocity
&& absVelocityY < maxSwipeVelocity) {
if (deltaY < 0) {
onSwipeTop();
} else {
onSwipeBottom();
}
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public void onSwipeLeft() {}
public void onSwipeRight() {}
public void onSwipeTop() {}
public void onSwipeBottom() {}
}
For some number y
and some divisor x
compute the quotient (quotient
) and remainder (remainder
) as:
var quotient = Math.floor(y/x);
var remainder = y % x;
Click on the cell you want to copy. In the formula bar, highlight the formula.
Press Ctrl C
.
Press escape (to take you out of actively editing that formula).
Choose new cell. Ctrl V.
In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id
annotation to specify the primary key of an entity.
The @GeneratedValue
annotation is used to specify how the primary key should be generated. In your example you are using an Identity
strategy which
Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
There are other strategies, you can see more here.
You can do Your own Animation style as an xml file like this(put it in anim folder):
left to right:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="500"/>
</set>
right to left:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="500" />
</set>
here You can set Your own values at duration, maybe it depends on the phone model how the animation will look like, try some values out if it looks not good.
and then You can call it in Your activity:
Intent animActivity = new Intent(this,YourStartAfterAnimActivity.class);
startActivity(nextActivity);
overridePendingTransition(R.anim.your_left_to_right, R.anim.your_right_to_left);
An elegant approach would involve making an abstraction similar to what other selenium language bindings offer out-of-the-box (e.g. Select
class in Python or Java).
Let's make a convenient wrapper and hide implementation details inside:
var SelectWrapper = function(selector) {
this.webElement = element(selector);
};
SelectWrapper.prototype.getOptions = function() {
return this.webElement.all(by.tagName('option'));
};
SelectWrapper.prototype.getSelectedOptions = function() {
return this.webElement.all(by.css('option[selected="selected"]'));
};
SelectWrapper.prototype.selectByValue = function(value) {
return this.webElement.all(by.css('option[value="' + value + '"]')).click();
};
SelectWrapper.prototype.selectByPartialText = function(text) {
return this.webElement.all(by.cssContainingText('option', text)).click();
};
SelectWrapper.prototype.selectByText = function(text) {
return this.webElement.all(by.xpath('option[.="' + text + '"]')).click();
};
module.exports = SelectWrapper;
Usage example (note how readable and easy-to-use it is):
var SelectWrapper = require('select-wrapper');
var mySelect = new SelectWrapper(by.id('locregion'));
# select an option by value
mySelect.selectByValue('4');
# select by visible text
mySelect.selectByText('BoxLox');
Solution taken from the following topic: Select -> option abstraction.
FYI, created a feature request: Select -> option abstraction.
$(function() {
$("[data-toggle = 'popover']").popover({
placement: 'left',
html: true,
trigger: " focus",
}).on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function() {
$(_this).popover('hide');
});
}).on("mouseleave", function() {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide")
}
}, 100);
});
});
There's no way to use CSS for this purpose. My advice is to include a javascript code where you assign or change the css class applied to the inputs. Something like that :
function change_input() {_x000D_
$('#id_input1')_x000D_
.toggleClass('class_disabled')_x000D_
.toggleClass('class_enabled');_x000D_
_x000D_
$('.class_disabled').attr('disabled', '');_x000D_
$('.class_enabled').removeAttr('disabled', '');_x000D_
}
_x000D_
.class_disabled { background-color : #FF0000; }_x000D_
.class_enabled { background-color : #00FF00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<form> _x000D_
Input: <input id="id_input1" class="class_enabled" /> _x000D_
<input type="button" value="Toggle" onclick="change_input()";/> _x000D_
</form>
_x000D_
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);
No need to do so much works..
var query = from c in obj.tbCourses
where ...
select c;
Then you can use:
List<course> list_course= query.ToList<course>();
It works fine for me.
I had to implement this recently. Thought of sharing what I had figured out;
To make it work in Safari, I had to set target: '_self',. Don't worry about filename in Safari. Looks like it's not supported as mentioned here; https://github.com/konklone/json/issues/56 (http://caniuse.com/#search=download)
The below code works fine for me in Mozilla, Chrome & Safari;
var anchor = angular.element('<a/>');
anchor.css({display: 'none'});
angular.element(document.body).append(anchor);
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
target: '_self',
download: 'data.csv'
})[0].click();
anchor.remove();
String.Trim()
returns a string which equals the input string with all white-spaces trimmed from start and end:
" A String ".Trim() -> "A String"
String.TrimStart()
returns a string with white-spaces trimmed from the start:
" A String ".TrimStart() -> "A String "
String.TrimEnd()
returns a string with white-spaces trimmed from the end:
" A String ".TrimEnd() -> " A String"
None of the methods modify the original string object.
(In some implementations at least, if there are no white-spaces to be trimmed, you get back the same string object you started with:
csharp> string a = "a";
csharp> string trimmed = a.Trim();
csharp> (object) a == (object) trimmed;
returns true
I don't know whether this is guaranteed by the language.)
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
select * from
(SELECT MEMBSHIP_ID
FROM user_payment WHERE user_id=1
order by paym_date desc)
where rownum=1;
On my linux system, I start Tomcat with the startup.sh script. To know whether it is running or not, i use
ps -ef | grep tomcat
If the output result contains the whole path to my tomcat folder, then it is running
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.
As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.
public class PrivilegesToClaimsTransformer : IClaimsTransformation
{
private readonly IPrivilegeProvider privilegeProvider;
public const string DidItClaim = "http://foo.bar/privileges/resolved";
public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
{
this.privilegeProvider = privilegeProvider;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is ClaimsIdentity claimer)
{
if (claimer.HasClaim(DidItClaim, bool.TrueString))
{
return principal;
}
var privileges = await this.privilegeProvider.GetPrivileges( ... );
claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));
foreach (var privilegeAsRole in privileges)
{
claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
}
}
return principal;
}
}
To use this in your Controller just add an appropriate [Authorize(Roles="whatever")]
to your methods.
[HttpGet]
[Route("poc")]
[Authorize(Roles = "plugh,blast")]
public JsonResult PocAuthorization()
{
var result = Json(new
{
when = DateTime.UtcNow,
});
result.StatusCode = (int)HttpStatusCode.OK;
return result;
}
In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.
Future voters, consider the date of writing when you vote. As of today, this works on my machine.
™ You will probably want more error handling and logging on your implementation.
Xcode 8 and Swift 3.0
Using URLSession:
let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()
URLSession Delegate call:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
}
Using Block GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
Working fine for me.. try it 100% result guarantee
$("option:selected").attr("selected", false);
If you want to control the width of the list that drops down, you can do it as follows.
CSS
#wgtmsr option {
width: 50px;
}
I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.
I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.
After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.
Like you have mentioned, The default -Xmxsize
(Maximum HeapSize) depends on your system configuration.
Java8 client
takes Larger of 1/64th of your physical memory for your Xmssize
(Minimum HeapSize) and Smaller of 1/4th of your physical memory for your -Xmxsize
(Maximum HeapSize).
Which means if you have a physical memory of 8GB RAM, you will have Xmssize
as Larger of 8*(1/6) and Smaller of -Xmxsize
as 8*(1/4).
You can Check your default HeapSize with
In Windows:
java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
In Linux:
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
These default values can also be overrided to your desired amount.
What have you tried, what was the problem?
Creating DataColumns
and add values to a DataTable
is straight forward:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml
.
The get
method of a dict (like for example characters
) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError
it returns the default value (if you call .get
with just one argument, the key, the default value is None
).
So an equivalent Python function (where calling myget(d, k, v)
is just like d.get(k, v)
might be:
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get
returns it (so it's just incremented by one), else get
returns 0 (so the incrementing correctly gives 1
at a character's first occurrence in the string).
As others have indicated, the raw_input
function has been renamed to input
in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.
From your description, I think you're using Windows, you've saved a .py
file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input
/ input
statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.
When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Weeble\My Python Program>_
To run your program, type the following (substituting your script name):
python myscript.py
...and press enter. (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.
IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py
file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.
Swift 4, Swift 3
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MySegueId" {
if let nextViewController = segue.destination as? NextViewController {
nextViewController.valueOfxyz = "XYZ" //Or pass any values
nextViewController.valueOf123 = 123
}
}
}
I think there's proper solution. Configure the yii\data\Sort
object:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]
Or
>>> L[::-1]
[40, 20, 10, 0]
speed of this has to be tested
from math import floor
def get_decimal(number):
'''returns number - floor of number'''
return number-floor(number)
Example:
n = 765.126357123
get_decimal(n)
0.12635712300004798
Simple XML http://simple.sourceforge.net/ is very easy for (de)serializing objects.
There is no concept of "interface" per se in C++. AFAIK, interfaces were first introduced in Java to work around the lack of multiple inheritance. This concept has turned out to be quite useful, and the same effect can be achieved in C++ by using an abstract base class.
An abstract base class is a class in which at least one member function (method in Java lingo) is a pure virtual function declared using the following syntax:
class A
{
virtual void foo() = 0;
};
An abstract base class cannot be instantiated, i. e. you cannot declare an object of class A. You can only derive classes from A, but any derived class that does not provide an implementation of foo()
will also be abstract. In order to stop being abstract, a derived class must provide implementations for all pure virtual functions it inherits.
Note that an abstract base class can be more than an interface, because it can contain data members and member functions that are not pure virtual. An equivalent of an interface would be an abstract base class without any data with only pure virtual functions.
And, as Mark Ransom pointed out, an abstract base class should provide a virtual destructor, just like any base class, for that matter.
Mine is that if you set MASM listing file option some extra selection, it will give you this error.
Just use
Enable Assembler Generated Code Listing Yes/Sg
Assembled Code Listing $(ProjectName).lst
it is fine.
But any extra you have issue.
Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:
array(
[0] => array ([0] => something, [1] => something_else))
...
[100] => array ([0] => something100, [1] => something_else100))
)
would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.
Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:
Where possible, always use objects instead of multiple dimensional arrays:
ArrayObject(
MyObject(something, something_else))
...
MyObject(something100, something_else100))
)
and apply a custom comparator interface and function to sort and find them:
interface Comparable {
public function compareTo(Comparable $o);
}
class MyObject implements Comparable {
public function compareTo(Comparable $o){
...
}
}
function myComp(Comparable $a, Comparable $b){
return $a->compareTo($b);
}
You can use uasort()
to utilize a custom comparator, if you're feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).
$arrayObj->uasort("myComp");
Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes ~20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP (array_search()
uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.
This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)
Although this question is answered a long time ago. I want to recommend to use the pathlib
module since this is a robust way to work on Windows and Unix OS.
So to get all paths in a specific directory including subdirectories:
from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))
# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix
etc.
Putting this answer here as it is the top result in Google.
If you want a quick and simple way:
filter: brightness(0.2);
*Not compatible with IE
You shouldn't have to worry about the stack leaking memory (it is highly uncommon). The only time you can have the stack get out of control is with infinite (or really deep) recursion.
This is just the heap. Sorry, didn't read your question fully at first.
You need to run the JVM with the following command line argument.
-Xmx<ammount of memory>
Example:
-Xmx1024m
That will allow a max of 1GB of memory for the JVM.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
The reason eval
and exec
are so dangerous is that the default compile
function will generate bytecode for any valid python expression, and the default eval
or exec
will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.
Instead, you can easily create a simple eval
function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.
c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]
The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d
, which is the bytecode for LOAD_CONST
, followed by the number of the constant to load (usually the last one in the list), followed by S
, which is the bytecode for RETURN_VALUE
. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).
This also opens the door to some more sophisticated input formats. For example:
stringExp = "1 + cos(2)"
This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS)
or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION
only allow functions in a 'safe' list.
from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator
globs = {'sin':sin, 'cos':cos}
safe = globs.values()
stack = LifoQueue()
class BINARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get(),stack.get()))
class UNARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get()))
def CALL_FUNCTION(context, arg):
argc = arg[0]+arg[1]*256
args = [stack.get() for i in range(argc)]
func = stack.get()
if func not in safe:
raise TypeError("Function %r now allowed"%func)
stack.put(func(*args))
def LOAD_CONST(context, arg):
cons = arg[0]+arg[1]*256
stack.put(context['code'].co_consts[cons])
def LOAD_NAME(context, arg):
name_num = arg[0]+arg[1]*256
name = context['code'].co_names[name_num]
if name in context['locals']:
stack.put(context['locals'][name])
else:
stack.put(context['globals'][name])
def RETURN_VALUE(context):
return stack.get()
opfuncs = {
opmap['BINARY_ADD']: BINARY(operator.add),
opmap['UNARY_INVERT']: UNARY(operator.invert),
opmap['CALL_FUNCTION']: CALL_FUNCTION,
opmap['LOAD_CONST']: LOAD_CONST,
opmap['LOAD_NAME']: LOAD_NAME
opmap['RETURN_VALUE']: RETURN_VALUE,
}
def VMeval(c):
context = dict(locals={}, globals=globs, code=c)
bci = iter(c.co_code)
for bytecode in bci:
func = opfuncs[ord(bytecode)]
if func.func_code.co_argcount==1:
ret = func(context)
else:
args = ord(bci.next()), ord(bci.next())
ret = func(context, args)
if ret:
return ret
def evaluate(expr):
return VMeval(compile(expr, 'userinput', 'eval'))
Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST
and a couple others would allow for input like 'x=5;return x+x
or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto
bytecodes, which means changing from a for
iterator to while
and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER
being the most obvious).
While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile
take anything arbitrarily complicated and reduces it to a sequence of simple instructions).
for (const field in this.formErrors) {
if (this.formErrors.hasOwnProperty(field)) {
for (const key in control.errors) {
if (control.errors.hasOwnProperty(key)) {
Media types do not allow you to detect touch capabilities as part of the standard:
http://www.w3.org/TR/css3-mediaqueries/
So, there is no way to do it consistently via CSS or media queries, you will have to resort to JavaScript.
No need to use Modernizr, you can just use plain JavaScript:
<script type="text/javascript">
var is_touch_device = 'ontouchstart' in document.documentElement;
if(is_touch_device) alert("touch is enabled!");
</script>
You can create a linked server and reference the table in the other instance using its fully qualified Server.Catalog.Schema.Table name.
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.
Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.
Consider a program ArgsTest.java:
package test;
import java.io.IOException;
public class ArgsTest {
public static void main(String[] args) throws IOException {
System.out.println("Program Arguments:");
for (String arg : args) {
System.out.println("\t" + arg);
}
System.out.println("System Properties from VM Arguments");
String sysProp1 = "sysProp1";
System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
String sysProp2 = "sysProp2";
System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));
}
}
If given input as,
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
in the commandline, in project bin folder would give the following result:
Program Arguments: pro1 pro2 pro3 System Properties from VM Arguments Name:sysProp1, Value:sp1 Name:sysProp2, Value:sp2
Add ?var1=data1&var2=data2
to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
First copy the source range then paste-special on target range with Transpose:=True, short sample:
Option Explicit
Sub test()
Dim sourceRange As Range
Dim targetRange As Range
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
Set targetRange = ActiveSheet.Cells(6, 1)
sourceRange.Copy
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub
The Transpose function takes parameter of type Varaiant and returns Variant.
Sub transposeTest()
Dim transposedVariant As Variant
Dim sourceRowRange As Range
Dim sourceRowRangeVariant As Variant
Set sourceRowRange = Range("A1:H1") ' one row, eight columns
sourceRowRangeVariant = sourceRowRange.Value
transposedVariant = Application.Transpose(sourceRowRangeVariant)
Dim rangeFilledWithTransposedData As Range
Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
rangeFilledWithTransposedData.Value = transposedVariant
End Sub
I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.
First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.
If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.
Hope i did not confuse u, my english is bad, sorry :-).
As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0
. however there are other alternatives available including DBCP
.
Check out
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
Not very simple but:
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]
Also handles the case for multiples in the 'subtrahend':
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]
EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.
b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }
Put it in a lambda if needed:
subtract = lambda do |minuend, subtrahend|
subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end
then:
subtract.call a, [1,1,3]
The answer to this question simply put is: Don't use BOOLEAN with Oracle-- PL/SQL is dumb and it doesn't work. Use another data type to run your process.
A note to SSRS report developers with Oracle datasource: You can use BOOLEAN parameters, but be careful how you implement. Oracle PL/SQL does not play nicely with BOOLEAN, but you can use the BOOLEAN value in the Tablix Filter if the data resides in your dataset. This really tripped me up, because I have used BOOLEAN parameter with Oracle data source. But in that instance I was filtering against Tablix data, not SQL query.
If the data is NOT in your SSRS Dataset Fields, you can rewrite the SQL something like this using an INTEGER parameter:
__
<ReportParameter Name="paramPickupOrders">
<DataType>Integer</DataType>
<DefaultValue>
<Values>
<Value>0</Value>
</Values>
</DefaultValue>
<Prompt>Pickup orders?</Prompt>
<ValidValues>
<ParameterValues>
<ParameterValue>
<Value>0</Value>
<Label>NO</Label>
</ParameterValue>
<ParameterValue>
<Value>1</Value>
<Label>YES</Label>
</ParameterValue>
</ParameterValues>
</ValidValues>
</ReportParameter>
...
<Query>
<DataSourceName>Gmenu</DataSourceName>
<QueryParameters>
<QueryParameter Name=":paramPickupOrders">
<Value>=Parameters!paramPickupOrders.Value</Value>
</QueryParameter>
<CommandText>
where
(:paramPickupOrders = 0 AND ordh.PICKUP_FLAG = 'N'
OR :paramPickupOrders = 1 AND ordh.PICKUP_FLAG = 'Y' )
If the data is in your SSRS Dataset Fields, you can use a tablix filter with a BOOLEAN parameter:
__
</ReportParameter>
<ReportParameter Name="paramFilterOrdersWithNoLoad">
<DataType>Boolean</DataType>
<DefaultValue>
<Values>
<Value>false</Value>
</Values>
</DefaultValue>
<Prompt>Only orders with no load?</Prompt>
</ReportParameter>
...
<Tablix Name="tablix_dsMyData">
<Filters>
<Filter>
<FilterExpression>
=(Parameters!paramFilterOrdersWithNoLoad.Value=false)
or (Parameters!paramFilterOrdersWithNoLoad.Value=true and Fields!LOADNUMBER.Value=0)
</FilterExpression>
<Operator>Equal</Operator>
<FilterValues>
<FilterValue DataType="Boolean">=true</FilterValue>
</FilterValues>
</Filter>
</Filters>
You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.
It goes by this syntax: ${VARIABLE:-default}.
The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.
If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".
In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly
property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
You can use to_date
, e.g.
> Event.last.starts_at
=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00
> Event.last.starts_at.to_date
=> Wed, 13 Jan 2021
A lot of solutions are mentioned above. No one worked for me(but please try above first).
Select Project -> Select Target -> Linked Framework and Libraries -> Add all pod libraries . (remove if they exist in embedded binaries)
Now remove these from Framework Folder in left file explorer of xcode.
This solved my issue.
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
you can disable link using javascript at run time by using this code
$('.page-link').css("pointer-events", "none");
This may help someone with the same problem.
Generate the key hash using the below code
keytool -exportcert -alias <your_keystore> alias -keystore <your_keystore_file> | openssl sha1 -binary | openssl base64
Paste it in required field in Facebook developer
In Android Studio, menu File → Project Structure
Add signing parameters.
Select flavors
Select the signing configuration we created.
Select build type
Select build variant and build it
To delete all directories with the name foo
, run:
find -type d -name foo -a -prune -exec rm -rf {} \;
The other answers are missing an important thing: the -prune
option. Without -prune
, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune
option tells it to not recurse into a directory that matched the conditions.
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
In .net VB - you could achieve control over columns and rows with the following in your razor file:
@Html.EditorFor(Function(model) model.generalNotes, New With {.htmlAttributes = New With {.class = "someClassIfYouWant", .rows = 5,.cols=6}})
I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.
The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.
.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:
OPTIONAL HEADER VALUES
10B magic # (PE32)
...
4.00 operating system version
0.00 image version
4.00 subsystem version // <=== here!!
0 Win32 version
...
What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.
You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.
That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0
And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0
Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.
char * const and const char *?
const char * p;
// value cannot be changed
char * const p;
// address cannot be changed
const char * const p;
// both cannot be changed.
You can easily use the MODE argument:
MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions
If the mode argument is omitted, the value of the default_week_format system variable is used:
MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables
I'm surprised no one has mentioned the obvious bash
solution utilizing only while
and read
.
while read -n1 character; do
echo "$character"
done < <(echo -n "$words")
Note the use of echo -n
to avoid the extraneous newline at the end. printf
is another good option and may be more suitable for your particular needs. If you want to ignore whitespace then replace "$words"
with "${words// /}"
.
Another option is fold
. Please note however that it should never be fed into a for loop. Rather, use a while loop as follows:
while read char; do
echo "$char"
done < <(fold -w1 <<<"$words")
The primary benefit to using the external fold
command (of the coreutils package) would be brevity. You can feed it's output to another command such as xargs
(part of the findutils package) as follows:
fold -w1 <<<"$words" | xargs -I% -- echo %
You'll want to replace the echo
command used in the example above with the command you'd like to run against each character. Note that xargs
will discard whitespace by default. You can use -d '\n'
to disable that behavior.
I just tested fold
with some of the Asian characters and realized it doesn't have Unicode support. So while it is fine for ASCII needs, it won't work for everyone. In that case there are some alternatives.
I'd probably replace fold -w1
with an awk array:
awk 'BEGIN{FS=""} {for (i=1;i<=NF;i++) print $i}'
Or the grep
command mentioned in another answer:
grep -o .
FYI, I benchmarked the 3 aforementioned options. The first two were fast, nearly tying, with the fold loop slightly faster than the while loop. Unsurprisingly xargs
was the slowest... 75x slower.
Here is the (abbreviated) test code:
words=$(python -c 'from string import ascii_letters as l; print(l * 100)')
testrunner(){
for test in test_while_loop test_fold_loop test_fold_xargs test_awk_loop test_grep_loop; do
echo "$test"
(time for (( i=1; i<$((${1:-100} + 1)); i++ )); do "$test"; done >/dev/null) 2>&1 | sed '/^$/d'
echo
done
}
testrunner 100
Here are the results:
test_while_loop
real 0m5.821s
user 0m5.322s
sys 0m0.526s
test_fold_loop
real 0m6.051s
user 0m5.260s
sys 0m0.822s
test_fold_xargs
real 7m13.444s
user 0m24.531s
sys 6m44.704s
test_awk_loop
real 0m6.507s
user 0m5.858s
sys 0m0.788s
test_grep_loop
real 0m6.179s
user 0m5.409s
sys 0m0.921s
// pop back stack all the way
final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
int entryCount = fm.getBackStackEntryCount();
while (entryCount-- > 0) {
fm.popBackStack();
}
On windows, Try using git bash and use your Linux commands there. Easy approach
chmod 400 *****.pem
ssh -i "******.pem" [email protected]
Please try this in your linear layout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
#include<stdio.h>
void frequency_counter(char* str)
{
int count[256] = {0}; //partial initialization
int i;
for(i=0;str[i];i++)
count[str[i]]++;
for(i=0;str[i];i++) {
if(count[str[i]]) {
printf("%c %d \n",str[i],count[str[i]]);
count[str[i]]=0;
}
}
}
void main()
{
char str[] = "The quick brown fox jumped over the lazy dog.";
frequency_counter(str);
}
Could you be a little more specific?
$key = array_search('string2',$list)
works fine for me. Are you trying to accomplish something more complex?
As others already wrote, a timer is the best option in the scenario you described.
Depending on your exact requirements, checking the current time every minute may not be necessary. If you do not need to perform the action exactly at midnight, but just within one hour after midnight, you can go for Martin's approach of only checking if the date has changed.
If the reason you want to perform your action at midnight is that you expect a low workload on your computer, better take care: The same assumption is often made by others, and suddenly you have 100 cleanup actions kicking off between 0:00 and 0:01 a.m.
In that case you should consider starting your cleanup at a different time. I usually do those things not at clock hour, but at half hours (1.30 a.m. being my personal preference)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $
represents the jQuery Function, and is actually a shorthand alias for jQuery
. (Unlike in most languages, the $
symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).
Then please check Package Docs Control Usage for Basic Functionality:
Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.
The command pallete will now show a number of commands. Most users will be interested in the following:
Install Package
Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
example:
Code: body{font-size:10px;} //keep at 10 all sizes below correct, change this value and the rest change to be e.g. 1.4 of this value
…
body
1
2
3
4
5
by changing the value in body the rest change automatically to be a kind of times the base value…
10×2=20 10×1.6=16 etc
you could have the base value as 8px… so 8×2=16 8×1.6=12.8 //may be rounded by browser
Sounds like an ideal application for RegEx -- an engine designed for fast text manipulation. In this case:
Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)
your mail.php
on config you declare host as smtp.mailgun.org
and port is 587
while on env is different. you need to change your mail.php
to
'host' => env('MAIL_HOST', 'mailtrap.io'),
'port' => env('MAIL_PORT', 2525),
if you desire to use mailtrap.Then run
php artisan config:cache
The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:
this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);
You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:
render: function() {
return (
<span>
// This will go through all the elements in arrayFromJson and
// render each one as a <SomeComponent /> with data from the object
{this.state.arrayFromJson.map(function(object) {
return (
<SomeComponent key={object.id} data={object} />
);
})}
</span>
);
}
var top = event.target.offsetTop + 'px';
Parent element top position like we are adding elemnt inside div
var rect = event.target.offsetParent;
rect.offsetTop;
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
In random.random() the output lies between 0 & 1 , and it takes no input parameters
Whereas random.uniform() takes parameters , wherein you can submit the range of the random number.
e.g.
import random as ra
print ra.random()
print ra.uniform(5,10)
OUTPUT:-
0.672485369423
7.9237539416
While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.
MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.
From VBA you might try using:
textbox.Value = Format(Date(),"mm/dd/yy")
With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.
It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:
systemctl stop firewalld
systemctl mask firewalld
Then, install the iptables-services package:
yum install iptables-services
Enable the service at boot-time:
systemctl enable iptables
Managing the service
systemctl [stop|start|restart] iptables
Saving your firewall rules can be done as follows:
service iptables save
or
/usr/libexec/iptables/iptables.init save
Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
You ask
How can I make a thread wait until it will be notified?
You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
Details for synchronization and waiting are already explained by Tom Hawtin.
java.lang.IllegalMonitorStateException
means you are trying to wait on object on which you are not synchronized - it's illegal to do so.
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
question_text varchar(1024) not null,
question_point_value decimal
);
--That will work too. Pehaps a bit more intuitive construct?
A slightly simplified answer:
public class Book
{
private final String title;
public Book(String title)
{
this.title = title;
}
public Book()
{
this("Default Title");
}
...
}
use the reset method of Path class
Path.reset();
I use this one:
from pyspark.sql.functions import col
df.select(['vin',col('timeStamp').alias('Date')]).show()
Elements that are not being rendered (be it through visibility: hidden
, display: none
, opacity: 0.0
, whatever) will not indicate focus. The browser will not draw a focus border around nothing.
If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex
property:
<label tabindex="0" class="checkbox">
<input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>
In this case, the <label>
tag above is actually receiving focus and everything within it will have a focus border when it's in focus.
I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" />
tag instead.
For return in date format
CAST(OrderDate AS date)
The above code will work in sql server 2010
It will return like 12/12/2013
For SQL Server 2012 use the below code
CONVERT(VARCHAR(10), OrderDate , 111)
In SQL Server you can turn on and off identity insert like this:
SET IDENTITY_INSERT table_name ON
-- run your queries here
SET IDENTITY_INSERT table_name OFF
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
RUN: Can be many, and it is used in build process, e.g. install multiple libraries
CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"]
, ["node", "app.js"]
)
exec is for statement and does not return anything. eval is for expression and returns value of expression.
expression means "something" while statement means "do something".
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:
const arr = [1, 2, 3];
const val = 4;
arr.concat([val]); // [1, 2, 3, 4]
Or just:
[...arr, val] // [1, 2, 3, 4]
Delete the finalizers block from resource (pod,deployment,ds etc...) yaml:
"finalizers": [
"foregroundDeletion"
]
An NSInteger
has the method stringValue
that can be used even with a literal
NSString *integerAsString1 = [@12 stringValue];
NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];
Very simple. Isn't it?
var integerAsString = String(integer)
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
Use this in your Style in your values-v21/style.xml
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.NoActionBar">_x000D_
<item name="android:windowBackground">@android:color/white</item>_x000D_
<item name="android:windowActionBar">false</item>_x000D_
<item name="android:colorAccent">@color/cbt_ui_primary_dark</item>_x000D_
<item name="android:windowTitleStyle">@style/DialogWindowTitle.Sphinx</item>_x000D_
<item name="android:textColorPrimary">@color/cbt_hints_color</item>_x000D_
<item name="android:backgroundDimEnabled">true</item>_x000D_
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>_x000D_
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>_x000D_
</style>
_x000D_
And for pre lollipop devices put it in values/style.xml
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.NoActionBar">_x000D_
<item name="android:windowBackground">@android:color/white</item>_x000D_
<item name="android:windowActionBar">false</item>_x000D_
<item name="android:colorAccent">@color/cbt_ui_primary_dark</item>_x000D_
<item name="android:windowTitleStyle">@style/DialogWindowTitle.Sphinx</item>_x000D_
<item name="android:textColorPrimary">@color/cbt_hints_color</item>_x000D_
<item name="android:backgroundDimEnabled">true</item>_x000D_
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>_x000D_
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>_x000D_
</style>_x000D_
_x000D_
<style name="DialogWindowTitle.Sphinx" parent="@style/DialogWindowTitle_Holo">_x000D_
<item name="android:textAppearance">@style/TextAppearance.Sphinx.DialogWindowTitle</item>_x000D_
</style>_x000D_
_x000D_
<style name="TextAppearance.Sphinx.DialogWindowTitle" parent="@android:style/TextAppearance.Holo.DialogWindowTitle">_x000D_
<item name="android:textColor">@color/dark</item>_x000D_
<!--<item name="android:fontFamily">sans-serif-condensed</item>-->_x000D_
<item name="android:textStyle">bold</item>_x000D_
</style>
_x000D_
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.