@apneadiving answer is a neat way of solving this. However, now we have a new method in Rspec 3.3. We can simply run rspec spec/unit/baseball_spec.rb[#context:#it]
instead of using a line number. Taken from here:
RSpec 3.3 introduces a new way to identify examples[...]
For example, this command:
$ rspec spec/unit/baseball_spec.rb[1:2,1:4]
…would run the 2nd and 4th example or group defined under the 1st top-level group defined in spec/unit/baseball_spec.rb.
So instead of doing
rspec spec/unit/baseball_spec.rb:42
where it (test in line 42) is the first test, we can simply do
rspec spec/unit/baseball_spec.rb[1:1]
or rspec spec/unit/baseball_spec.rb[1:1:1]
depending on how nested the test case is.
I solved it by following these steps:
config.encoding = "utf-8"
is in the application.rb file.# encoding: utf-8
at the top of file containing UTF-8 characters.Above the <App Name>::Application.initialize!
line in the environment.rb file, add following two lines:
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
http://rorguide.blogspot.com/2011/06/incompatible-character-encodings-ascii.html
.md
stands for markdown and is generated at the bottom of your github page as html.
Typical syntax includes:
Will become a heading
==============
Will become a sub heading
--------------
*This will be Italic*
**This will be Bold**
- This will be a list item
- This will be a list item
Add a indent and this will end up as code
For more details: http://daringfireball.net/projects/markdown/
it's as specified in the JLS (15.22.2):
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The "trick" is that &
is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.
It seems most web sites out on the internet use 1460 bytes for the value of MTU. Sometimes it's 1452 and if you are on a VPN it will drop even more for the IPSec headers.
The default window size varies quite a bit up to a max of 65535 bytes. I use http://tcpcheck.com to look at my own source IP values and to check what other Internet vendors are using.
You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:
from StringIO import StringIO
import prettytable
output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt
Lock your time loop to the system clock like this:
import time
starttime = time.time()
while True:
print "tick"
time.sleep(60.0 - ((time.time() - starttime) % 60.0))
To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?
. In order to tell Vim to also look inside ~/.vim/vim-haml
you'll want to add
set runtimepath+=$HOME/.vim/vim-haml
to your ~/.vimrc
. You'll likely also want the following in your ~/.vimrc
to enable all the functionality provided by vim-haml.
filetype plugin indent on
syntax on
You can refer to the 'runtimepath'
and :filetype
help topics in Vim for more information.
A .jar file contains compiled code (*.class files) and other data/resources related to that code. It enables you to bundle multiple files into a single archive file. It also contains metadata. Since it is a zip file it is capable of compressing the data that you put into it.
Couple of things i found useful.
http://www.skylit.com/javamethods/faqs/createjar.html
http://docs.oracle.com/javase/tutorial/deployment/jar/basicsindex.html
The book OSGi in practice defines JAR files as, "JARs are archive files based on the ZIP file format, allowing many files to be aggregated into a single file. Typically the files contained in the archive are a mixture of compiled Java class files and resource files such as images and documents. Additionally the specification defines a standard location within a JAR archive for metadata — the META-INF folder — and several standard file names and formats within that directly, most important of which is the MANIFEST.MF file."
It's a function annotation.
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.
There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.
You can use the GNU profiler. It shows the call-graph as well! the command is gprof
and you need to compile your code with some option.
I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.
Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.
I too faced a similar issue and my resolution was different. I went to the line of code mentioned and traversed to the character (For SpanishTest.java[31, 81], go to 31st line and 81th character including spaces). I observed an apostrophe in comment which was causing the issue. Though not a mistake, the maven compiler reports issue and in my case it was possible to remove maven's 'illegal' character.. lol.
Old post. I ended up setting media queries and using max-width: YYpx;
and width:auto;
for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md
screen), the modal will scale down to 740px (excluding padding for the .modal-body
, if applied)
<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<div class="modal-body"></div>
</div>
</div>
</div>
Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss
file that _bootstrap.scss
imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss
.
It is also important to note that the original bootstrap styles for .modal-dialog
is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;
, hence why I overrode it w/ width: auto;
.
@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
.modal-dialog {
max-width: 600px;
width: auto;
}
}
@media (min-width: $screen-md-min) { // this is the 992px breakpoint
.modal-dialog {
max-width: 800px;
}
}
Example below of modal being responsive with an image.
For those looking for a solution. If you accidentally made pip
requirements with pip list
instead of pip freeze
, and want to convert into pip freeze format. I wrote this R script to do so.
library(tidyverse)
pip_list = read_lines("requirements.txt")
pip_freeze = pip_list %>%
str_replace_all(" \\(", "==") %>%
str_replace_all("\\)$", "")
pip_freeze %>% write_lines("requirements.txt")
Http 415 Media Unsupported
is responded back only when the content type header you are providing is not supported by the application.
With POSTMAN, the Content-type
header you are sending is Content type 'multipart/form-data
not application/json
. While in the ajax code you are setting it correctly to application/json
. Pass the correct Content-type header in POSTMAN and it will work.
If the SSH it gives you 2 options, choose number 1, and put "None". Just that...for the moment.
I have faced the same question recently. What I understand is, if the branch you are checking in has a file which you modified and it happens to be also modified and committed by that branch. Then git will stop you from switching to the branch to keep your change safe before you commit or stash.
json_decode($json, true);
// the second param being true will return associative array. This one is easy.
When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON
clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE
clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON
or WHERE
clauses -- the result will be the same.
SELECT s.*,
cs.`value`
FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
AND cs.character_id = 1
One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.
From the documentation,
bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool
array_walk takes an array and a function F
and modifies it by replacing every element x with F(x)
.
array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array
array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.
array array_filter ( array $input [, callback $callback ] )<-return array
array_filter with function F
, instead of transforming the elements, will remove any elements for which F(x)
is not true
Two reasons, there may be more:
pip provides an uninstall
command
if an installation fails in the middle, pip will leave you in a clean state.
I'd recommend you yo use an out-of-the-box solution. Given that the development of a workflow engine requires a vast amount of resources and time, a ready-made engine is a better option. Have a look at Workflow Engine. It's a lightweight component that enables you to add custom executable workflows of any complexity to any Java solutions.
Try this all four way to take input with space :)
#include<iostream>
#include<stdio.h>
using namespace std;
void dinput(char *a)
{
for(int i=0;; i++)
{
cin >> noskipws >> a[i];
if(a[i]=='\n')
{
a[i]='\0';
break;
}
}
}
void input(char *a)
{
//cout<<"\nInput string: ";
for(int i=0;; i++)
{
*(a+i*sizeof(char))=getchar();
if(*(a+i*sizeof(char))=='\n')
{
*(a+i*sizeof(char))='\0';
break;
}
}
}
int main()
{
char a[20];
cout<<"\n1st method\n";
input(a);
cout<<a;
cout<<"\n2nd method\n";
cin.get(a,10);
cout<<a;
cout<<"\n3rd method\n";
cin.sync();
cin.getline(a,sizeof(a));
cout<<a;
cout<<"\n4th method\n";
dinput(a);
cout<<a;
return 0;
}
If you're willing to use LLVM, check this out: http://llvm.org/docs/tutorial/. It teaches you how to write a compiler from scratch using LLVM's framework, and doesn't assume you have any knowledge about the subject.
The tutorial suggest you write your own parser and lexer etc, but I advise you to look into bison and flex once you get the idea. They make life so much easier.
For me the 'Bla' file was System.Net.http dll which was missing from my BIN folder. I just added it and it worked fine. Didn't change any registry key or anything of that sort.
For me, the problem resolves after I changed:
<script type='text/javascript' src='../../path-to-slick/slick.min.js'></script>
to
<script src='../../path-to-slick/slick.min.js'></script>
My work is based on Jquery 2.2.4, and I'm running my development on the latest Xampp and Chrome.
id
overviewAn Android id
is an integer commonly used to identify views; this id
can be assigned via XML (when possible) and via code (programmatically.) The id
is most useful for getting references for XML-defined View
s generated by an Inflater
(such as by using setContentView
.)
id
via XML
android:id="@+id/
somename"
to your view.android:id
will be assigned a unique int
for use in code.android:id
's int
value in code using "R.id.
somename" (effectively a constant.)int
can change from build to build so never copy an id from gen/
package.name/R.java
, just use "R.id.
somename".id
assigned to a Preference
in XML is not used when the Preference
generates its View
.)id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)id
sXML
-assigned id
s will be unique.id
s do not have to be uniqueid
s can (theoretically) conflict with XML
-assigned id
s.id
s won't matter if queried correctly (keep reading).id
s don't matterfindViewById(int)
will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View
it finds with a matching id
.id
s assigned before an XML-defined id
in the hierarchy, findViewById(R.id.somename)
will always return the XML-defined View so id
'd.ID
sViewGroup
with id
.LinearLayout
with android:id="@+id/placeholder"
.ViewGroup
with View
s.id
s that are convenient to each view.Query these child views using placeholder.findViewById(convenientInt);
API 17 introduced View.generateViewId()
which allows you to generate a unique ID.
If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext()
and be sure to set each reference to null in onDestroy
. Apparently leaking the Activity
(hanging onto it after is is destroyed) is wasteful.. :)
android:id
for use in codeAPI 17 introduced View.generateViewId()
which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
Here, values/ids.xml defines a custom id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
myViewGroup.setId(R.id.reservedNamedId);
id
exampleFor clarity by way of obfuscating example, lets examine what happens when there is an id
conflict behind the scenes.
layout/mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
To simulate a conflict, lets say our latest build assigned R.id.placeholder
(@+id/placeholder
) an int
value of 12
..
Next, MyActivity.java defines some adds views programmatically (via code):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
So placeholder
and one of our new TextView
s both have an id
of 12! But this isn't really a problem if we query placeholder's child views:
// Will return a generated TextView:
placeholder.findViewById(12);
// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);
*Not so bad
select previous, Present, previous-Present as Difference from tablename
or
select previous, Present, previous-Present as Difference from #TEMP1
A solution without the Desktop environment is BrowserLauncher2. This solution is more general as on Linux, Desktop is not always available.
The lenghty answer is posted at https://stackoverflow.com/a/21676290/873282
FOR UNINSTALLING AND THEN BEING ABLE TO REINSTALL XCODE 9 CORRECTLY
I followed the topmost answer for deleting Xcode 7 and found a major error, deleting ~/Library/Developer
will delete an important folder called PrivateFrameworks
, which will actually crash Xcode everytime you reinstall and force you to have to get your friends to send you the PrivateFrameworks folder again, a complete waste of time seeing if you needed to uninstall and reinstall Xcode urgently for immediate work purposes.
I have tried editing the topmost answer but see no changes so below is the modified steps you should take for Xcode 9:
Delete
/Applications/Xcode.app
~/Library/Preferences/com.apple.dt.*
(Generally anything with com.apple.dt. as prefix is removable in the Preferences folder)
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
Everything in
/Library/Developer
directory except for
/Library/Developer/PrivateFrameworks
From this link:
def prnDict(aDict, br='\n', html=0,
keyAlign='l', sortKey=0,
keyPrefix='', keySuffix='',
valuePrefix='', valueSuffix='',
leftMargin=0, indent=1 ):
'''
return a string representive of aDict in the following format:
{
key1: value1,
key2: value2,
...
}
Spaces will be added to the keys to make them have same width.
sortKey: set to 1 if want keys sorted;
keyAlign: either 'l' or 'r', for left, right align, respectively.
keyPrefix, keySuffix, valuePrefix, valueSuffix: The prefix and
suffix to wrap the keys or values. Good for formatting them
for html document(for example, keyPrefix='<b>', keySuffix='</b>').
Note: The keys will be padded with spaces to have them
equally-wide. The pre- and suffix will be added OUTSIDE
the entire width.
html: if set to 1, all spaces will be replaced with ' ', and
the entire output will be wrapped with '<code>' and '</code>'.
br: determine the carriage return. If html, it is suggested to set
br to '<br>'. If you want the html source code eazy to read,
set br to '<br>\n'
version: 04b52
author : Runsun Pan
require: odict() # an ordered dict, if you want the keys sorted.
Dave Benjamin
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403
'''
if aDict:
#------------------------------ sort key
if sortKey:
dic = aDict.copy()
keys = dic.keys()
keys.sort()
aDict = odict()
for k in keys:
aDict[k] = dic[k]
#------------------- wrap keys with ' ' (quotes) if str
tmp = ['{']
ks = [type(x)==str and "'%s'"%x or x for x in aDict.keys()]
#------------------- wrap values with ' ' (quotes) if str
vs = [type(x)==str and "'%s'"%x or x for x in aDict.values()]
maxKeyLen = max([len(str(x)) for x in ks])
for i in range(len(ks)):
#-------------------------- Adjust key width
k = {1 : str(ks[i]).ljust(maxKeyLen),
keyAlign=='r': str(ks[i]).rjust(maxKeyLen) }[1]
v = vs[i]
tmp.append(' '* indent+ '%s%s%s:%s%s%s,' %(
keyPrefix, k, keySuffix,
valuePrefix,v,valueSuffix))
tmp[-1] = tmp[-1][:-1] # remove the ',' in the last item
tmp.append('}')
if leftMargin:
tmp = [ ' '*leftMargin + x for x in tmp ]
if html:
return '<code>%s</code>' %br.join(tmp).replace(' ',' ')
else:
return br.join(tmp)
else:
return '{}'
'''
Example:
>>> a={'C': 2, 'B': 1, 'E': 4, (3, 5): 0}
>>> print prnDict(a)
{
'C' :2,
'B' :1,
'E' :4,
(3, 5):0
}
>>> print prnDict(a, sortKey=1)
{
'B' :1,
'C' :2,
'E' :4,
(3, 5):0
}
>>> print prnDict(a, keyPrefix="<b>", keySuffix="</b>")
{
<b>'C' </b>:2,
<b>'B' </b>:1,
<b>'E' </b>:4,
<b>(3, 5)</b>:0
}
>>> print prnDict(a, html=1)
<code>{
'C' :2,
'B' :1,
'E' :4,
(3, 5):0
}</code>
>>> b={'car': [6, 6, 12], 'about': [15, 9, 6], 'bookKeeper': [9, 9, 15]}
>>> print prnDict(b, sortKey=1)
{
'about' :[15, 9, 6],
'bookKeeper':[9, 9, 15],
'car' :[6, 6, 12]
}
>>> print prnDict(b, keyAlign="r")
{
'car':[6, 6, 12],
'about':[15, 9, 6],
'bookKeeper':[9, 9, 15]
}
'''
Settings ->
Preference ->
Edit Components (tab) ->
Tab Setting (group) ->
Replace by space
In version 5.6.8 (and above):
Settings ->
Preferences... ->
Language Menu/Tab Settings ->
Tab Settings (group) ->
Replace by space
There's a great blog post on this here:
http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
Along with a demo here:
http://www.kylejlarson.com/files/iosdemo/
In summary, you can use the following on a div containing your main content:
.scrollable {
position: absolute;
top: 50px;
left: 0;
right: 0;
bottom: 0;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?
In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.
It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:
document.addEventListener('touchmove', function(event) {
if(event.target.parentNode.className.indexOf('noBounce') != -1
|| event.target.className.indexOf('noBounce') != -1 ) {
event.preventDefault(); }
}, false);
Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.
Other alternatives, also mentioned in the blog post, are Scrollability and iScroll
if (($("#one").length > 0)){
alert('yes');
}
if (($("#two").length > 0)){
alert('yes');
}
if (($("#three").length > 0)){
alert('yes');
}
if (($("#four")).length == 0){
alert('no');
}
This is what you need :)
i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo
in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how
cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
if the directory /var/mysql doesnt exist, we must create it with
sudo mkdir /var/mysql
The regex into selected answer fail for Unicode: 0x1d (with php 7.4)
a solution:
<?php
$ct = 'différents'."\r\n test";
// fail for Unicode: 0x1d
$ct = preg_replace('/[\x00-\x1F\x7F]$/u', '',$ct);
// work for Unicode: 0x1d
$ct = preg_replace( '/[^\P{C}]+/u', "", $ct);
// work for Unicode: 0x1d and allow line break
$ct = preg_replace( '/[^\P{C}\n]+/u', "", $ct);
echo $ct;
from: UTF 8 String remove all invisible characters except newline
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
You can then wrap each API call with the gpuErrchk
macro, which will process the return status of the API call it wraps, for example:
gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );
If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr
and the application will exit. You could conceivably modify gpuAssert
to raise an exception rather than call exit()
in a more sophisticated application if it were required.
A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:
kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:
kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );
in which case the cudaMemcpy
call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.
Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:
#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) assert(0);
}
}
In addition to @Connor Leech's answer.
If you want to create a new custom typography type of your own, define the following in your css file.
.text-foo {
.text-emphasis-variant(#FFFFFF);
}
The mixin text-emphasis-variant
is defined in Bootstrap's mixins.less
file.
The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:
entry: {
outputone: './source/fileone.jsx',
outputtwo: './source/filetwo.jsx'
},
output: {
path: path.resolve(__dirname, './wwwroot/js/dist'),
filename: '[name].js'
},
This will generate 2 files: outputone.js und outputtwo.js in the target folder.
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:
ALTER TABLE dbo.Content
ADD CONSTRAINT FK_Content_Libraries
FOREIGN KEY(LibraryID, Application)
REFERENCES dbo.Libraries(ID, Application)
Is that what you're using?? If (ID, Application)
is indeed the primary key on dbo.Libraries
, this statement should definitely work.
Luk: just to check - can you run this statement in your database and report back what the output is??
SELECT
tc.TABLE_NAME,
tc.CONSTRAINT_NAME,
ccu.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
tc.TABLE_NAME IN ('Libraries', 'Content')
placeholder
attributeYou're looking for the placeholder
attribute. Use it like any other attribute inside your ASP.net control:
<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>
Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:
<input type="text" placeholder="hint"/>
placeholder
in resourcesA fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains
<data name="WithHint.placeholder">
<value>hint</value>
</data>
and your control looks like
<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>
the rendered result will look the same as the one in the chapter above.
Like any other attribute you can add the placeholder
to the AttributeCollection
:
txtWithHint.Attributes.Add("placeholder", "hint");
From the CREATE TRIGGER documentation:
deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use:
SELECT * FROM deleted
So that at least gives you a way of seeing the new data.
I can't see anything in the docs which specifies that you won't see the inserted data when querying the normal table though...
You just have to hit another Graph API:
https://graph.facebook.com/me?access_token={access-token}
It will give your e-mail Id and user Id (for Facebook) also.
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
var newUrl = refineUrl();
window.history.pushState("object or string", "Title", "/"+newUrl );
}
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url = url.slice( 0, url.indexOf('?') );
//get the part after before ?
value = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');
return value;
}
I use this Swift 5, pure Core Graphics extension that correctly handles non-zero origins in image rects:
extension CGContext {
/// Draw `image` flipped vertically, positioned and scaled inside `rect`.
public func drawFlipped(_ image: CGImage, in rect: CGRect) {
self.saveGState()
self.translateBy(x: 0, y: rect.origin.y + rect.height)
self.scaleBy(x: 1.0, y: -1.0)
self.draw(image, in: CGRect(origin: CGPoint(x: rect.origin.x, y: 0), size: rect.size))
self.restoreGState()
}
}
You can use it exactly like CGContext
's regular draw(: in:)
method:
ctx.drawFlipped(myImage, in: myRect)
You can use gdb for this like objdump.
This excerpt is taken from http://sources.redhat.com/gdb/current/onlinedocs/gdb_9.html#SEC64
Here is an example showing mixed source+assembly for Intel x86:
(gdb) disas /m main Dump of assembler code for function main: 5 { 0x08048330 : push %ebp 0x08048331 : mov %esp,%ebp 0x08048333 : sub $0x8,%esp 0x08048336 : and $0xfffffff0,%esp 0x08048339 : sub $0x10,%esp 6 printf ("Hello.\n"); 0x0804833c : movl $0x8048440,(%esp) 0x08048343 : call 0x8048284 7 return 0; 8 } 0x08048348 : mov $0x0,%eax 0x0804834d : leave 0x0804834e : ret End of assembler dump.
It is worth noting, the library that John Slegers mentioned does have a jQuery dependency, however here is a version that is vanilla Javascript.
https://github.com/EldonMcGuinness/querystring.js
I would have simply commented on his post, but I lack the reputation to do so. :/
The example below process the following, albeit irregular, query string:
?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
var qs = "?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";_x000D_
//var qs = "?=&=";_x000D_
//var qs = ""_x000D_
_x000D_
var results = querystring(qs);_x000D_
_x000D_
(document.getElementById("results")).innerHTML =JSON.stringify(results, null, 2);
_x000D_
<script _x000D_
src="https://rawgit.com/EldonMcGuinness/querystring.js/master/dist/querystring.min.js"></script>_x000D_
<pre id="results">RESULTS: Waiting...</pre>
_x000D_
If your values are static, you can use x:Array
:
<Button Command="{Binding MyCommand}">10
<Button.CommandParameter>
<x:Array Type="system:Object">
<system:String>Y</system:String>
<system:Double>10</system:Double>
</x:Array>
</Button.CommandParameter>
</Button>
I solved it eventually with a timeout on the onblur event (thanks to the advice of a friend who is not StackOverflow):
<input id="myInput" onblur="setTimeout(function() {alert(clickSrc);},200);"></input>
<span onclick="clickSrc='mySpan';" id="mySpan">Hello World</span>
Works both in FF and IE.
You want .children()
instead (documentation here):
$(this).closest('tr').children('td.two').text();
Using you current code, make this tweak:
public void listf(String directoryName, List<File> files) {
File directory = new File(directoryName);
// Get all files from a directory.
File[] fList = directory.listFiles();
if(fList != null)
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}
}
I've used the open source control at http://dropdowncheckboxes.codeplex.com/ and been very happy with it. My addition was to allow a list of checked files to use just file names instead of full paths if the 'selected' caption gets too long. My addition is called instead of UpdateSelection in your postback handler:
// Update the caption assuming that the items are files<br/>
// If the caption is too long, eliminate paths from file names<br/>
public void UpdateSelectionFiles(int maxChars) {
StringBuilder full = new StringBuilder();
StringBuilder shorter = new StringBuilder();
foreach (ListItem item in Items) {
if (item.Selected) {
full.AppendFormat("{0}; ", item.Text);
shorter.AppendFormat("{0}; ", new FileInfo(item.Text).Name);
}
}
if (full.Length == 0) Texts.SelectBoxCaption = "Select...";
else if (full.Length <= maxChars) Texts.SelectBoxCaption = full.ToString();
else Texts.SelectBoxCaption = shorter.ToString();
}
First Solution
You can use keyboardType = 'numeric'
for numeric keyboard.
<View style={styles.container}>
<Text style={styles.textStyle}>Enter Number</Text>
<TextInput
placeholder={'Enter number here'}
style={styles.paragraph}
keyboardType="numeric"
onChangeText={value => this.onTextChanged(value)}
value={this.state.number}
/>
</View>
In first case punctuation marks are included ex:- . and -
Second Solution
Use regular expression to remove punctuation marks.
onTextChanged(value) {
// code to remove non-numeric characters from text
this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
}
Please check snack link
I took miku's answer and jsch example code. I then had to download multiple files during the session and preserve original timestamps. This is my example code how to do it, probably many people find it usefull. Please ignore filenameHack() function its my own usecase.
package examples;
import com.jcraft.jsch.*;
import java.io.*;
import java.util.*;
public class ScpFrom2 {
public static void main(String[] args) throws Exception {
Map<String,String> params = parseParams(args);
if (params.isEmpty()) {
System.err.println("usage: java ScpFrom2 "
+ " user=myid password=mypwd"
+ " host=myhost.com port=22"
+ " encoding=<ISO-8859-1,UTF-8,...>"
+ " \"remotefile1=/some/file.png\""
+ " \"localfile1=file.png\""
+ " \"remotefile2=/other/file.txt\""
+ " \"localfile2=file.txt\""
);
return;
}
// default values
if (params.get("port") == null)
params.put("port", "22");
if (params.get("encoding") == null)
params.put("encoding", "ISO-8859-1"); //"UTF-8"
Session session = null;
try {
JSch jsch=new JSch();
session=jsch.getSession(
params.get("user"), // myuserid
params.get("host"), // my.server.com
Integer.parseInt(params.get("port")) // 22
);
session.setPassword( params.get("password") );
session.setConfig("StrictHostKeyChecking", "no"); // do not prompt for server signature
session.connect();
// this is exec command and string reply encoding
String encoding = params.get("encoding");
int fileIdx=0;
while(true) {
fileIdx++;
String remoteFile = params.get("remotefile"+fileIdx);
String localFile = params.get("localfile"+fileIdx);
if (remoteFile == null || remoteFile.equals("")
|| localFile == null || localFile.equals("") )
break;
remoteFile = filenameHack(remoteFile);
localFile = filenameHack(localFile);
try {
downloadFile(session, remoteFile, localFile, encoding);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
try{ session.disconnect(); } catch(Exception ex){}
}
}
private static void downloadFile(Session session,
String remoteFile, String localFile, String encoding) throws Exception {
// send exec command: scp -p -f "/some/file.png"
// -p = read file timestamps
// -f = From remote to local
String command = String.format("scp -p -f \"%s\"", remoteFile);
System.console().printf("send command: %s%n", command);
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command.getBytes(encoding));
// get I/O streams for remote scp
byte[] buf=new byte[32*1024];
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
// reply: T<mtime> 0 <atime> 0\n
// times are in seconds, since 1970-01-01 00:00:00 UTC
int c=checkAck(in);
if(c!='T')
throw new IOException("Invalid timestamp reply from server");
long tsModified = -1; // millis
for(int idx=0; ; idx++){
in.read(buf, idx, 1);
if(tsModified < 0 && buf[idx]==' ') {
tsModified = Long.parseLong(new String(buf, 0, idx))*1000;
} else if(buf[idx]=='\n') {
break;
}
}
buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
// reply: C0644 <binary length> <filename>\n
// length is given as a text "621873" bytes
c=checkAck(in);
if(c!='C')
throw new IOException("Invalid filename reply from server");
in.read(buf, 0, 5); // read '0644 ' bytes
long filesize=-1;
for(int idx=0; ; idx++){
in.read(buf, idx, 1);
if(buf[idx]==' ') {
filesize = Long.parseLong(new String(buf, 0, idx));
break;
}
}
// read remote filename
String origFilename=null;
for(int idx=0; ; idx++){
in.read(buf, idx, 1);
if(buf[idx]=='\n') {
origFilename=new String(buf, 0, idx, encoding); // UTF-8, ISO-8859-1
break;
}
}
System.console().printf("size=%d, modified=%d, filename=%s%n"
, filesize, tsModified, origFilename);
buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
// read binary data, write to local file
FileOutputStream fos = null;
try {
File file = new File(localFile);
fos = new FileOutputStream(file);
while(filesize > 0) {
int read = Math.min(buf.length, (int)filesize);
read=in.read(buf, 0, read);
if(read < 0)
throw new IOException("Reading data failed");
fos.write(buf, 0, read);
filesize -= read;
}
fos.close(); // we must close file before updating timestamp
fos = null;
if (tsModified > 0)
file.setLastModified(tsModified);
} finally {
try{ if (fos!=null) fos.close(); } catch(Exception ex){}
}
if(checkAck(in) != 0)
return;
buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
System.out.println("Binary data read");
}
private static int checkAck(InputStream in) throws IOException {
// b may be 0 for success
// 1 for error,
// 2 for fatal error,
// -1
int b=in.read();
if(b==0) return b;
else if(b==-1) return b;
if(b==1 || b==2) {
StringBuilder sb=new StringBuilder();
int c;
do {
c=in.read();
sb.append((char)c);
} while(c!='\n');
throw new IOException(sb.toString());
}
return b;
}
/**
* Parse key=value pairs to hashmap.
* @param args
* @return
*/
private static Map<String,String> parseParams(String[] args) throws Exception {
Map<String,String> params = new HashMap<String,String>();
for(String keyval : args) {
int idx = keyval.indexOf('=');
params.put(
keyval.substring(0, idx),
keyval.substring(idx+1)
);
}
return params;
}
private static String filenameHack(String filename) {
// It's difficult reliably pass unicode input parameters
// from Java dos command line.
// This dirty hack is my very own test use case.
if (filename.contains("${filename1}"))
filename = filename.replace("${filename1}", "Korilla ABC ÅÄÖ.txt");
else if (filename.contains("${filename2}"))
filename = filename.replace("${filename2}", "test2 ABC ÅÄÖ.txt");
return filename;
}
}
That's exactly why the "fuser -m /mount/point" exists.
BTW, I don't think "fuser" or "lsof" will indicate when a resource is held by kernel module, although I don't usually have that issue..
without much ado:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
parameter '..' makes navigation one level up, i.e. parent :)
It is because you haven't qualified Cells(1, 1)
with a worksheet object, and the same holds true for Cells(10, 2)
. For the code to work, it should look something like this:
Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
Alternately:
With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range
also, like so:
ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
or
With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
How to find out what this MySQL Error is trying to say:
#1064 - You have an error in your SQL syntax;
This error has no clues in it. You have to double check all of these items to see where your mistake is:
!@#$%^&*()-_=+[]{}\|;:'",<>/?
select
, into
, or countless others. Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
You can use this plugin very easily. From the docs:
var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)
And also set the name of the fields if you wish:
mongoose.plugin(timestamps, {
createdAt: 'created_at',
updatedAt: 'updated_at'
});
The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end
).
The solution: use backticks around the offending column name:
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
With the added backticks around end
, the query works as expected.
IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS
Source: This Hive ticket from the Facebook Phabricator tracker
UPDATE
Now we need to use Custom Targets
SAMPLE CODE
Glide.with(mContext)
.asBitmap()
.load("url")
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
How does one use glide to download an image into a bitmap?
The above all answer are correct but outdated
because in new version of Glide implementation 'com.github.bumptech.glide:glide:4.8.0'
You will find below error in code
.asBitmap()
is not available in glide:4.8.0
SimpleTarget<Bitmap>
Here is solution
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Glide.with(this)
.load("")
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
.into(new Target<Drawable>() {
@Override
public void onLoadStarted(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
}
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
Bitmap bitmap = drawableToBitmap(resource);
imageView.setImageBitmap(bitmap);
// now you can use bitmap as per your requirement
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void getSize(@NonNull SizeReadyCallback cb) {
}
@Override
public void removeCallback(@NonNull SizeReadyCallback cb) {
}
@Override
public void setRequest(@Nullable Request request) {
}
@Nullable
@Override
public Request getRequest() {
return null;
}
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void onDestroy() {
}
});
}
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
Swift 3: Chage ViewController withOut Segue and send AnyObject Use: Identity MainPageViewController on target ViewController
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
or if you want to Change View Controller and send Data
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
let dataToSend = "**Any String**" or var ObjectToSend:**AnyObject**
mainPage.getData = dataToSend
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
Try this, it will give you queries currently running for more than 60 seconds. Note that it prints multiple lines per running query if the SQL has multiple lines. Look at the sid,serial# to see what belongs together.
select s.username,s.sid,s.serial#,s.last_call_et/60 mins_running,q.sql_text from v$session s
join v$sqltext_with_newlines q
on s.sql_address = q.address
where status='ACTIVE'
and type <>'BACKGROUND'
and last_call_et> 60
order by sid,serial#,q.piece
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'))
Either
Method 2 by step
Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.
If you want to set both (your image and title) use the following code:
btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];
The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll()
.
var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove();
The querySelectorAll()
function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var
, then you can pass it as an argument to jquery remove()
.
I am not sure but you can try intialising handler to null in onDestroy()
I think the annotation you are looking for is:
public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;
And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
I don't believe there is a direct supported way. However, if you are desparate, then under navigation options, select to show system objects. Then in your table list, system tables will appear. Two tables are of interest here: MSysIMEXspecs and MSysIMEXColumns. You'll be able edit import and export information. Good luck!
For new XAMPP-VM
for Mac OS X,
I change the ownership to daemon
user and solve the problem.
For example,
$ chown -R daemon:daemon /opt/lampp/htdocs/hello-laravel/storage
It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".
maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi
Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.
Public: https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6/11.2.0.4
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.
https://www.youtube.com/watch?v=jV8B24rSN5o
I think you can use display as grid:
.parent { display: grid };
For me it has worked execute the gradle task 'clean' (under :app, at Gradle pane, usually located at the right) and run again the project.
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Just type git reset
it will revert back and it is like you never typed git add .
since your last commit. Make sure you have committed before.
- There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?
noexcept
is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept
property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.
If you have a function that cannot throw, ask yourself whether it will like stay noexcept
or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept
.
On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept
. However, keep in mind that the compiler will not be able to detect violations of noexcept
if your implementation changes.
- For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?
There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:
noexcept(true)
unless you make them noexcept(false)
)These functions should generally be noexcept
, and it is most likely that library implementations can make use of the noexcept
property. For example, std::vector
can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).
This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.
- When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.
The advantage of noexcept
against no exception specification or throw()
is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw()
case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).
In the noexcept
case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.
The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.
I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.
.myDiv { height: 150px; width 150px; }
<div class="mainDiv">
<div class="myDiv"></div>
<div class="myDiv"></div>
<div class="myDiv"></div>
</div>
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
A pseudo element works best.
a, a:hover {
position: relative;
text-decoration: none;
}
a:after {
content: '';
display: block;
position: absolute;
height: 0;
top:90%;
left: 0;
right: 0;
border-bottom: solid 1px red;
}
See jsfiddle.
You don't need any extra elements, you can position it as close or far as you want from the text (border-bottom is kinda far for my liking), there aren't any extra colors that show up if your link is over a different colored background (like with the box-shadow trick), and it works in all browsers (text-decoration-color only supports Firefox as of yet).
Possible downside: The link can't be position:static, but that's probably not a problem the vast majority of the time. Just set it to relative and all is good.
The most efficient, but not the C++ way would be:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
#
EDIT - 2Just tested the std::filebuf
variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary
and rb
) modes.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
cout<< "Hello";
printf("%s", "Hello");
Both are used to print values. They have completely different syntax. C++ has both, C only has printf.
Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.
I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).
I found a better way to do it now:
def status=(value)
self[:status] = 'P'
end
In Ruby a method call is allowed to have no parentheses, therefore I should name the local variable into something else, otherwise Ruby will recognize it as a method call.
Here's a simple single threaded sleep based version that drifts, but tries to auto-correct when it detects drift.
NOTE: This will only work if the following 3 reasonable assumptions are met:
-
from datetime import timedelta
from datetime import datetime
def exec_every_n_seconds(n,f):
first_called=datetime.now()
f()
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=n)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
f()
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
print "drift=",drift
If a profiler is not applicable in your setup, you may try to identify the thread following steps in this post.
Basically, there are three steps:
top -H
and get PID of the thread with highest CPU.varbinary(max)
is the way to go (introduced in SQL Server 2005)
You can't do that with Mockito but you can use Powermock to extend Mockito and mock private methods. Powermock supports Mockito. Here's an example.
I love code examples (as well as fruit), so let me show you
apple = "apple"
print(apple)
>>> apple
apple = None
print(apple)
>>> None
None means nothing, it has no value.
None evaluates to False.
Depending on which browsers you have to support, this can be done in a number of ways. The overwhelming majority of browsers in the wild support ECMAScript 5 (ES5), but be warned that many of the examples below use Object.keys
, which is not available in IE < 9. See the compatibility table.
If you have to support older versions of IE, then this is the option for you:
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var val = obj[key];
// use val
}
}
The nested if
makes sure that you don't enumerate over properties in the prototype chain of the object (which is the behaviour you almost certainly want). You must use
Object.prototype.hasOwnProperty.call(obj, key) // ok
rather than
obj.hasOwnProperty(key) // bad
because ECMAScript 5+ allows you to create prototypeless objects with Object.create(null)
, and these objects will not have the hasOwnProperty
method. Naughty code might also produce objects which override the hasOwnProperty
method.
You can use these methods in any browser that supports ECMAScript 5 and above. These get values from an object and avoid enumerating over the prototype chain. Where obj
is your object:
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var val = obj[keys[i]];
// use val
}
If you want something a little more compact or you want to be careful with functions in loops, then Array.prototype.forEach
is your friend:
Object.keys(obj).forEach(function (key) {
var val = obj[key];
// use val
});
The next method builds an array containing the values of an object. This is convenient for looping over.
var vals = Object.keys(obj).map(function (key) {
return obj[key];
});
// use vals array
If you want to make those using Object.keys
safe against null
(as for-in
is), then you can do Object.keys(obj || {})...
.
Object.keys
returns enumerable properties. For iterating over simple objects, this is usually sufficient. If you have something with non-enumerable properties that you need to work with, you may use Object.getOwnPropertyNames
in place of Object.keys
.
Arrays are easier to iterate with ECMAScript 2015. You can use this to your advantage when working with values one-by–one in a loop:
for (const key of Object.keys(obj)) {
const val = obj[key];
// use val
}
Using ECMAScript 2015 fat-arrow functions, mapping the object to an array of values becomes a one-liner:
const vals = Object.keys(obj).map(key => obj[key]);
// use vals array
ECMAScript 2015 introduces Symbol
, instances of which may be used as property names. To get the symbols of an object to enumerate over, use Object.getOwnPropertySymbols
(this function is why Symbol
can't be used to make private properties). The new Reflect
API from ECMAScript 2015 provides Reflect.ownKeys
, which returns a list of property names (including non-enumerable ones) and symbols.
Array comprehensions were removed from ECMAScript 6 before publication. Prior to their removal, a solution would have looked like:
const vals = [for (key of Object.keys(obj)) obj[key]];
// use vals array
ECMAScript 2016 adds features which do not impact this subject. The ECMAScript 2017 specification adds Object.values
and Object.entries
. Both return arrays (which will be surprising to some given the analogy with Array.entries
). Object.values
can be used as is or with a for-of
loop.
const values = Object.values(obj);
// use values array or:
for (const val of Object.values(obj)) {
// use val
}
If you want to use both the key and the value, then Object.entries
is for you. It produces an array filled with [key, value]
pairs. You can use this as is, or (note also the ECMAScript 2015 destructuring assignment) in a for-of
loop:
for (const [key, val] of Object.entries(obj)) {
// use key and val
}
Object.values
shimFinally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object
(which is much less dangerous). Using fat-arrow functions, this can be done in one line too:
Object.values = obj => Object.keys(obj).map(key => obj[key]);
which you can now use like
// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });
If you want to avoid shimming when a native Object.values
exists, then you can do:
Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));
Be aware of the browsers/versions you need to support. The above are correct where the methods or language features are implemented. For example, support for ECMAScript 2015 was switched off by default in V8 until recently, which powered browsers such as Chrome. Features from ECMAScript 2015 should be be avoided until the browsers you intend to support implement the features that you need. If you use babel to compile your code to ECMAScript 5, then you have access to all the features in this answer.
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
Identifying the column is easy:
SELECT *
FROM ( SELECT id,
time
FROM dbo.a
UNION
SELECT id,
time
FROM dbo.b
)
GROUP BY id
But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION
rather than UNION ALL
, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).
So, for example, change the first line to SELECT id, MAX(time)
or the like!
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
The two approaches offered thus far fail with large data sets as (amongst other memory issues) they create is.na(df)
, which will be an object the same size as df
.
Here are two approaches that are more memory and time efficient
An approach using Filter
Filter(function(x)!all(is.na(x)), df)
and an approach using data.table (for general time and memory efficiency)
library(data.table)
DT <- as.data.table(df)
DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]
big_data <- replicate(10, data.frame(rep(NA, 1e6), sample(c(1:8,NA),1e6,T), sample(250,1e6,T)),simplify=F)
bd <- do.call(data.frame,big_data)
names(bd) <- paste0('X',seq_len(30))
DT <- as.data.table(bd)
system.time({df1 <- bd[,colSums(is.na(bd) < nrow(bd))]})
# error -- can't allocate vector of size ...
system.time({df2 <- bd[, !apply(is.na(bd), 2, all)]})
# error -- can't allocate vector of size ...
system.time({df3 <- Filter(function(x)!all(is.na(x)), bd)})
## user system elapsed
## 0.26 0.03 0.29
system.time({DT1 <- DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]})
## user system elapsed
## 0.14 0.03 0.18
Adding the
autocomplete="off"
to the form tag will disable the browser autocomplete (what was previously typed into that field) from all input
fields within that particular form.
Tested on:
Yes, take a look at this thread which talks about the differences between platforms.
How to detect right-click event for Mac OS
BUTTON3
is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.
"What's your favourite debugger?"
"What's your favourite profiler?"
The actual application/ide/frontend doesn't matter much as long as it goes beyond "notepad, echo and microtime()". It's so unlikely you hire the one in a billion developer that writes perfect code all the time and his/her unit tests spotted all the errors and bottlenecks before they even occur that you want someone who can profile and/or step through the code and find errors in finite time. (That's true for probably all languages/platforms but it seems a bit of an underdeveloped skill-set amongst php developers to me, purely subjective speaking)
this is answer for your question.
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
int RowIndex = gvr.RowIndex;
There could be 3 solution from this posting and other answer.
Solution 1
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('up 1');
}
else {
console.log('down 1');
}
lastScrollTop = st;
});
Solution 2
$('body').on('DOMMouseScroll', function(e){
if(e.originalEvent.detail < 0) {
console.log('up 2');
}
else {
console.log('down 2');
}
});
Solution 3
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('up 3');
}
else {
console.log('down 3');
}
});
I couldn't tested it on Safari
chrome 42 (Win 7)
Firefox 37 (Win 7)
IE 11 (Win 8)
IE 10 (Win 7)
IE 9 (Win 7)
IE 8 (Win 7)
I checked that side effect from IE 11 and IE 8 is come from
if else
statement. So, I replaced it withif else if
statement as following.
From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.
I referred this answer to detect IE 11.
// Detect IE version
var iev=0;
var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var rv=navigator.userAgent.indexOf("rv:11.0");
if (ieold) iev=new Number(RegExp.$1);
if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
if (trident&&rv!=-1) iev=11;
// Firefox or IE 11
if(typeof InstallTrigger !== 'undefined' || iev == 11) {
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('Up');
}
else if(st > lastScrollTop) {
console.log('Down');
}
lastScrollTop = st;
});
}
// Other browsers
else {
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('Up');
}
else if(e.originalEvent.wheelDelta < 0) {
console.log('Down');
}
});
}
An interface with only one abstract method is called Functional Interface. It is not mandatory to use @FunctionalInterface, but it’s best practice to use it with functional interfaces to avoid addition of extra methods accidentally. If the interface is annotated with @FunctionalInterface annotation and we try to have more than one abstract method, it throws compiler error.
package com.akhi;
@FunctionalInterface
public interface FucnctionalDemo {
void letsDoSomething();
//void letsGo(); //invalid because another abstract method does not allow
public String toString(); // valid because toString from Object
public boolean equals(Object o); //valid
public static int sum(int a,int b) // valid because method static
{
return a+b;
}
public default int sub(int a,int b) //valid because method default
{
return a-b;
}
}
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
You can simply do conditional check before doing map like
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
})
}
Now a days .map can be done in two different ways but still the conditional check is required like
.map with return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
return <li key={player.championId}>{player.summonerName}</li>
})
}
.map without return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
return <li key={player.championId}>{player.summonerName}</li>
))
}
both the above functionalities does the same
This should work but must be used within an unsafe context:
byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
IntPtr ptr = (IntPtr)p;
// do you stuff here
}
beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.
I found using the minimal stdout_callback
with ansible-playbook gave similar output to using ad-hoc ansible.
In your ansible.cfg (Note that I'm on OS X so modify the callback_plugins
path to suit your install)
stdout_callback = minimal
callback_plugins = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ansible/plugins/callback
So that a ansible-playbook
task like yours
---
-
hosts: example
gather_facts: no
tasks:
- shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
Gives output like this, like an ad-hoc command would
example | SUCCESS | rc=0 >>
%CPU USER COMMAND
0.2 root sshd: root@pts/3
0.1 root /usr/sbin/CROND -n
0.0 root [xfs-reclaim/vda]
0.0 root [xfs_mru_cache]
I'm using ansible-playbook 2.2.1.0
Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.
I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags
option descibed above. The option is described as following annotated tags. My tags were simple tags.
I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).
Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.
When I did a similar push with Git GUI, the tags were sent.
For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags
.
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
if you are looking for a boolean, the quickest way would be
var values = [_x000D_
{ name: 'someName1' },_x000D_
{ name: 'someName2' },_x000D_
{ name: 'someName1' },_x000D_
{ name: 'someName1' }_x000D_
]_x000D_
_x000D_
// solution_x000D_
var hasDuplicate = false;_x000D_
values.map(v => v.name).sort().sort((a, b) => {_x000D_
if (a === b) hasDuplicate = true_x000D_
})_x000D_
console.log('hasDuplicate', hasDuplicate)
_x000D_
Had been over looking the issue having surfaced it. Believe this will be a good read for others who come down here with the same issue:
I think this is what you want:
REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'
echo "$1" | grep -P -q $REGEX_DATE
echo $?
I've used the -P switch to get perl regex.
Starting from tonight nightly build of 4.6/Neon, the Eclipse Platform includes a way to increase/decrease font size on text editors using Ctrl+ and Ctrl- (on Windows or Linux, Cmd= and Cmd- on Mac OS X) : https://www.eclipse.org/eclipse/news/4.6/M4/#text-zoom-commands . The implementation is shipped with any product using a recent build of the platform, and is more reliable that the one in the alternative plugins mentioned above. It will be more widely available within weeks, when the IDE packages for Neon M4 will be available, and it will be part of the public Neon release in June 2016.
I think your code is correct unlike the other answer suggested. onPostExecute will run on the UI thread. That's the whole point of AsyncTask - you don't have to worry about calling runOnUiThread or deal with handlers. Furthermore, according to the docs, dismiss() can be safely called from any thread (not sure they made this the exception).
Perhaps it's a timing issue where dialog.dismiss() is getting called after the activity is no longer displayed?
What about testing what happens if you comment out the setOnCancelListener and then exit the activity while the background task is running? Then your onPostExecute will try to dismiss an already dismissed dialog. If the app crashes you can probably just check if the dialog is open before dismissing it.
I'm having the exact same problem so I'm going to try it out in code.
Installation lxml
pip install lxml
If you get an error like "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?", try to do this first:
# Debian/Ubuntu
apt-get install python-dev python3-dev libxml2-dev libxslt-dev
# Fedora 23+
dnf install python-devel python3-devel libxml2-devel libxslt-devel
The simplest validator
Let's create simplest validator.py
from lxml import etree
def validate(xml_path: str, xsd_path: str) -> bool:
xmlschema_doc = etree.parse(xsd_path)
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_doc = etree.parse(xml_path)
result = xmlschema.validate(xml_doc)
return result
then write and run main.py
from validator import validate
if validate("path/to/file.xml", "path/to/scheme.xsd"):
print('Valid! :)')
else:
print('Not valid! :(')
A little bit of OOP
In order to validate more than one file, there is no need to create an XMLSchema object every time, therefore:
validator.py
from lxml import etree
class Validator:
def __init__(self, xsd_path: str):
xmlschema_doc = etree.parse(xsd_path)
self.xmlschema = etree.XMLSchema(xmlschema_doc)
def validate(self, xml_path: str) -> bool:
xml_doc = etree.parse(xml_path)
result = self.xmlschema.validate(xml_doc)
return result
Now we can validate all files in the directory as follows:
main.py
import os
from validator import Validator
validator = Validator("path/to/scheme.xsd")
# The directory with XML files
XML_DIR = "path/to/directory"
for file_name in os.listdir(XML_DIR):
print('{}: '.format(file_name), end='')
file_path = '{}/{}'.format(XML_DIR, file_name)
if validator.validate(file_path):
print('Valid! :)')
else:
print('Not valid! :(')
For more options read here: Validation with lxml
If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')
Then I'd use JSON.net and use Linq to JSON to get the values out...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["items"] != null)
{
var items = Request["items"].ToString(); // Get the JSON string
JArray o = JArray.Parse(items); // It is an array so parse into a JArray
var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
// a == "Charles"
}
}
}
It only worked for me in Firefox when accessing it from the window
object.
Example...
window.onload = function()
{
window.localStorage.clear();
}
Well I'm not sure about the regex or your situation..
How about CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines and viola all blank line gone.
A side note - if the line is blank i.e. does not contain spaces, this will work
Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.
>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1., 2.],
[ 1., 2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1., 3.],
[ 2., 3.]])
>>> t = np.floor(x)
>>> t
array([[ 1., 2.],
[ 1., 2.]])
>>> a = np.rint(x)
>>> a
array([[ 1., 2.],
[ 1., 3.]])
To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):
a.astype(int)
array([[1, 2],
[1, 3]])
>>> y.astype(int)
array([[1, 2],
[1, 2]])
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
I'll answer this anyway. Just in case someone needs it.
An activity that watches for notifications for the event named "custom-event-name"
.
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
The second activity that sends/broadcasts notifications.
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Every time a button is clicked, we want to broadcast a notification.
findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
With the code above, every time the button R.id.button_send
is clicked, an Intent is broadcasted and is received by mMessageReceiver
in ReceiverActivity
.
The debug output should look like this:
01-16 10:35:42.413: D/sender(356): Broadcasting message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message!
On Windows, highlight the code that has classes which need to be resolved and hit Alt+Enter
If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.
In your $CATALINA_BASE/conf/context.xml
add block below before </Context>
<Resources cachingAllowed="true" cacheMaxSize="100000" />
For more information: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html
Found the flex magic.
Here's an example of how to do a fixed header and a scrollable content. Code:
<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset=utf-8 />
<title>Holy Grail</title>
<!-- Reset browser defaults -->
<link rel="stylesheet" href="reset.css">
</head>
<body style="display: flex; height: 100%; flex-direction: column">
<div>HEADER<br/>------------
</div>
<div style="flex: 1; overflow: auto">
CONTENT - START<br/>
<script>
for (var i=0 ; i<1000 ; ++i) {
document.write(" Very long content!");
}
</script>
<br/>CONTENT - END
</div>
</body>
</html>
* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.
For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
Here is how I do it:
app.directive('example', function() {
return function(scope, element, attrs) {
angular.element(document).ready(function() {
//MANIPULATE THE DOM
});
};
});
Try this, this should work,
td input[type="checkbox"] {
float: left;
margin: 0 auto;
width: 100%;
}
in my case the fix was replacing
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
with
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'
sample:
getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI
Use $() to assign the output of cat
to your variable like this:
VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)
# this will echo variable with new lines intact
echo "$VAR"
# this will echo variable without new lines (changed to space character)
echo $VAR
Making sure to delimit starting END_HEREDOC with single-quotes.
Note that ending heredoc delimiter END_HEREDOC
must be alone on the line (hence ending parenthesis is on the next line).
Thanks to @ephemient
for the answer.
If you want:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]
Then here is your solution for Python 2:
c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
In Python 3 filter
returns an iterable instead of list
, so you need to wrap filter
calls with list()
:
c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
Explanation:
The filter part takes each sublist's item and checks to see if it is in the source list c1. The list comprehension is executed for each sublist in c2.
try
window.frameElement.ownerDocument.domain
I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:
http://github.com/mastermind202/GoogleVoice
I hope others find it useful. Feedback and suggestions welcome.
There are two ways to do it.
In the method that opens the dialog, pass in the following configuration option disableClose
as the second parameter in MatDialog#open()
and set it to true
:
export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
Alternatively, do it in the dialog component itself.
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
Here's what you're looking for:
And here's a Stackblitz demo
Here's some other use cases and code snippets of how to implement them.
As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:
import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
P.S. This is an answer which originated from this answer, where the demo was based on this answer.
To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialog will have the configuration option disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialog to close.
Afterwards, subscribe to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
Alternatively, this can be done in the dialog component:
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
No IEnumerable is an interface, you can't create instance of interface
you can do something like this
IEnumerable<object> a = new object[0];
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';
At a place where you want javadoc, type in /**
<NEWLINE> and it will create the template.
Not sure of this is helpful but this what worked for me in Rails 4
Foo.where.not(bar: nil)
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
var folder = "img/";_x000D_
_x000D_
$.ajax({_x000D_
url : folder,_x000D_
success: function (data) {_x000D_
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"_x000D_
var result = data.match(patt1);_x000D_
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!_x000D_
_x000D_
var uniqueNames = []; // this array will help to remove duplicate images_x000D_
$.each(result, function(i, el){_x000D_
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded_x000D_
console.log("under analysis: " + el);_x000D_
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){_x000D_
console.log("adding " + el_url_encoded);_x000D_
uniqueNames.push(el_url_encoded);_x000D_
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML_x000D_
} else{ console.log(el_url_encoded + " already in!"); }_x000D_
});_x000D_
},_x000D_
error: function(xhr, textStatus, err) {_x000D_
alert('Error: here we go...');_x000D_
alert(textStatus);_x000D_
alert(err);_x000D_
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);_x000D_
alert("responseText: "+xhr.responseText);_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
MySQL Workbench 8.0 Update
Based on Gunther's answer, it seems like in code_editor.xml
they're planning to enable a dark mode at some point down the road. What was once fore-color
has now been split into fore-color-light
and fore-color-dark
. Likewise with back-color
.
Here's how to get a dark editor (not whole application theme) based on the Monokai colours provided graciously by elMestre:
<!--
dark-gray: #282828;
brown-gray: #49483E;
gray: #888888;
light-gray: #CCCCCC;
ghost-white: #F8F8F0;
light-ghost-white: #F8F8F2;
yellow: #E6DB74;
blue: #66D9EF;
pink: #F92672;
purple: #AE81FF;
brown: #75715E;
orange: #FD971F;
light-orange: #FFD569;
green: #A6E22E;
sea-green: #529B2F;
-->
<style id="32" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- STYLE_DEFAULT !BACKGROUND! -->
<style id="33" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- STYLE_LINENUMBER -->
<style id= "0" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_DEFAULT -->
<style id= "1" fore-color-light="#999999" back-color-light="#282828" fore-color-dark="#999999" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id= "2" fore-color-light="#999999" back-color-light="#282828" fore-color-dark="#999999" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id= "3" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id= "4" fore-color-light="#66D9EF" back-color-light="#282828" fore-color-dark="#66D9EF" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id= "5" fore-color-light="#66D9EF" back-color-light="#282828" fore-color-dark="#66D9EF" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id= "6" fore-color-light="#AE81FF" back-color-light="#282828" fore-color-dark="#AE81FF" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id= "7" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id= "8" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id= "9" fore-color-light="#9B859D" back-color-light="#282828" fore-color-dark="#9B859D" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="10" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="11" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="12" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="13" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="14" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="15" fore-color-light="#9B859D" back-color-light="#282828" fore-color-dark="#9B859D" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="16" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="17" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="18" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="19" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="20" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="21" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="22" fore-color-light="#909090" back-color-light="#49483E" fore-color-dark="#909090" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color-light="#999999" back-color-light="#49483E" fore-color-dark="#999999" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id="66" fore-color-light="#999999" back-color-light="#49483E" fore-color-dark="#999999" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id="67" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id="68" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id="69" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id="70" fore-color-light="#AE81FF" back-color-light="#49483E" fore-color-dark="#AE81FF" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id="71" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id="72" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id="73" fore-color-light="#9B859D" back-color-light="#49483E" fore-color-dark="#9B859D" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="74" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="75" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="76" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="77" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="78" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="79" fore-color-light="#9B859D" back-color-light="#49483E" fore-color-dark="#9B859D" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="80" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="81" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="82" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="83" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="84" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="85" fore-color-light="#66D9EF" back-color-light="#888888" fore-color-dark="#66D9EF" back-color-dark="#888888" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="86" fore-color-light="#AAAAAA" back-color-light="#888888" fore-color-dark="#AAAAAA" back-color-dark="#888888" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
Remember to paste all these styles inside of the <language name="SCLEX_MYSQL">
tag in data > code_editor.xml
.
This is simple code. You can try it and grab the knowledge easily.
n = int(input('Enter integer : '))
if n % 2 == 3`8huhubuiiujji`:
print('digit entered is ODD')
elif n % 2 == 0 and 2 < n < 5:
print('EVEN AND in between [2,5]')
elif n % 2 == 0 and 6 < n < 20:
print('EVEN and in between [6,20]')
elif n % 2 == 0 and n > 20:
print('Even and greater than 20')
and so on...
Actually it's not an error! It means you should enter some message to mark this merge. My OS is Ubuntu 14.04.If you use the same OS, you just need to do this as follows:
Type some message
CtrlCO
Type the file name (such as "Merge_feature01") and press Enter
CtrlX to exit
Now if you go to .git and you will find the file "Merge_feature01", that's the merge log actually.
No rocket scien code require .Hope this simple and short code will help.
List linesList = File.ReadAllLines("myFile.txt").ToList();
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());
OR use this
public void DeleteLinesFromFile(string strLineToDelete)
{
string strFilePath = "Provide the path of the text file";
string strSearchText = strLineToDelete;
string strOldText;
string n = "";
StreamReader sr = File.OpenText(strFilePath);
while ((strOldText = sr.ReadLine()) != null)
{
if (!strOldText.Contains(strSearchText))
{
n += strOldText + Environment.NewLine;
}
}
sr.Close();
File.WriteAllText(strFilePath, n);
}
You can use method reference like this:
user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);
Method ifPresent()
get Consumer
object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user
.
Or if this method doSomethingWithUser
is in the User
class and it is not static
, you can use method reference like this:
user.ifPresent(this::doSomethingWithUser);
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
create table articles(code varchar2(30)constraint articles_pk primary key,titre varchar2(30),
support varchar2(30) constraint support_fk references supports(support),type_support varchar2(30),
numeroDePage varchar2(30),datepublication date,categorie varchar2(30)constraint categorie_fk references organismes(categorie),
tendance varchar2(30)constraint tendance_fk references apreciations(tendance));
In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.
Start by defining a generic function pointer type:
typedef int (__stdcall* func_ptr_t)();
What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
In this array we can store the actual function pointers that point into the DLL memory space.
Next problem is that GetProcAddress
expects the function names as strings. So create a similar array consisting of the function names in the DLL:
const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] =
{
"dll_add",
"dll_subtract",
"dll_do_stuff",
...
};
Now we can easily call GetProcAddress() in a loop and store each function inside that array:
for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);
if(func_ptr[i] == NULL)
{
// error handling, most likely you have to terminate the program here
}
}
If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:
typedef struct
{
int (__stdcall* dll_add_ptr)(int, int);
int (__stdcall* dll_subtract_ptr)(int, int);
void (__stdcall* dll_do_stuff_ptr)(something);
...
} functions_struct;
And finally, to connect these to the array from before, create a union:
typedef union
{
functions_struct by_type;
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
} functions_union;
Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type
union member.
But of course, it is a bit burdensome to type out something like
functions.by_type.dll_add_ptr(1, 1);
whenever you want to call a function.
As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:
#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)
And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:
int result = dll_add(1, 1);
Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.
Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert
to ensure that the struct/union has no padding might be in order still.
I suggest the following:
import ast
def is_int(s):
return isinstance(ast.literal_eval(s), int)
From the docs:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
I should note that this will raise a ValueError
exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:
from ast import literal_eval
from contextlib import suppress
def is_int(s):
with suppress(ValueError):
return isinstance(literal_eval(s), int)
return False
¯\_(?)_/¯
Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.
From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s
Update: its not true anymore, <meta name="viewport" content="width=device-width">
is enough to remove 300ms delay
Use a common table expression to add grand total row, top 100
is required for order by
to work.
With Detail as
(
SELECT top 100 propertyId, SUM(Amount) as TOTAL_COSTS
FROM MyTable
WHERE EndDate IS NULL
GROUP BY propertyId
ORDER BY TOTAL_COSTS desc
)
Select * from Detail
Union all
Select ' Total ', sum(TOTAL_COSTS) from Detail
You need to give it a container with a height. width uses the viewport as the default width
If you use linq and want to keep your code short, I recommand to always use !=null
And this is why:
Let imagine we have some class Foo
with a nullable double variable SomeDouble
public class Foo
{
public double? SomeDouble;
//some other properties
}
If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :
public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
return foos.Where(foo => foo?.SomeDouble != null);
return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
return foos.Where(foo=>foo?.SomeDouble.HasValue == true);
return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}
And in this kind of situation I recommand to always go for the shorter one
This works for me:
@echo OFF
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command Processor"
set VALUE_NAME=DefaultColor
FOR /F "usebackq skip=4 tokens=1-3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueName=%%A
set ValueType=%%B
set ValueValue=%%C
)
if defined ValueName (
@echo Value Name = %ValueName%
@echo Value Type = %ValueType%
@echo Value Value = %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found.
)
usebackq
is needed since the command to REG QUERY
uses double quotes.
skip=4
ignores all the output except for the line that has the value name, type and value, if it exists.
2^>nul
prevents the error text from appearing. ^
is the escape character that lets you put the >
in the for
command.
When I run the script above as given, I get this output:
Value Name = DefaultColor
Value Type = REG_DWORD
Value Value = 0x0
If I change the value of VALUE_NAME
to BogusValue
then I get this:
"HKEY_CURRENT_USER\Software\Microsoft\Command Processor"\BogusValue not found.
As mentioned in a more recent answer, the preferred way is now simply:
const homedir = require('os').homedir();
[Original Answer]: Why not use the USERPROFILE
environment variable on win32?
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.
And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:
private void MainForm_Shown(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
Hide();
}
I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.
The core function
public int Recv(byte[] buffer, int maxLen)
has name and works like "well known" socket's recv()
.
It means that
TimeoutException
.maxLen
bytes .
public class Uart : SerialPort
{
private int _receiveTimeout;
public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }
static private string ComPortName = "";
/// <summary>
/// It builds PortName using ComPortNum parameter and opens SerialPort.
/// </summary>
/// <param name="ComPortNum"></param>
public Uart(int ComPortNum) : base()
{
base.BaudRate = 115200; // default value
_receiveTimeout = 2000;
ComPortName = "COM" + ComPortNum;
try
{
base.PortName = ComPortName;
base.Open();
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Error: Port {0} is in use", ComPortName);
}
catch (Exception ex)
{
Console.WriteLine("Uart exception: " + ex);
}
} //Uart()
/// <summary>
/// Private property returning positive only Environment.TickCount
/// </summary>
private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }
/// <summary>
/// It uses SerialPort.BaseStream rather SerialPort functionality .
/// It Receives up to maxLen number bytes of data,
/// Or throws TimeoutException if no any data arrived during ReceiveTimeout.
/// It works likes socket-recv routine (explanation in body).
/// Returns:
/// totalReceived - bytes,
/// TimeoutException,
/// -1 in non-ComPortNum Exception
/// </summary>
/// <param name="buffer"></param>
/// <param name="maxLen"></param>
/// <returns></returns>
public int Recv(byte[] buffer, int maxLen)
{
/// The routine works in "pseudo-blocking" mode. It cycles up to first
/// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
/// If no any message received during ReceiveTimeout property,
/// the routine throws TimeoutException
/// In other hand, if any data has received, first no-data cycle
/// causes to exit from routine.
int TimeOutSpan = 2;
// counts delay in TimeOutSpan-s after end of data to break receive
int EndOfDataCnt;
// pseudo-blocking timeout counter
int TimeOutCnt = _tickCount + _receiveTimeout;
//number of currently received data bytes
int justReceived = 0;
//number of total received data bytes
int totalReceived = 0;
BaseStream.ReadTimeout = TimeOutSpan;
//causes (2+1)*TimeOutSpan delay after end of data in UART stream
EndOfDataCnt = 2;
while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
{
try
{
justReceived = 0;
justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
totalReceived += justReceived;
if (totalReceived >= maxLen)
break;
}
catch (TimeoutException)
{
if (totalReceived > 0)
EndOfDataCnt--;
}
catch (Exception ex)
{
totalReceived = -1;
base.Close();
Console.WriteLine("Recv exception: " + ex);
break;
}
} //while
if (totalReceived == 0)
{
throw new TimeoutException();
}
else
{
return totalReceived;
}
} // Recv()
} // Uart
myenv:
python 2.7.14
pip 9.0.1
mac osx 10.9.4
mysolution:
download get-pip.py
manually from https://packaging.python.org/tutorials/installing-packages/
run python get-pip.py
refs:
https://github.com/pypa/warehouse/issues/3293#issuecomment-378468534
https://packaging.python.org/tutorials/installing-packages/
Securely Download get-pip.py [1]
Run python get-pip.py. [2] This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.
Ensure pip, setuptools, and wheel are up to date
While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:
python -m pip install --upgrade pip setuptools wheel
Try to uninstall python3.7.3 using this:-
https://huybien.com/how-to-completely-uninstall-python-on-macos/
No, you're creating an array, but there's a big difference:
char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!
The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:
char string[] = "Some string";
creates the same, read only, constant string, and copies it to the stack array. That's why:
string[1] = 'v';
Is valid in the latter case.
If you write:
char string[] = {"some", " string"};
the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:
char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};
Where the last version gives you an array of strings (arrays of chars) that you actually can edit...
Iterating a bit on Tom Hale's answer, I've found it possible to wrap the redirection yoga into a function for easier reuse. For example:
#!/bin/sh
capture () {
{ captured=$( { { "$@" ; } 1>&3 ; } 2>&1); } 3>&1
}
# Example usage; capturing dialog's output without resorting to temp files
# was what motivated me to search for this particular SO question
capture dialog --menu "Pick one!" 0 0 0 \
"FOO" "Foo" \
"BAR" "Bar" \
"BAZ" "Baz"
choice=$captured
clear; echo $choice
It's almost certainly possible to simplify this further. Haven't tested especially-thoroughly, but it does appear to work with both bash and ksh.
EDIT: an alternative version of the capture
function which stores the captured STDERR output into a user-specified variable (instead of relying on a global $captured
), taking inspiration from Léa Gris's answer while preserving the ksh
(and zsh
) compatibility of the above implementation:
capture () {
if [ "$#" -lt 2 ]; then
echo "Usage: capture varname command [arg ...]"
return 1
fi
typeset var captured; captured="$1"; shift
{ read $captured <<<$( { { "$@" ; } 1>&3 ; } 2>&1); } 3>&1
}
And usage:
capture choice dialog --menu "Pick one!" 0 0 0 \
"FOO" "Foo" \
"BAR" "Bar" \
"BAZ" "Baz"
clear; echo $choice
The only way not to capture something is using look-around assertions:
(?<=123-)((apple|banana)(?=-456)|(?=456))
Because even with non-capturing groups (?:…)
the whole regular expression captures their matched contents. But this regular expression matches only apple
or banana
if it’s preceded by 123-
and followed by -456
, or it matches the empty string if it’s preceded by 123-
and followed by 456
.
|Lookaround | Name | What it Does |
-----------------------------------------------------------------------
|(?=foo) | Lookahead | Asserts that what immediately FOLLOWS the |
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?<=foo) | Lookbehind | Asserts that what immediately PRECEDES the|
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?!foo) | Negative | Asserts that what immediately FOLLOWS the |
| | Lookahead | current position in the string is NOT foo|
-------------------------------------------------------------------------
|(?<!foo) | Negative | Asserts that what immediately PRECEDES the|
| | Lookbehind | current position in the string is NOT foo|
-------------------------------------------------------------------------
ZoneId here = ZoneId.of("Europe/Kiev");
ZonedDateTime hereAndNow = Instant.now().atZone(here);
String.format("%tz", hereAndNow);
will give you a standardized string representation like "+0300"
In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date
I use this for every external link:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
In Bash you can do it by enabling the extglob
option, like this (replace ls
with cp
and add the target directory, of course)
~/foobar> shopt extglob
extglob off
~/foobar> ls
abar afoo bbar bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob # Enables extglob
~/foobar> ls !(b*)
abar afoo
~/foobar> ls !(a*)
bbar bfoo
~/foobar> ls !(*foo)
abar bbar
You can later disable extglob with
shopt -u extglob
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
cd venv
source bin/activate
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
python
\>\> import sys
\>\> sys.path
You are looking for the window.scrollTop()
function.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > some_number) {
// do something
}
});
Try this:
#include <QDebug>
QString string;
// do things...
qDebug() << "right" << string << std::endl;
To expand on persistent's answer, and to provide more of the functionality of NUnit, you can do this:
public bool AssertThrows<TException>(
Action action,
Func<TException, bool> exceptionCondition = null)
where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
if (exceptionCondition != null)
{
return exceptionCondition(ex);
}
return true;
}
catch
{
return false;
}
return false;
}
Examples:
// No exception thrown - test fails.
Assert.IsTrue(
AssertThrows<InvalidOperationException>(
() => {}));
// Wrong exception thrown - test fails.
Assert.IsTrue(
AssertThrows<InvalidOperationException>(
() => { throw new ApplicationException(); }));
// Correct exception thrown - test passes.
Assert.IsTrue(
AssertThrows<InvalidOperationException>(
() => { throw new InvalidOperationException(); }));
// Correct exception thrown, but wrong message - test fails.
Assert.IsTrue(
AssertThrows<InvalidOperationException>(
() => { throw new InvalidOperationException("ABCD"); },
ex => ex.Message == "1234"));
// Correct exception thrown, with correct message - test passes.
Assert.IsTrue(
AssertThrows<InvalidOperationException>(
() => { throw new InvalidOperationException("1234"); },
ex => ex.Message == "1234"));
There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:
numpy.nonzero(array - item)
You could then take the first elements of the lists to get a single element.
using System.Diagnostics;
...
var st = new StackTrace();
var sf = st.GetFrame(0);
var currentMethodName = sf.GetMethod();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
Updated with credits to @stusmith.
-- Note that you can not use an alias over the table where you need delete
DELETE tbl_pagos_activos_usuario
FROM tbl_pagos_activos_usuario, tbl_usuarios b, tbl_facturas c
Where tbl_pagos_activos_usuario.usuario=b.cedula
and tbl_pagos_activos_usuario.cod=c.cod
and tbl_pagos_activos_usuario.rif=c.identificador
and tbl_pagos_activos_usuario.usuario=c.pay_for
and tbl_pagos_activos_usuario.nconfppto=c.nconfppto
and NOT ISNULL(tbl_pagos_activos_usuario.nconfppto)
and c.estatus=50
Seems like you have a single function that you need to call on two different parameters. This can be elegantly done using a combination of concurrent.futures
and map
with Python 3.2+
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def sleep_secs(seconds):
time.sleep(seconds)
print(f'{seconds} has been processed')
secs_list = [2,4, 6, 8, 10, 12]
Now, if your operation is IO bound, then you can use the ThreadPoolExecutor
as such:
with ThreadPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
Note how map
is used here to map
your function to the list of arguments.
Now, If your function is CPU bound, then you can use ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
If you are not sure, you can simply try both and see which one gives you better results.
Finally, if you are looking to print out your results, you can simply do this:
with ThreadPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
for result in results:
print(result)
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
private boolean current;
public void setCurrent(boolean current){
this.current=current;
}
public boolean hasCurrent(){
return this.current;
}
.a
files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.
git fetch
will retrieve remote branches so that you can git diff
or git merge
them with the current branch. git pull
will run fetch on the remote brach tracked by the current branch and then merge the result. You can use git fetch
to see if there are any updates to the remote branch without necessary merging them with your local branch.
Application.DoEvents can create problems, if something other than graphics processing is put in the message queue.
It can be useful for updating progress bars and notifying the user of progress in something like MainForm construction and loading, if that takes a while.
In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.
Use StrictMode Something like this:-
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
you can use cleave.js
// phone (123) 123-4567
var cleavePhone = new Cleave('.input-phone', {
//prefix: '(123)',
delimiters: ['(',') ','-'],
blocks: [0, 3, 3, 4]
});
playing with globals() makes it possible:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
one result:
'alphabet'
'random'
('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')
I used random because you don't explain which names of "variables" to give, and which values to create. Because i don't think it's possible to create a name without making it binded to an object.
hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar
I might be misunderstanding your question, so apologies if I am.
If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong>
tags:
<strong>Quid</strong>: ...
Hope that helps!
Some additional information for anyone who might be struggling with this:
You'll be getting null values if you're trying to get URL from iframe before it's loaded. I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:
var iframe = document.createElement('iframe');
iframe.onload = function() {
//some custom settings
this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
var href = iframe.contentWindow.location.href;
var origin = iframe.contentWindow.location.origin;
var url = iframe.contentWindow.location.url;
var path = iframe.contentWindow.location.pathname;
console.log("href: ", href)
console.log("origin: ", origin)
console.log("path: ", path)
console.log("url: ", url)
};
iframe.src = 'http://localhost/folder/index.html';
document.body.appendChild(iframe);
Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.
Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp
You can use the form
attribute id
to span a form over multiple elements each using the form
attribute with the name of the form as follows:
<table>
<tr>
<td>
<form method="POST" id="form-1" action="/submit/form-1"></form>
<input name="a" form="form-1">
</td>
<td><input name="b" form="form-1"></td>
<td><input name="c" form="form-1"></td>
<td><input type="submit" form="form-1"></td>
</tr>
</table>
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
The backslash \
is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /
.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
Snagged from Oracle OTN forums
Use alter table to add column, for example:
alter table tableName add(columnName NUMBER);
Then create a sequence:
CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;
and, the use update
to insert values in column like this
UPDATE tableName SET columnName = seq_test_id.NEXTVAL
Try the below code if you're Using Python3:
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
or try this...
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
or try this...
import warnings
warnings.filterwarnings("ignore")