const initialState = {
a: '',
b: '',
c: ''
};
class ExampleComponent extends Component {
state = { ...initialState } // use spread operator to avoid mutation
handleReset = this.handleReset.bind(this);
handleReset() {
this.setState(initialState);
}
}
Remember that in order to be able to reset the state it is important not to mutate initialState.
state = {...initialState} // GOOD
// => state points to a new obj in memory which has the values of initialState
state = initialState // BAD
// => they point to the same obj in memory
The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.
state = Object.assign({}, initialState); // GOOD
state = {...initialState}; // GOOD
The question is about to use a variable in a script means to me it will be used in SQL*Plus.
The problem is you missed the quotes and Oracle can not parse the value to number.
SQL> DEFINE num = 2018
SQL> SELECT &num AS your_num FROM dual;
old 1: SELECT &num AS your_num FROM dual
new 1: SELECT 2018 AS your_num FROM dual
YOUR_NUM
----------
2018
Elapsed: 00:00:00.01
This sample is works fine because of automatic type conversion (or whatever it is called).
If you check by typing DEFINE in SQL*Plus, it will shows that num variable is CHAR.
SQL>define
DEFINE NUM = "2018" (CHAR)
It is not a problem in this case, because Oracle can deal with parsing string to number if it would be a valid number.
When the string can not parse to number, than Oracle can not deal with it.
SQL> DEFINE num = 'Doh'
SQL> SELECT &num AS your_num FROM dual;
old 1: SELECT &num AS your_num FROM dual
new 1: SELECT Doh AS your_num FROM dual
SELECT Doh AS your_num FROM dual
*
ERROR at line 1:
ORA-00904: "DOH": invalid identifier
With a quote, so do not force Oracle to parse to number, will be fine:
17:31:00 SQL> SELECT '&num' AS your_num FROM dual;
old 1: SELECT '&num' AS your_num FROM dual
new 1: SELECT 'Doh' AS your_num FROM dual
YOU
---
Doh
So, to answer the original question, it should be do like this sample:
SQL> DEFINE stupidvar = 'X'
SQL>
SQL> SELECT 'print stupidvar:' || '&stupidvar'
2 FROM dual
3 WHERE dummy = '&stupidvar';
old 1: SELECT 'print stupidvar:' || '&stupidvar'
new 1: SELECT 'print stupidvar:' || 'X'
old 3: WHERE dummy = '&stupidvar'
new 3: WHERE dummy = 'X'
'PRINTSTUPIDVAR:'
-----------------
print stupidvar:X
Elapsed: 00:00:00.00
There is an other way to store variable in SQL*Plus by using Query Column Value.
The COL[UMN] has new_value option to store value from query by field name.
SQL> COLUMN stupid_column_name new_value stupid_var noprint
SQL> SELECT dummy || '.log' AS stupid_column_name
2 FROM dual;
Elapsed: 00:00:00.00
SQL> SPOOL &stupid_var.
SQL> SELECT '&stupid_var' FROM DUAL;
old 1: SELECT '&stupid_var' FROM DUAL
new 1: SELECT 'X.log' FROM DUAL
X.LOG
-----
X.log
Elapsed: 00:00:00.00
SQL>SPOOL OFF;
As you can see, X.log value was set into the stupid_var variable, so we can find a X.log file in the current directory has some log in it.
Firstly, there is an issue with the ADT plugin and Helios which causes lag with looking up Android classes - use Galileo instead (v3.5).
Secondly, the emulators become more resource hungry depending on the version of Android you're developing for. Example, I have a P4 2.4GHz, 1GB RAM PC with Win XP 32-bit and an Android v2.2 emulator takes at least 4-5 minutes to load up. An Android v1.6 emulator on the other hand loads up in less than 1 minute. Remember though that once the emulator is up and running, you can leave it loaded and it will be more responsive than first use.
Also bear in mind that if you give your emulator a 2GB SD card (for example) it will try to create that through virtual memory if there isn't enough physical memory.
This link has formulas for what you want. Then it's a matter of performance (numerical techniques) if you want it fast.
Open the file in text wrangler or notepad ++ and show the formating e.g. in text wrangler you do show invisibles. That way you can see the new line or tabs characters Often excel will add all sorts of tabs in the wrong places and not a last new line character, but you need to show the symbols to see this.
I've successfully used OpenPop.NET to access emails via POP3.
Someone already has the answer.
$('video') will return an array of video items. It is totally a valid seletor!
so
$("video").each(function () { this.pause() });
will work.
Here is the simplest possible Swift 5 solution that doesn't require you to create a custom back button and give up all that UINavigationController left button functionality you get for free.
As Brandon A recommends above, you need need to implement UINavigationControllerDelegate
in the view controller you want to interact with before returning to it. A good way is to create an unwind segue that you can perform manually or automatically and reuse the same code from a custom done button or the back button.
First, make your view controller of interest (the one you want to detect returning to) a delegate of the navigation controller in its viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
Second, add an extension at the bottom of the file that overrides navigationController(willShow:animated:)
extension PickerTableViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
willShow viewController: UIViewController,
animated: Bool) {
if let _ = viewController as? EditComicBookViewController {
let selectedItemRow = itemList.firstIndex(of: selectedItemName)
selectedItemIndex = IndexPath(row: selectedItemRow!, section: 0)
if let selectedCell = tableView.cellForRow(at: selectedItemIndex) {
performSegue(withIdentifier: "PickedItem", sender: selectedCell)
}
}
}
}
Since your question included a UITableViewController
, I included a way to get the index path of the row the user tapped.
For all the python3
and pip3
users out there:
curl https://bootstrap.pypa.io/get-pip.py | sudo python3
and then assume you want to install pandas
pip3 install pandas --user
Checking the header file solve's the problem. One can check for there system compiler.
For my system , AF_INET == PF_INET
AF == Address Family And PF == Protocol Family
Protocol families, same as address families.
On Mac:
Per-user config file: ~/.npmrc
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
I'm using python 2.7.13 with scandir and here's my one-liner recursive function to get the total size of a folder:
from scandir import scandir
def getTotFldrSize(path):
return sum([s.stat(follow_symlinks=False).st_size for s in scandir(path) if s.is_file(follow_symlinks=False)]) + \
+ sum([getTotFldrSize(s.path) for s in scandir(path) if s.is_dir(follow_symlinks=False)])
>>> print getTotFldrSize('.')
1203245680
Update, if you are running SQL Server 2012 see: https://stackoverflow.com/a/10309947
The problem is that the SQL Server implementation of the Over clause is somewhat limited.
Oracle (and ANSI-SQL) allow you to do things like:
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM Table
SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.
The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will probably
be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):
Full working sample:
drop table #t
create table #t ( ord int primary key, total int, running_total int)
insert #t(ord,total) values (2,20)
-- notice the malicious re-ordering
insert #t(ord,total) values (1,10)
insert #t(ord,total) values (3,10)
insert #t(ord,total) values (4,1)
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
order by ord
ord total running_total
----------- ----------- -------------
1 10 10
2 20 30
3 10 40
4 1 41
You asked for a benchmark this is the lowdown.
The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.
The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.
Bottom line, for production code I would go with the cursor.
Test data:
create table #t ( ord int primary key, total int, running_total int)
set nocount on
declare @i int
set @i = 0
begin tran
while @i < 10000
begin
insert #t (ord, total) values (@i, rand() * 100)
set @i = @i +1
end
commit
Test 1:
SELECT ord,total,
(SELECT SUM(total)
FROM #t b
WHERE b.ord <= a.ord) AS b
FROM #t a
-- CPU 11731, Reads 154934, Duration 11135
Test 2:
SELECT a.ord, a.total, SUM(b.total) AS RunningTotal
FROM #t a CROSS JOIN #t b
WHERE (b.ord <= a.ord)
GROUP BY a.ord,a.total
ORDER BY a.ord
-- CPU 16053, Reads 154935, Duration 4647
Test 3:
DECLARE @TotalTable table(ord int primary key, total int, running_total int)
DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord, total
FROM #t
ORDER BY ord
OPEN forward_cursor
DECLARE @running_total int,
@ord int,
@total int
SET @running_total = 0
FETCH NEXT FROM forward_cursor INTO @ord, @total
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @running_total = @running_total + @total
INSERT @TotalTable VALUES(@ord, @total, @running_total)
FETCH NEXT FROM forward_cursor INTO @ord, @total
END
CLOSE forward_cursor
DEALLOCATE forward_cursor
SELECT * FROM @TotalTable
-- CPU 359, Reads 30392, Duration 496
Test 4:
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
-- CPU 0, Reads 58, Duration 139
Though this is old, I think question is valid even today
My suspicion is that aud should refer to the resource server(s), and the client_id should refer to one of the client applications recognized by the authentication server
Yes, aud should refer to token consuming party. And client_id refers to token obtaining party.
In my current case, my resource server is also my web app client.
In the OP's scenario, web app and resource server both belongs to same party. So this means client and audience to be same. But there can be situations where this is not the case.
Think about a SPA which consume an OAuth protected resource. In this scenario SPA is the client. Protected resource is the audience of access token.
This second scenario is interesting. There is a working draft in place named "Resource Indicators for OAuth 2.0" which explain where you can define the intended audience in your authorisation request. So the resulting token will restricted to the specified audience. Also, Azure OIDC use a similar approach where it allows resource registration and allow auth request to contain resource parameter to define access token intended audience. Such mechanisms allow OAuth adpotations to have a separation between client and token consuming (audience) party.
You don not need to create a $(document).mousemove( function(e) {})
to handle mouse x,y. Get the event in the $.hover
function and from there it is possible to get x and y positions of the mouse. See the code below:
$('foo').hover(function(e){
var pos = [e.pageX-150,e.pageY];
$('foo1').dialog( "option", "position", pos );
$('foo1').dialog('open');
},function(){
$('foo1').dialog('close');
});
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub JohnDenverAnniesSong(): Const E4# = 329.6276: Dim Note&, Frequencies$, Durations$: Frequencies = "iiihfihfffhidadddfhihfffhihiiihfihffihfdadddfhihffhiki": Durations = "aabbbfjaabbbbnaabbbfjaabcapaabbbfjaabbbbnaabbbfjaabcap": For Note = 1 To Len(Frequencies): Beep CLng(E4 * 2 ^ ((AscW(Mid$(Frequencies, Note, 1)) - 96) / 12)), CLng((Asc(Mid$(Durations, Note, 1)) - 96) * 200 - 10): Sleep 10: DoEvents: Next: End Sub
Dump in Excel to run:D
Ingnoring the duplicated unique constraint isn't a solution?
INSERT IGNORE INTO tblSoftwareTitles...
I pasted the contents of your example into a file named so.txt
.
$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10
Explanation:
cat so.txt
will print the contents of the file to stdout
. awk '{ print $7 }'
will print the seventh column, i.e. the one containing id=n
cut -f2 -d"="
will cut the output of step #2 using =
as the delimiter and get the second column (-f2
)If you'd rather get id=
also, then:
$ cat so.txt | awk '{ print $7 }'
id=9
id=10
Vanilla Javascript:
this.querySelector(':checked').getAttribute('data-id')
Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.
The desired result can be achieved by wrapping the two tables within another table:
<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>
and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).
I conclude that there are some layouts that can only be achieved with tables.
use the val() method:
$(document).ready(function () {
var j = $("textarea");
if (j.val().length > 0) {
alert(j.val());
}
});
Perl has a readlink function (e.g. How do I copy symbolic links in Perl?). This works across most platforms, including OS X:
perl -e "print readlink '/path/to/link'"
For example:
$ mkdir -p a/b/c
$ ln -s a/b/c x
$ perl -e "print readlink 'x'"
a/b/c
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
Use this method and pass your array in parameter
Collections.shuffle(arrayList);
This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.
You can now use arraylist which is shuffled.
To make it work in Chrome (and bootply) i had to change code in this way:
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<input type="text" class="form-control" placeholder="year" />
<input type="text" class="form-control" placeholder="month" />
<input type="text" class="form-control" placeholder="day" />
</div>
</div>
</div>
</form>
The default way to detach from an interactive container is Ctrl+P Ctrl+Q, but you can override it when running a new container or attaching to existing container using the --detach-keys flag.
onclick event to call a function
<strike> <input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" /> </strike>
it will surely help you
it take a little more time than normal but wait it will work
String.equalsIgnoreCase
is the most practical choice for naive case-insensitive string comparison.
However, it is good to be aware that this method does neither do full case folding nor decomposition and so cannot perform caseless matching as specified in the Unicode standard. In fact, the JDK APIs do not provide access to information about case folding character data, so this job is best delegated to a tried and tested third-party library.
That library is ICU, and here is how one could implement a utility for case-insensitive string comparison:
import com.ibm.icu.text.Normalizer2;
// ...
public static boolean equalsIgnoreCase(CharSequence s, CharSequence t) {
Normalizer2 normalizer = Normalizer2.getNFKCCasefoldInstance();
return normalizer.normalize(s).equals(normalizer.normalize(t));
}
String brook = "?u\u0308ßchen";
String BROOK = "FLÜSSCHEN";
assert equalsIgnoreCase(brook, BROOK);
Naive comparison with String.equalsIgnoreCase
, or String.equals
on upper- or lowercased strings will fail even this simple test.
(Do note though that the predefined case folding flavour getNFKCCasefoldInstance
is locale-independent; for Turkish locales a little more work involving UCharacter.foldCase
may be necessary.)
We can Increasing the maximum limit using .htaccess
file.
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
If sometimes other way are not working, this way is working perfect.
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
Add nil to the end of the declaration.
// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil
// Init the view
override init(frame: CGRect)
super.init(frame: frame)
...
This worked for my case, but may not work for yours
ExecuteNonQuery
This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.
ExecuteScalar
It’s very fast to retrieve single values from database. Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. ExecuteReader
Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
This will work perfectly.
@Override
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
if(window == null) return;
WindowManager.LayoutParams params = window.getAttributes();
params.width = 400;
params.height = 400;
window.setAttributes(params);
}
The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
Based on what you have provided your CSS selector is not specific enough to override the CSS rules defined by Bootstrap.
Try this:
.table > tbody > tr > td {
vertical-align: middle;
}
In Boostrap 4, this can be achieved with the .align-middle
Vertical Alignment utility class.
<td class="align-middle">Text</td>
Simply use below code as follows.
List<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
Sorry for misunderstanding, from what I understood you want your DIV to have three different colors with different heights. This is the output of my code:
,
If this is what you want try this code:
div {_x000D_
height: 100px;_x000D_
width:400px;_x000D_
position: relative;_x000D_
}_x000D_
.c {_x000D_
background: blue; /* Old browsers */_x000D_
}_x000D_
_x000D_
.c:after{_x000D_
content: '';_x000D_
position: absolute;_x000D_
width:20%;_x000D_
left:0;_x000D_
height:110%;_x000D_
background: yellow;_x000D_
}_x000D_
.c:before{_x000D_
content: '';_x000D_
position: absolute;_x000D_
width:40%;_x000D_
left:60%;_x000D_
height:140%;_x000D_
background: green;_x000D_
}
_x000D_
<div class="c"></div>
_x000D_
Some time we need to set PATH variable for WINDOWS
%USERPROFILE%\AppData\Roaming\npm
After that test with where grunt
Note: Do not forget to close the command prompt window and reopen it.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
when we call ASCII as 7 bit code, the left most bit is used as sign bit so with 7 bits we can write up to 127. that means from -126 to 127 because Max imam value of ASCII is 0 to 255. this can be only satisfied with the argument of 7 bit if last bit is considered as sign bit
Vue.js considers this an anti-pattern. For example, declaring and setting some props like
this.propsVal = 'new Props Value'
So to solve this issue you have to take in a value from the props to the data or the computed property of a Vue instance, like this:
props: ['propsVal'],
data: function() {
return {
propVal: this.propsVal
};
},
methods: {
...
}
This will definitely work.
Google now has a documentation page dedicated to Maps URLs:
https://developers.google.com/maps/documentation/urls/guide
An API key is not required.
Manipulating one of the examples, I came up with this URL scheme that fits your question:
https://www.google.com/maps/search/<search term>/@<coordinates>,<zoom level>z
A valid example of this would be:
https://www.google.com/maps/search/pizza/@41.089988,-81.542901,12z
This should show you all of the pizza places around Akron, Ohio.
You're nesting mocking inside of mocking. You're calling getSomeList()
, which does some mocking, before you've finished the mocking for MyMainModel
. Mockito doesn't like it when you do this.
Replace
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}
with
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
List<SomeModel> someModelList = getSomeList();
Mockito.when(mainModel.getList()).thenReturn(someModelList);
}
To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.
Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when
method reads the last of these invocations off the list and records this invocation in the OngoingStubbing
object it returns.
The line
Mockito.when(mainModel.getList()).thenReturn(someModelList);
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,thenReturn
is called on the OngoingStubbing
object returned by the when
method.The thenReturn
method can then instruct the mock it received via the OngoingStubbing
method to handle any suitable call to the getList
method to return someModelList
.
In fact, as Mockito can't see your code, you can also write your mocking as follows:
mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);
This style is somewhat less clear to read, especially since in this case the null
has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.
However, the line
Mockito.when(mainModel.getList()).thenReturn(getSomeList());
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,mock
of SomeModel
is created (inside getSomeList()
),model.getName()
is called,At this point Mockito gets confused. It thought you were mocking mainModel.getList()
, but now you're telling it you want to mock the model.getName()
method. To Mockito, it looks like you're doing the following:
when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);
This looks silly to Mockito
as it can't be sure what you're doing with mainModel.getList()
.
Note that we did not get to the thenReturn
method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList()
method.
Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.
Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
Just in case someone has the same issue as me, I was missing "/" before one of the "/p" arguments. Not very clear from the description. I hope this helps someone.
To add to this there's: http://www.oracle.com/technetwork/developer-tools/adf-mobile/overview/index.html
A Java & HTML5 Based Framework for Developing
Oracle ADF Mobile enables developers to build and extend enterprise applications for iOS and Android from a single code base. Based on a hybrid mobile architecture, ADF Mobile supports access to native device services, enables offline applications and protects enterprise investments from future technology shifts.
I adjust your answer a bit (shixukai)
image: {
flex: 1,
width: 50,
height: 50,
resizeMode: 'contain' }
When I set to null, the image wont show at all. I set to certain size like 50
Its not very subtle, but there is a folder in the install location that carries the installed version name.
eg I've got:
C:\Program Files\Microsoft Visual Studio 9.0\Microsoft Visual Studio 2008 Standard Edition - ENU
and
C:\Program Files\Microsoft Visual Studio 10.0\Microsoft Visual Studio 2010 Professional - ENU
You could find the install location from the registry keys you listed above.
Alternatively this will be in the registry at a number of places, eg:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Setup\Microsoft Visual Studio 2008 Standard Edition - ENU
There are loads of values and keys with the string in, you can find them by looking for "Microsoft Visual Studio 2010" in the Regedit>Edit>Find function.
You'd just need to pick the one you want and do a little bit of string matching.
I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
protected boolean displaySensitiveInformation() {
return false;
}
You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.
Suppose this method is changed in the parent class to
protected boolean displaySensitiveInformation(Context context) {
return true;
}
This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.
To answer your question: you should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.
I have same issue, i used simple solution
1)create sliding_out_right.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
2) create sliding_in_left.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
3) simply using fragment transaction setCustomeAnimations() with two custom xml and two default xml for animation as follows :-
fragmentTransaction.setCustomAnimations(R.anim.sliding_in_left, R.anim.sliding_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right );
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
click File -> Invalidate Caches/ Restart doesn't help you anymore
Delete .iml , .idea files & folders from file explorer not inside android studio
1) Open android studio with different/another project
2) import project newly not from recent
3) build the project again
sure it will work
Throwing exceptions causes the stack to unwind, which has some performance impacts (admitted, modern managed environments have improved on that). Still repeatedly throwing and catching exceptions in a nested situation would be a bad idea.
Probably more important than that, exceptions are meant for exceptional conditions. They should not be used for ordinary control flow, because this will hurt your code's readability.
Be extremely careful using any of the other suggestions. It all depends on context.
I have spent a long time tracing a bugs in a system that presumed a==b
if |a-b|<epsilon
. The underlying problems were:
The implicit presumption in an algorithm that if a==b
and b==c
then a==c
.
Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is a==b
but 1000a!=1000b
. (This is why AlmostEqual2sComplement asks for the epsilon or max ULPS).
The use of the same epsilon for both the cosine of angles and the length of lines!
Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator == for doubles produced correct results.)
Like I said: it all depends on context and the expected size of a
and b
.
BTW, std::numeric_limits<double>::epsilon()
is the "machine epsilon". It is the difference between 1.0 and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)
Also, if you basically have int
arithmetic in doubles
(here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example 4.0/2.0 will be the same as 1.0+1.0. This is as long as you do not do things that result in fractions (4.0/3.0) or do not go outside of the size of an int.
You can try if(typeof object !== 'undefined')
basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:
Image playbutton;
try
{
playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
Image frame;
try
{
frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
using (frame)
{
using (var bitmap = new Bitmap(width, height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(frame,
new Rectangle(0,
0,
width,
height),
new Rectangle(0,
0,
frame.Width,
frame.Height),
GraphicsUnit.Pixel);
canvas.DrawImage(playbutton,
(bitmap.Width / 2) - (playbutton.Width / 2),
(bitmap.Height / 2) - (playbutton.Height / 2));
canvas.Save();
}
try
{
bitmap.Save(/*somekindofpath*/,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { }
}
}
The second one would be preferred:
However, having two different types of object in the same list has a bit of a bad design smell. We need more context to speak on that.
This article explains a technique of #include removing by using the parsing of Doxygen. That's just a perl script, so it's quite easy to use.
Also, there was just a typo in your original post.
'min:2|max5'
should have been 'min:2|max:5'
.
Notice the ":" for the "max" rule.
In Python the passing by reference or by value has to do with what are the actual objects you are passing.So,if you are passing a list for example,then you actually make this pass by reference,since the list is a mutable object.Thus,you are passing a pointer to the function and you can modify the object (list) in the function body.
When you are passing a string,this passing is done by value,so a new string object is being created and when the function terminates it is destroyed. So it all has to do with mutable and immutable objects.
Here they asked a similar question, and the answer seems more complete, I leave the source:
How to take partial screenshot with Selenium WebDriver in python?
from selenium import webdriver
from PIL import Image
from io import BytesIO
fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')
# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image
If Cas Bloem's answer does not apply (i.e. you've definitely got the web
middleware on the applicable route), you might want to check the order of middlewares in your HTTP Kernel.
The default order in Kernel.php
is this:
$middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
];
Note that VerifyCsrfToken
comes after StartSession
. If you've got these in a different order, the dependency between them can also lead to the Session store not set on request.
exception.
I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.
//
//
// CSV to object
//
//
const new_line_char = '\n';
const field_separator_char = ',';
function parse_csv(csv_str) {
var result = [];
let line_end_index_moved = false;
let line_start_index = 0;
let line_end_index = 0;
let csr_index = 0;
let cursor_val = csv_str[csr_index];
let found_new_line_char = get_new_line_char(csv_str);
let in_quote = false;
// Handle \r\n
if (found_new_line_char == '\r\n') {
csv_str = csv_str.split(found_new_line_char).join(new_line_char);
}
// Handle the last character is not \n
if (csv_str[csv_str.length - 1] !== new_line_char) {
csv_str += new_line_char;
}
while (csr_index < csv_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === new_line_char) {
if (in_quote === false) {
if (line_end_index_moved && (line_start_index <= line_end_index)) {
result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
line_start_index = csr_index + 1;
} // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
} // Else: just ignore because we are in a quote
}
csr_index++;
cursor_val = csv_str[csr_index];
line_end_index = csr_index;
line_end_index_moved = true;
}
// Handle \r\n
if (found_new_line_char == '\r\n') {
let new_result = [];
let curr_row;
for (var i = 0; i < result.length; i++) {
curr_row = [];
for (var j = 0; j < result[i].length; j++) {
curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
}
new_result.push(curr_row);
}
result = new_result;
}
return result;
}
function parse_csv_line(csv_line_str) {
var result = [];
//let field_end_index_moved = false;
let field_start_index = 0;
let field_end_index = 0;
let csr_index = 0;
let cursor_val = csv_line_str[csr_index];
let in_quote = false;
// Pretend that the last char is the separator_char to complete the loop
csv_line_str += field_separator_char;
while (csr_index < csv_line_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === field_separator_char) {
if (in_quote === false) {
if (field_start_index <= field_end_index) {
result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
field_start_index = csr_index + 1;
} // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
} // Else: just ignore because we are in quote
}
csr_index++;
cursor_val = csv_line_str[csr_index];
field_end_index = csr_index;
field_end_index_moved = true;
}
return result;
}
function parse_csv_field(csv_field_str) {
with_quote = (csv_field_str[0] === '"');
if (with_quote) {
csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
}
return csv_field_str;
}
// Initial method: check the first newline character only
function get_new_line_char(csv_str) {
if (csv_str.indexOf('\r\n') > -1) {
return '\r\n';
} else {
return '\n'
}
}
If you pushed the changes, you can undo
it and move the files back to stage without using another branch.
git show HEAD > patch
git revert HEAD
git apply patch
It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.
var Animal = function(options) {
var name = options.name;
var animal = {};
animal.getName = function() {
return name;
};
var somePrivateMethod = function() {
};
return animal;
};
// usage
var cat = Animal({name: 'tiger'});
Process of generating RPM from source file:
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important
directive! But sometimes it's the only way to override the inline style
attribute. So it's a best practice trying to avoid both.
Use is_same
:
#include <type_traits>
template <typename T>
void foo()
{
if (std::is_same<T, animal>::value) { /* ... */ } // optimizable...
}
Usually, that's a totally unworkable design, though, and you really want to specialize:
template <typename T> void foo() { /* generic implementation */ }
template <> void foo<animal>() { /* specific for T = animal */ }
Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
This works for me:
window.addEventListener("beforeunload", function(event) {_x000D_
event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_
With an indexed array, you can to something like this:
declare -a a=()
a+=('foo' 'bar')
A common error that is the cause of this is when you add
@Model SampleModel
at the top of the page instead of
@model SampleModel
I assume you have different sized images. I tested this myself, and it works as you describe (always centered, images widths appropriately)
/*CSS*/
div.c-wrapper{
width: 80%; /* for example */
margin: auto;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}
<!--html-->
<div class="c-wrapper">
<div id="carousel-example-generic" class="carousel slide">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="http://placehold.it/600x400">
<div class="carousel-caption">
hello
</div>
</div>
<div class="item">
<img src="http://placehold.it/500x400">
<div class="carousel-caption">
hello
</div>
</div>
<div class="item">
<img src="http://placehold.it/700x400">
<div class="carousel-caption">
hello
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="icon-next"></span>
</a>
</div>
</div>
This creates a "jump" due to variable heights... to solve that, try something like this: Select the tallest image of a list
Or use media-query to set your own fixed height.
I tried on ubuntu to move data from ELK 2.4.3 to ELK 5.1.1
Following are the steps
$ sudo apt-get update
$ sudo apt-get install -y python-software-properties python g++ make
$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update
$ sudo apt-get install npm
$ sudo apt-get install nodejs
$ npm install colors
$ npm install nomnom
$ npm install elasticdump
in home directory goto
$ cd node_modules/elasticdump/
execute the command
If you need basic http auth, you can use it like this:
--input=http://name:password@localhost:9200/my_index
Copy an index from production:
$ ./bin/elasticdump --input="http://Source:9200/Sourceindex" --output="http://username:password@Destination:9200/Destination_index" --type=data
Edit September 2016: Although it's nice to still get an occasional up-vote for this, because the world has moved on, I'd now go with the answer that uses transform (and which has a ton of upvotes). I wouldn't do it this way any more.
Another way not to have to calculate a margin or need a sub-container:
#menu {
position: fixed; /* Take it out of the flow of the document */
left: 0; /* Left edge at left for now */
right: 0; /* Right edge at right for now, so full width */
top: 30px; /* Move it down from top of window */
width: 500px; /* Give it the desired width */
margin: auto; /* Center it */
max-width: 100%; /* Make it fit window if under 500px */
z-index: 10000; /* Whatever needed to force to front (1 might do) */
}
In the year 2020 / 2021 it is even easier with Array.from
to 'convert' from a array-like nodes to an actual array, and then using .map
to loop through the resulting array.
The code is as simple as the follows:
Array.from(tableFields.children).map((child)=>console.log(child))
You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.
SHELL
is an environment variable, and so it's not the most reliable for what you're trying to figure out. If your tool is using a shell which doesn't set it, it will retain its old value.
Use ps
to figure out what's really going on.
Like this:
target:
$(shell cd ....); \
# ... commands execution in this directory
# ... no need to go back (using "cd -" or so)
# ... next target will be automatically in prev dir
Good luck!
Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId
, planCompareViewModel[1].PlanId
to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model)
use for
loop and render names with indexes.
If you use constraints (and so don't have the frame sizes) then you can add a border view with the required constraints
// MARK: - Add a border to one side of a view
public enum BorderSide {
case top, bottom, left, right
}
extension UIView {
public func addBorder(side: BorderSide, color: UIColor, width: CGFloat) {
let border = UIView()
border.translatesAutoresizingMaskIntoConstraints = false
border.backgroundColor = color
self.addSubview(border)
let topConstraint = topAnchor.constraint(equalTo: border.topAnchor)
let rightConstraint = trailingAnchor.constraint(equalTo: border.trailingAnchor)
let bottomConstraint = bottomAnchor.constraint(equalTo: border.bottomAnchor)
let leftConstraint = leadingAnchor.constraint(equalTo: border.leadingAnchor)
let heightConstraint = border.heightAnchor.constraint(equalToConstant: width)
let widthConstraint = border.widthAnchor.constraint(equalToConstant: width)
switch side {
case .top:
NSLayoutConstraint.activate([leftConstraint, topConstraint, rightConstraint, heightConstraint])
case .right:
NSLayoutConstraint.activate([topConstraint, rightConstraint, bottomConstraint, widthConstraint])
case .bottom:
NSLayoutConstraint.activate([rightConstraint, bottomConstraint, leftConstraint, heightConstraint])
case .left:
NSLayoutConstraint.activate([bottomConstraint, leftConstraint, topConstraint, widthConstraint])
}
}
}
Then set it something like the below
myButton.addBorder(side: .left, color: UIColor.lightGray, width: 1)
(inspired by this answer)
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
I struggled with this problem for a while myself. It turned out that cmake
was looking for Boost library files using Boost's naming convention, in which the library name is a function of the compiler version used to build it. Our Boost libraries were built using GCC 4.9.1
, and that compiler version was in fact present on our system; however, GCC 4.4.7
also happened to be installed. As it happens, cmake's FindBoost.cmake
script was auto-detecting the GCC 4.4.7
installation instead of the GCC 4.9.1
one, and thus was looking for Boost library files with "gcc44
" in the file names, rather than "gcc49
".
The simple fix was to force cmake to assume that GCC 4.9 was present, by setting Boost_COMPILER
to "-gcc49
" in CMakeLists.txt
. With this change, FindBoost.cmake
looked for, and found, my Boost library files.
In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.
When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.
As people have said before, an assignment is a modification of the reference, thus is lost:
public void Method1(object obj) {
obj = new Object();
}
public void Method2(object obj) {
obj = _privateObject;
}
The methods above does not modifies the original object.
A little modification of your example
using System;
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t = new TestRef();
t.Something = "Bar";
}
}
public class TestRef
{
private string s;
public string Something
{
get {return s;}
set { s = value; }
}
}
.catch(error => { throw error})
is a no-op. It results in unhandled rejection in route handler.
As explained in this answer, Express doesn't support promises, all rejections should be handled manually:
router.get("/emailfetch", authCheck, async (req, res, next) => {
try {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch (err) {
next(err);
}
})
So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.
HTML
<div class="shadow-block">
<div class="shadow"></div>
<div class="overlay">
<div class="overlay-inner">
content here
</div>
</div>
</div>
CSS
.overlay {
background: #f7f7f4;
height: 185px;
overflow: hidden;
position: relative;
width: 100%;
}
.overlay:before {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
content: " ";
display: block;
margin: 0 auto;
width: 80%;
}
.overlay:after {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
content: "-";
display: block;
margin: 0 auto;
position: absolute;
bottom: -65px;
left: -50%;
right: -50%;
width: 80%;
}
.shadow {
position: relative;
width:100%;
height:8px;
margin: 0 0 -22px 0;
-webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
border-radius: 50%;
}
<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
<telerik:RadNumericTextBox ID="txt" runat="server">
</telerik:RadNumericTextBox>
<asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>
protected void txt_TextChanged(object sender, EventArgs e)
{
//enter code here
}
The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).
You can set the resolution of the output image in the script.
The script and a Quick Action can be downloaded from github.
#!/usr/bin/python
# coding: utf-8
import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault)
resolution = 300.0 #dpi
scale = resolution/72.0
cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast
transparency = Quartz.kCGImageAlphaNoneSkipLast
#Save image to file
def writeImage (image, url, type, options):
destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
Quartz.CGImageDestinationAddImage(destination, image, options)
Quartz.CGImageDestinationFinalize(destination)
return
def getFilename(filepath):
i=0
newName = filepath
while os.path.exists(newName):
i += 1
newName = filepath + " %02d"%i
return newName
if __name__ == '__main__':
for filename in sys.argv[1:]:
pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
shortName = os.path.splitext(filename)[0]
prefix = os.path.splitext(os.path.basename(filename))[0]
folderName = getFilename(shortName)
try:
os.mkdir(folderName)
except:
print "Can't create directory '%s'"%(folderName)
sys.exit()
# For each page, create a file
for i in range (1, numPages+1):
page = Quartz.CGPDFDocumentGetPage(pdf, i)
if page:
#Get mediabox
mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
x = Quartz.CGRectGetWidth(mediaBox)
y = Quartz.CGRectGetHeight(mediaBox)
x *= scale
y *= scale
r = Quartz.CGRectMake(0,0,x, y)
# Create a Bitmap Context, draw a white background and add the PDF
writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
Quartz.CGContextSaveGState (writeContext)
Quartz.CGContextScaleCTM(writeContext, scale,scale)
Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
Quartz.CGContextFillRect(writeContext, r)
Quartz.CGContextDrawPDFPage(writeContext, page)
Quartz.CGContextRestoreGState(writeContext)
# Convert to an "Image"
image = Quartz.CGBitmapContextCreateImage(writeContext)
# Create unique filename per page
outFile = folderName +"/" + prefix + " %03d.png"%i
url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
# kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
type = kUTTypePNG
# See the full range of image properties on Apple's developer pages.
options = {
Quartz.kCGImagePropertyDPIHeight: resolution,
Quartz.kCGImagePropertyDPIWidth: resolution
}
writeImage (image, url, type, options)
del page
U+2304 DOWN ARROWHEAD, in HTML as ⌄
I know it's old question but in case anyone needs it. I use this in my application and it works well. i used it to check if the cart has been changed or not.
private boolean validateOrderProducts(Cart cart) {
boolean doesProductsChanged = false;
if (originalProductsList.size() == cart.getCartItemsList().size()) {
for (Product originalProduct : originalProductsList) {
if (!doesProductsChanged) {
for (Product cartProduct : cart.getCartProducts()) {
if (originalProduct.getId() == cartProduct.getId()) {
if (originalProduct.getPivot().getProductCount() != cartProduct.getCount()) {
doesProductsChanged = true;
// cart has been changed -> break from inner loop
break;
}
} else {
doesProductsChanged = false;
}
}
} else {
// cart is already changed -> break from first loop
break;
}
}
} else {
// some products has been added or removed (simplest case of Change)
return true;
}
return doesProductsChanged;
}
To be able to pass the select
, I just set it back to :
$('#selectID').prop('disabled',false);
or
$('#selectID').attr('disabled',false);
when passing the request.
The following should work.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Check if page is fully loaded or not
if (this.webBrowser1.ReadyState != WebBrowserReadyState.Complete)
return;
else
//Action to be taken on page loading completion
}
Mine says:
Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5
I found this solution works well and it inherits the origin font before sizing:
$.fn.textWidth = function(text){
var org = $(this)
var html = $('<span style="postion:absolute;width:auto;left:-9999px">' + (text || org.html()) + '</span>');
if (!text) {
html.css("font-family", org.css("font-family"));
html.css("font-size", org.css("font-size"));
}
$('body').append(html);
var width = html.width();
html.remove();
return width;
}
http_get_request_body()
was explicitly made for getting the body of PUT
and POST
requests as per the documentation http://php.net/manual/fa/function.http-get-request-body.php
Improved Lukas Knuth's version:
public class TweakedWebView extends WebView {
private ZoomButtonsController zoomButtons;
public TweakedWebView(Context context) {
super(context);
init();
}
public TweakedWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TweakedWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getSettings().setDisplayZoomControls(false);
} else {
try {
Method method = getClass()
.getMethod("getZoomButtonsController");
zoomButtons = (ZoomButtonsController) method.invoke(this);
} catch (Exception e) {
// pass
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean result = super.onTouchEvent(ev);
if (zoomButtons != null) {
zoomButtons.setVisible(false);
zoomButtons.getZoomControls().setVisibility(View.GONE);
}
return result;
}
}
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
// your code goes here
int pi_length=11; //Total length
char *str1;
const char *padding="0000000000000000000000000000000000000000";
const char *myString="Monkey";
int padLen = pi_length - strlen(myString); //length of padding to apply
if(padLen < 0) padLen = 0;
str1= (char *)malloc(100*sizeof(char));
sprintf(str1,"%*.*s%s", padLen, padLen, padding, myString);
printf("%s --> %d \n",str1,strlen(str1));
return 0;
}
You should add following to CardView
:
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
ArrayList
is newer and 20-30% faster.
If you don't need something explitly apparent in Vector
, use ArrayList
You should post your example document, because the code works fine:
>>> import BeautifulSoup
>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div id="articlebody"> ... </div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>
Finding <div>
s inside <div>
s works as well:
>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div><div id="articlebody"> ... </div></div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>
Or you can:
hadoop fs -rm -r PATH
Hint: if you enter:
hadoop fs -rmr PATH
you would mostly get:Please use 'rm -r' instead.
Try the code below. e.preventDefault() was added. This removes the default event action for the form.
$(document).ready(function () {
$("form").submit(function (e) {
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data, e);
},
cache: false
});
e.preventDefault();
});
});
Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?
Here is an example of some added validation
$(document).ready(function () {
$("form").submit(function (e) {
/* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
if(!$('#inputID').val()){
e.preventDefault(); // This will prevent the form submission
} else{
// In the event all validations pass. THEN process AJAX request.
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data, e);
},
cache: false
});
}
});
});
This has happened to me because the repository was disabled (a repository can be disabled by the owner or Github may disable all private repositories of an account if the account does not pay it's bill).
So you should contact the repository owner and inform him that the repository is disabled.
In MSVC there is a Microsoft specific keyword for that: __super
MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
Have you looked under Advanced Security Settings?
something like below image change permissions of folder to IIS_IUSRS
Simply, row_num = df.shape[0] # gives number of rows, here's the example:
import pandas as pd
import numpy as np
In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])
In [323]: df
Out[323]:
col_1 col_2
0 -0.894268 1.309041
1 -0.120667 -0.241292
2 0.076168 -1.071099
3 1.387217 0.622877
4 -0.488452 0.317882
In [324]: df.shape
Out[324]: (5, 2)
In [325]: df.shape[0] ## Gives no. of rows/records
Out[325]: 5
In [326]: df.shape[1] ## Gives no. of columns
Out[326]: 2
I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():
In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.
Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.
You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a CI server
<dependency>
<groupId>com.stackoverflow</groupId>
<artifactId>commons-utils</artifactId>
<version>1.3</version>
<scope>system</scope>
<systemPath>${basedir}/lib/commons-utils.jar</systemPath>
</dependency>
You're looking for implode()
$string = implode(",", $array);
Go to your projects "Properties" within visual studio. Then go to signing tab.
Then make sure Sign the Click Once manifests is turned off.
OR
1.Open the .csproj file in Notepad.
2.Delete the following information related to signing certificate in the certificate store xxxxx xxxxxx xxxxxxxx.pfx true false `
Worked for me.
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
You need to use the as.Date formats correctly.
Eg.
x = '2012/07/25'
xd = as.Date(x,'%Y/%m/%d')
xd # Prints "2012-07-25"
R date formats are similary to *nix ones.
Doing a typeof(xd) shows it as a double ie. days since 1970.
The underlying type of a variadic method function(Object... args)
is function(Object[] args)
. Sun added varargs in this manner to preserve backwards compatibility.
So you should just be able to prepend extraVar
to args
and call String.format(format, args)
.
As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:
import axios from 'axios';
...
class Login extends Component {
constructor(props, context) {
super(props, context);
this.onLogin = this.onLogin.bind(this);
...
}
async onLogin() {
const { email, password } = this.state;
try {
const response = await axios.post('/login', { email, password });
console.log(response);
} catch (err) {
...
}
}
...
}
The key distinction is repeating a captured group instead of capturing a repeated group.
As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.
In PCRE (PHP):
((?:\w+)+),?
Match 1, Group 1. 0-5 HELLO
Match 2, Group 1. 6-11 THERE
Match 3, Group 1. 12-20 BRUTALLY
Match 4, Group 1. 21-26 CRUEL
Match 5, Group 1. 27-32 WORLD
Since all captures are in Group 1, you only need $1
for substitution.
I used the following general form of this regular expression:
((?:{{RE}})+)
Example at regex101
All of the above answers are not match for Unicode characters in URL, for example: http://google.com?query=d?c+filan+dã+search
For the solution, this one should work:
(ftp:\/\/|www\.|https?:\/\/){1}[a-zA-Z0-9u00a1-\uffff0-]{2,}\.[a-zA-Z0-9u00a1-\uffff0-]{2,}(\S*)
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
var obj = {_x000D_
no: ["no", 32],_x000D_
nt: ["no", 32],_x000D_
nf: ["no", 32, 90]_x000D_
};_x000D_
_x000D_
count = -1; // which must be static value_x000D_
for (i in obj) {_x000D_
count++;_x000D_
if (obj.hasOwnProperty(i)) {_x000D_
console.log(obj[i][count])_x000D_
};_x000D_
};
_x000D_
in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array
perfect Method , if you interested, press like
I just use ramda, for resolve the same problem, i need to know what is changed in new object. So here my design.
const oldState = {id:'170',name:'Ivab',secondName:'Ivanov',weight:45};
const newState = {id:'170',name:'Ivanko',secondName:'Ivanov',age:29};
const keysObj1 = R.keys(newState)
const filterFunc = key => {
const value = R.eqProps(key,oldState,newState)
return {[key]:value}
}
const result = R.map(filterFunc, keysObj1)
result is, name of property and it's status.
[{"id":true}, {"name":false}, {"secondName":true}, {"age":false}]
This works for me. Hope it will work for you too.
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
I have edited the html page which you have provided. The updated page is as below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("Hello Test!!!!");
$('#ButtonRow').css("display", "block");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow" style="display: none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$("#<%=SearchCategory.ClientID%> input").change(function () {
alert("hi");
$("#ButtonRow").show();
});
</script>
You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:
# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful
On Ubuntu/Debian you can configure headers in the file
/etc/apache2/conf-enabled/security.conf
#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"
#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"
Note: This is the bottom part of the file. Only the last three entries are CSP settings.
The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.
Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.
While you're at it you could take a look at the other header settings and install mod_security
Further reading:
https://developers.google.com/web/fundamentals/security/csp/
An Error "indicates serious problems that a reasonable application should not try to catch."
while
An Exception "indicates conditions that a reasonable application might want to catch."
Error along with RuntimeException
& their subclasses are unchecked
exceptions. All other Exception classes are checked
exceptions.
Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException
, ParseException
, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller
On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException
, ClassCastException
, etc. Many applications will use try-catch
or throws
clause for RuntimeExceptions
& their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException
is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.
Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch
clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError
, StackOverflowError
, etc.
Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions
(also unchecked exceptions) in code. Checked exceptions should be handled by the code.
Latest SWIFT 3:
func detectScreenShot(action: @escaping () -> ()) {
let mainQueue = OperationQueue.main
NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in
// executes after screenshot
action()
}
}
In viewDidLoad, call this function
detectScreenShot { () -> () in
print("User took a screen shot")
}
However,
NotificationCenter.default.addObserver(self, selector: #selector(test), name: .UIApplicationUserDidTakeScreenshot, object: nil)
func test() {
//do stuff here
}
works totally fine. I don't see any points of mainQueue...
I know this is an old topic and there are certainly a lot of options, but I really prefer gibo
by Simon Whitaker. It's super simple to use, cross-platform (mac, *nix, and windows), and uses the github gitignore
repo so it is (basically) always up to date.
Make sure your local cache is up to date:
$ gibo --upgrade
From https://github.com/github/gitignore
* branch master -> FETCH_HEAD
Current branch master is up to date.
Search for the language/technology you need:
$ gibo --search android
Android
Display the .gitignore file:
$ gibo Android
### Android
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
Now, append it to your project's .gitignore file:
$ gibo Android >> .gitignore
(Make sure you use >>
to append to your project's .gitignore file; one >
will overwrite it - as I've done many times on accident!)
I know this isn't answering the OP's exact question, but using gibo makes it so you pretty much don't have to think about 'the question' anymore! .. it's nice! ;)
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Looking for this on 2018. Click event on option tag, inside a select tag, is not fired on Chrome.
Use change event, and capture the selected option:
$(document).delegate("select", "change", function() {
//capture the option
var $target = $("option:selected",$(this));
});
Be aware that $target may be a collection of objects if the select tag is multiple.
When [dropping] the encoding settings mentioned above all characters [are rendered] correctly but the encoding that is detected shows either windows-1252 or ISO-8859-1 depending on the browser.
Then that's what you're really sending. None of the encoding settings in your bullet list will actually modify your output in any way; all they do is tell the browser what encoding to assume when interpreting what you send. That's why you're getting those ?s - you're telling the browser that what you're sending is UTF-8, but it's really ISO-8859-1.
You actually can use an inet function. Observe.
main.c:
#include <arpa/inet.h>
main() {
uint32_t ip = 2110443574;
struct in_addr ip_addr;
ip_addr.s_addr = ip;
printf("The IP address is %s\n", inet_ntoa(ip_addr));
}
The results of gcc main.c -ansi; ./a.out
is
The IP address is 54.208.202.125
Note that a commenter said this does not work on Windows.
This should work:
/^((?!PART).)*$/
If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:
/^(?!PART)/
The (?!...)
syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/
." The site I've linked explains this far better than I can, but I'll try to break this down:
^ #Start matching from the beginning of the string.
(?!PART) #This position must not be followed by the string "PART".
. #Matches any character except line breaks (it will include those in single-line mode).
$ #Match all the way until the end of the string.
The ((?!xxx).)*
idiom is probably hardest to understand. As we saw, (?!PART)
looks at the string ahead and says that whatever comes next can't match the subpattern /PART/
. So what we're doing with ((?!xxx).)*
is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.
The ^
and $
anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.
Since we do have ^
and $
, if PART were anywhere in the string, one of the characters would match (?=PART).
and the overall match would fail. Hope that's clear enough to be helpful.
I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pf;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Administrator
*
* google-gson issue # 402: Memory Leak in web application; comment # 25
* https://code.google.com/p/google-gson/issues/detail?id=402
*/
public class ThreadLocalImmolater {
final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);
Boolean debug;
public ThreadLocalImmolater() {
debug = true;
}
public Integer immolate() {
int count = 0;
try {
final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocalsField.setAccessible(true);
for (final Thread thread : Thread.getAllStackTraces().keySet()) {
count += clear(threadLocalsField.get(thread));
count += clear(inheritableThreadLocalsField.get(thread));
}
logger.info("immolated " + count + " values in ThreadLocals");
} catch (Exception e) {
throw new Error("ThreadLocalImmolater.immolate()", e);
}
return count;
}
private int clear(final Object threadLocalMap) throws Exception {
if (threadLocalMap == null)
return 0;
int count = 0;
final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
tableField.setAccessible(true);
final Object table = tableField.get(threadLocalMap);
for (int i = 0, length = Array.getLength(table); i < length; ++i) {
final Object entry = Array.get(table, i);
if (entry != null) {
final Object threadLocal = ((WeakReference)entry).get();
if (threadLocal != null) {
log(i, threadLocal);
Array.set(table, i, null);
++count;
}
}
}
return count;
}
private void log(int i, final Object threadLocal) {
if (!debug) {
return;
}
if (threadLocal.getClass() != null &&
threadLocal.getClass().getEnclosingClass() != null &&
threadLocal.getClass().getEnclosingClass().getName() != null) {
logger.info("threadLocalMap(" + i + "): " +
threadLocal.getClass().getEnclosingClass().getName());
}
else if (threadLocal.getClass() != null &&
threadLocal.getClass().getName() != null) {
logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
}
else {
logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
}
}
}
Tried the answer given by Tough Coder in Windows 7 and it works!
Create a shortcut to cmd.exe in %HOMEDRIVE%%HOMEPATH%\Links
, open its file properties and change the field 'Start at' to %1
('Iniciar en' translated from spanish).
Now drag folders to it and you'll see the magic. It works too in all standard Open File dialogs. wow!
ps: those 'strange' tabs above in my picture are because I use Clover. I recommend it!
document.all
is very old, you don't have to use it anymore.
To quote Nicholas Zakas:
For instance, when the DOM was young, not all browsers supported getElementById(), and so there was a lot of code that looked like this:
if(document.getElementById){ //DOM
element = document.getElementById(id);
} else if (document.all) { //IE
element = document.all[id];
} else if (document.layers){ //Netscape < 6
element = document.layers[id];
}
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
simply use delete
, but be aware that you should read fully what the effects are of using this:
delete object.index; //true
object.index; //undefined
but if I was to use like so:
var x = 1; //1
delete x; //false
x; //1
but if you do wish to delete variables in the global namespace, you can use it's global object such as window
, or using this
in the outermost scope i.e
var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true
http://perfectionkills.com/understanding-delete/
another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice
which is a prototype of the array object.
Example Array:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
if I was to do:
delete myCars[1];
the resulting array would be:
["Saab", undefined, "BMW"]
but using splice like so:
myCars.splice(1,1);
would result in:
["Saab", "BMW"]
If you don't have the stdlib then you have to do it manually.
unsigned long hex2int(char *a, unsigned int len)
{
int i;
unsigned long val = 0;
for(i=0;i<len;i++)
if(a[i] <= 57)
val += (a[i]-48)*(1<<(4*(len-1-i)));
else
val += (a[i]-55)*(1<<(4*(len-1-i)));
return val;
}
Note: This code assumes uppercase A-F. It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters.
You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:
SELECT @NewIdOutputParam = SCOPE_IDENTITY()
Then in test1, retrieve it like so:
DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed
Simplest and best:
i = 0
while not there_is_reason_to_break(i):
# some code here
i += 1
It may be tempting to choose the closest analogy to the C code possible in Python:
from itertools import count
for i in count():
if thereIsAReasonToBreak(i):
break
But beware, modifying i
will not affect the flow of the loop as it would in C. Therefore, using a while
loop is actually a more appropriate choice for porting that C code to Python.
You can use like this.
when: condition1 == "condition1" or condition2 == "condition2"
Link to official docs: The When Statement.
Also Please refer to this gist: https://gist.github.com/marcusphi/6791404
Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"]
means that this will match each <input />
with type attribute type
equals to checkbox
After that: :checked
will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});
My fix worked copying zipalign.exe from sdk\build-tools\android-4.4W to sdk\platform-tools, as shown in video linked by digiboomz, and did not work copying it in sdk\tools
==
:In most programming languages, the comparison operator (==) checks, on the one hand, the data type and on the other hand the content of the variable for equality. The standard comparison operator (==) in PHP behaves differently. This tries to convert both variables into the same data type before the comparison and only then checks whether the content of these variables is the same. The following results are obtained:
<?php
var_dump( 1 == 1 ); // true
var_dump( 1 == '1' ); // true
var_dump( 1 == 2 ); // false
var_dump( 1 == '2' ); // false
var_dump( 1 == true ); // true
var_dump( 1 == false ); // false
?>
===
:This operator also checks the datatype of the variable and returns (bool)true only if both variables have the same content and the same datatype. The following would therefore be correct:
<?php
var_dump( 1 === 1 ); // true
var_dump( 1 === '1' ); // false
var_dump( 1 === 2 ); // false
var_dump( 1 === '2' ); // false
var_dump( 1 === true ); // false
var_dump( 1 === false ); // false
?>
Read more in What is the difference between == and === in PHP
To use IN, you must have a set, use this syntax instead:
SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)
If you don't want to use libraries or other things, you can use this native javascript approach:
var MD5 = function(d){var r = M(V(Y(X(d),8*d.length)));return r.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}_x000D_
_x000D_
/** NORMAL words**/_x000D_
var value = 'test';_x000D_
_x000D_
var result = MD5(value);_x000D_
_x000D_
document.body.innerHTML = 'hash - normal words: ' + result;_x000D_
_x000D_
/** NON ENGLISH words**/_x000D_
value = '????'_x000D_
_x000D_
//unescape() can be deprecated for the new browser versions_x000D_
result = MD5(unescape(encodeURIComponent(value)));_x000D_
_x000D_
document.body.innerHTML += '<br><br>hash - non english words: ' + result;_x000D_
_x000D_
For non english words you may need to use unescape() and the encodeURIComponent() methods.
In rails 5, we need to add 2 lines of code
skip_before_action :verify_authenticity_token
protect_from_forgery prepend: true, with: :exception
I would recommend using lastIndexOf() as opposed to indexOf()
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
If you want the column names of your dataframe, you can use the pyspark.sql
class. I'm not sure if the SDK supports explicitly indexing a DF by column name. I received this traceback:
>>> df.columns['High']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
However, calling the columns method on your dataframe, which you have done, will return a list of column names:
df.columns
will return ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
If you want the column datatypes, you can call the dtypes
method:
df.dtypes
will return [('Date', 'timestamp'), ('Open', 'double'), ('High', 'double'), ('Low', 'double'), ('Close', 'double'), ('Volume', 'int'), ('Adj Close', 'double')]
If you want a particular column, you'll need to access it by index:
df.columns[2]
will return 'High'
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
For JetBrains Rider:
First Option
Second option:
That's it!
For this simple use case, you can simply join the strings with comma. If you use Java 8:
String csv = String.join("\t", yourArray);
otherwise commons-lang has a join() method:
String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");
You should iterate over keys with:
for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
Same as the answer from 'Richie' but a bit more concise.
Query for user constraints only
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM user_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
Query for all constraints
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM all_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):
<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">
<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>
If you have those included, try posting your source so we can see what's going on.
Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.
import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;
//...
assertThat(result, is(new int[] {56, 100, 2000}));
Failure Trace output:
java.lang.AssertionError:
Expected: is [<56>, <100>, <2000>]
but: was [<55>, <100>, <2000>]
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0
In main layout xml you will have NavigationView
defined, in that use app:headerLayout
to set the header view.
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_drawer_header"
app:menu="@menu/navigation_drawer_menu" />
And the @layout/nav_drawer_header
will be the place holder of the image and texts.
nav_drawer_header.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="170dp"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/headerRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="@drawable/background" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/action_bar_size"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#40000000"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="16dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="35dp"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="@+id/navHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/navHeaderSubTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
And in your main class, you can take handle of Imageview
and TextView
as like normal other views.
TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");
TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");
Hope this helps.
I use Enthought Canopy for my python, at first I used "pip install --upgrade pip", it showed a syntax error like yours, then I added a "!" in front of the pip, then it finally worked.
Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC
option ensures that GCC produces such code.
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Well, the Qt FAQ says:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLocal8Bit();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
So perhaps you're having other problems. How exactly doesn't this work?
If you can use java streams, you can try the following:
Random randomizeTimestamp = new Random();
Long min = ZonedDateTime.parse("2018-01-01T00:00:00.000Z").toInstant().toEpochMilli();
Long max = ZonedDateTime.parse("2019-01-01T00:00:00.000Z").toInstant().toEpochMilli();
randomizeTimestamp.longs(generatedEventListSize, min, max).forEach(timestamp -> {
System.out.println(timestamp);
});
This will generate numbers in the given range for longs.
For Android, I previously used tPacketCapture but it didn't work well for an app streaming some video. I'm now using Shark. You need to be root to use it though.
It uses TCPDump (check the arguments you can pass) and creates a pcap file that can be read by Wireshark. The default arguments are usually good enough for me.
...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:
e.g.:
DIM YourName string
YourName = "Daniel O'Neal"
If InStr(YourName, "'") Then
SELECT * FROM tblStudents WHERE [name] Like """ Your Name """ ;
else
SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;
endif
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
"Resource temporarily unavailable"
is the error message corresponding to EAGAIN
, which means that the operation would have blocked but nonblocking operation was requested. For send()
, that could be due to any of:
fcntl()
; orMSG_DONTWAIT
flag to send()
; orSO_SNDTIMEO
socket option.My issue was also within the heredoc. I had it within an if/then statement and the closing bracket directly after the semicolon. So I moved the closing bracket to its own line and issue was fixed.
I changed:
... ;}
to:
... ;
}
When you call a function in PHP (such as array_push()
), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.
Using $arr[] = 'some value';
does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[]
.
I'm using a Mac OS Mojave
These 4 steps worked for me.
conda update conda
conda install python=3.6
conda install anaconda-client
conda update anaconda
@Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
function __exec($tmppath, $cmd)
{
$WshShell = new COM("WScript.Shell");
$tmpf = rand(1000, 9999).".tmp"; // Temp file
$tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file
$oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);
// return $oExec == 0 ? true : false; // Return True False after exec
return $tmpf;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file. Thanks again @Mark!
See this answer about the No overload for method 'ToString' takes 1 arguments
error.
You cannot format a nullable DateTime - you have to use the DateTime.Value property.
@Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty
Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.
How i solved this
This error occurs because you have set your build variants to release mode. set it to build mode and run project again.
If you want to run in release mode, just generate a signed apk the way we do it normally when releasing the app
If you want pull requests, there are the open source projects of RhodeCode and GitLab and the paid Stash
You can find some useful query here:
Investigating the Cause of SQL Server High CPU
For me this helped a lot:
SELECT s.session_id,
r.status,
r.blocking_session_id 'Blk by',
r.wait_type,
wait_resource,
r.wait_time / (1000 * 60) 'Wait M',
r.cpu_time,
r.logical_reads,
r.reads,
r.writes,
r.total_elapsed_time / (1000 * 60) 'Elaps M',
Substring(st.TEXT,(r.statement_start_offset / 2) + 1,
((CASE r.statement_end_offset
WHEN -1
THEN Datalength(st.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset) / 2) + 1) AS statement_text,
Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(st.objectid, st.dbid)) + N'.' +
Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text,
r.command,
s.login_name,
s.host_name,
s.program_name,
s.last_request_end_time,
s.login_time,
r.open_transaction_count
FROM sys.dm_exec_sessions AS s
JOIN sys.dm_exec_requests AS r
ON r.session_id = s.session_id
CROSS APPLY sys.Dm_exec_sql_text(r.sql_handle) AS st
WHERE r.session_id != @@SPID
ORDER BY r.cpu_time desc
In the fields of status, wait_type and cpu_time you can find the most cpu consuming task that is running right now.
You can try this:
char tab[7]={'a','b','t','u','a','y','t'};
printf("%d\n",sizeof(tab)/sizeof(tab[0]));
The Mono project is your best option. However, it has a lot of pitfalls (like incomplete API support in some areas), and it's legally gray (people like Richard Stallman have derided the use of Mono because of the possibility of Microsoft coming down on Mono by using its patent rights, but that's another story).
Anyway, Apache supports .NET/Mono through a module, but the last time I checked the version supplied with Debian, it gave Perl language support only; I can't say if it's changed since, perhaps someone else can correct me there.
Just another little improvement about @Duncan answer and the others answers based on clearfix element.
If you want to make the content clickable you will need a z-index
> 0 on it or clearfix will overlap the content and handle the click.
This is the example not working (you can't see the cursor pointer and clicking will do nothing):
<div class="row">
<div ng-repeat="product in products">
<div class="clearfix" ng-if="$index % 3 == 0"></div>
<div class="col-sm-4" style="cursor: pointer" ng-click="doSomething()">
<h2>{{product.title}}</h2>
</div>
</div>
</div>
While this is the fixed one:
<div class="row">
<div ng-repeat-start="product in products" class="clearfix" ng-if="$index % 3 == 0"></div>
<div ng-repeat-end class="col-sm-4" style="cursor: pointer; z-index: 1" ng-click="doSomething()">
<h2>{{product.title}}</h2>
</div>
</div>
I've added z-index: 1
to have the content raise over the clearfix and I've removed the container div using instead ng-repeat-start
and ng-repeat-end
(available from AngularJS 1.2) because it made z-index not working.
Hope this helps!
Plunker: http://plnkr.co/edit/4w5wZj
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start
being on (defaults to off)
If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):
/etc/php.d/my-new-file.ini :
session.auto_start = 1
(This is correct for CentOS 8, adjust for your OS/packaging)
You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.
I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.
And for completeness (primarily educational), it is possible without using the len()
function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.
def count(list):
item_count = 0
for item in list[:]:
item_count += 1
return item_count
count([1,2,3,4,5])
(The colon in list[:]
is implicit and is therefore also optional.)
The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.
Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:
class MyList(object):
def __init__(self):
self._data = []
self.length = 0 # length tracker that takes up memory but makes length op O(1) time
# the implicit iterator in a list class
def __iter__(self):
for elem in self._data:
yield elem
def add(self, elem):
self._data.append(elem)
self.length += 1
def remove(self, elem):
self._data.remove(elem)
self.length -= 1
mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2
The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x)
. Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".
Explanation:
String(x)
handles nulls, undefined, Symbols, [anything] and calls .toString()
for objects.
'' + x
calls .valueOf()
on x (casting to number), throws on Symbols, can provide implementation dependent results.
x.toString()
throws on nulls and undefined.
Note: String(x)
will still fail on prototype-less objects like Object.create(null)
.
If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:
/**
* Safely casts any value to string. Null and undefined are converted to ''.
* @param {*} value
* @return {string}
*/
function string (str) {
return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}
just change the codec to "DIVX"
. This codec works with all formats.
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
i hope this works for you!
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
or
function createOfferUrlArray($offer) {
foreach ( $offer as &$value ) {
$value = $value[4];
}
unset($value);
return $offer;
}
Using regex and find&replace, you can delete all the lines containing #region without leaving empty lines.
Because for some reason Ray's method didn't work on my machine I searched for (.*#region.*\n)|(\n.*#region.*)
and left the replace box empty.
That regex ensures that the if #region
is found on the first line, the ending newline is deleted, and if it is found on the last line the preceding newline is deleted.
Still, Ray's solution is the better one if it works for you.
SUMMARY:
I provide here a no-jQuery cross-browser desktop-and-mobile ability to consistently respond to range/slider interactions, something not possible in current browsers. It essentially forces all browsers to emulate IE11's on("change"...
event for either their on("change"...
or on("input"...
events. The new function is...
function onRangeChange(r,f) {
var n,c,m;
r.addEventListener("input",function(e){n=1;c=e.target.value;if(c!=m)f(e);m=c;});
r.addEventListener("change",function(e){if(!n)f(e);});
}
...where r
is your range input element and f
is your listener. The listener will be called after any interaction that changes the range/slider value but not after interactions that do not change that value, including initial mouse or touch interactions at the current slider position or upon moving off either end of the slider.
Problem:
As of early June 2016, different browsers differ in terms of how they respond to range/slider usage. Five scenarios are relevant:
The following table shows how at least three different desktop browsers differ in their behaviour with respect to which of the above scenarios they respond to:
Solution:
The onRangeChange
function provides a consistent and predictable cross-browser response to range/slider interactions. It forces all browsers to behave according to the following table:
In IE11, the code essentially allows everything to operate as per the status quo, i.e. it allows the "change"
event to function in its standard way and the "input"
event is irrelevant as it never fires anyway. In other browsers, the "change"
event is effectively silenced (to prevent extra and sometimes not-readily-apparent events from firing). In addition, the "input"
event fires its listener only when the range/slider's value changes. For some browsers (e.g. Firefox) this occurs because the listener is effectively silenced in scenarios 1, 4 and 5 from the above list.
(If you truly require a listener to be activated in either scenario 1, 4 and/or 5 you could try incorporating "mousedown"
/"touchstart"
, "mousemove"
/"touchmove"
and/or "mouseup"
/"touchend"
events. Such a solution is beyond the scope of this answer.)
Functionality in Mobile Browsers:
I have tested this code in desktop browsers but not in any mobile browsers. However, in another answer on this page MBourne has shown that my solution here "...appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari)". (Thanks MBourne.)
Usage:
To use this solution, include the onRangeChange
function from the summary above (simplified/minified) or the demo code snippet below (functionally identical but more self-explanatory) in your own code. Invoke it as follows:
onRangeChange(myRangeInputElmt, myListener);
where myRangeInputElmt
is your desired <input type="range">
DOM element and myListener
is the listener/handler function you want invoked upon "change"
-like events.
Your listener may be parameter-less if desired or may use the event
parameter, i.e. either of the following would work, depending on your needs:
var myListener = function() {...
or
var myListener = function(evt) {...
(Removing the event listener from the input
element (e.g. using removeEventListener
) is not addressed in this answer.)
Demo Description:
In the code snippet below, the function onRangeChange
provides the universal solution. The rest of the code is simply an example to demonstrate its use. Any variable that begins with my...
is irrelevant to the universal solution and is only present for the sake of the demo.
The demo shows the range/slider value as well as the number of times the standard "change"
, "input"
and custom "onRangeChange"
events have fired (rows A, B and C respectively). When running this snippet in different browsers, note the following as you interact with the range/slider:
Demo Code:
// main function for emulating IE11's "change" event:_x000D_
_x000D_
function onRangeChange(rangeInputElmt, listener) {_x000D_
_x000D_
var inputEvtHasNeverFired = true;_x000D_
_x000D_
var rangeValue = {current: undefined, mostRecent: undefined};_x000D_
_x000D_
rangeInputElmt.addEventListener("input", function(evt) {_x000D_
inputEvtHasNeverFired = false;_x000D_
rangeValue.current = evt.target.value;_x000D_
if (rangeValue.current !== rangeValue.mostRecent) {_x000D_
listener(evt);_x000D_
}_x000D_
rangeValue.mostRecent = rangeValue.current;_x000D_
});_x000D_
_x000D_
rangeInputElmt.addEventListener("change", function(evt) {_x000D_
if (inputEvtHasNeverFired) {_x000D_
listener(evt);_x000D_
}_x000D_
}); _x000D_
_x000D_
}_x000D_
_x000D_
// example usage:_x000D_
_x000D_
var myRangeInputElmt = document.querySelector("input" );_x000D_
var myRangeValPar = document.querySelector("#rangeValPar" );_x000D_
var myNumChgEvtsCell = document.querySelector("#numChgEvtsCell");_x000D_
var myNumInpEvtsCell = document.querySelector("#numInpEvtsCell");_x000D_
var myNumCusEvtsCell = document.querySelector("#numCusEvtsCell");_x000D_
_x000D_
var myNumEvts = {input: 0, change: 0, custom: 0};_x000D_
_x000D_
var myUpdate = function() {_x000D_
myNumChgEvtsCell.innerHTML = myNumEvts["change"];_x000D_
myNumInpEvtsCell.innerHTML = myNumEvts["input" ];_x000D_
myNumCusEvtsCell.innerHTML = myNumEvts["custom"];_x000D_
};_x000D_
_x000D_
["input", "change"].forEach(function(myEvtType) {_x000D_
myRangeInputElmt.addEventListener(myEvtType, function() {_x000D_
myNumEvts[myEvtType] += 1;_x000D_
myUpdate();_x000D_
});_x000D_
});_x000D_
_x000D_
var myListener = function(myEvt) {_x000D_
myNumEvts["custom"] += 1;_x000D_
myRangeValPar.innerHTML = "range value: " + myEvt.target.value;_x000D_
myUpdate();_x000D_
};_x000D_
_x000D_
onRangeChange(myRangeInputElmt, myListener);
_x000D_
table {_x000D_
border-collapse: collapse; _x000D_
}_x000D_
th, td {_x000D_
text-align: left;_x000D_
border: solid black 1px;_x000D_
padding: 5px 15px;_x000D_
}
_x000D_
<input type="range"/>_x000D_
<p id="rangeValPar">range value: 50</p>_x000D_
<table>_x000D_
<tr><th>row</th><th>event type </th><th>number of events </th><tr>_x000D_
<tr><td>A</td><td>standard "change" events </td><td id="numChgEvtsCell">0</td></tr>_x000D_
<tr><td>B</td><td>standard "input" events </td><td id="numInpEvtsCell">0</td></tr>_x000D_
<tr><td>C</td><td>new custom "onRangeChange" events</td><td id="numCusEvtsCell">0</td></tr>_x000D_
</table>
_x000D_
Credit:
While the implementation here is largely my own, it was inspired by MBourne's answer. That other answer suggested that the "input" and "change" events could be merged and that the resulting code would work in both desktop and mobile browsers. However, the code in that answer results in hidden "extra" events being fired, which in and of itself is problematic, and the events fired differ between browsers, a further problem. My implementation here solves those problems.
Keywords:
JavaScript input type range slider events change input browser compatability cross-browser desktop mobile no-jQuery
If you're using Bootstrap 3, this works quite well
<a href="#" class="btn btn-primary btn-lg active" role="button">Primary link</a>
<a href="#" class="btn btn-default btn-lg active" role="button">Link</a>
One-liner with Python 3.8 and above:
while res:= input("When correct, press enter to continue...").lower() not in {'y','yes','Y','YES',''}: pass
I solved this problem with a custom Angular filter as well, but mine takes advantage of regex capturing groups and so the code is really short. I pair it with a separate stripNonNumeric
filter to sanitize the input:
app.filter('stripNonNumeric', function() {
return function(input) {
return (input == null) ? null : input.toString().replace(/\D/g, '');
}
});
The phoneFormat
filter properly formats a phone number with or without the area code. (I did not need international number support.)
app.filter('phoneFormat', function() {
//this establishes 3 capture groups: the first has 3 digits, the second has 3 digits, the third has 4 digits. Strings which are not 7 or 10 digits numeric will fail.
var phoneFormat = /^(\d{3})?(\d{3})(\d{4})$/;
return function(input) {
var parsed = phoneFormat.exec(input);
//if input isn't either 7 or 10 characters numeric, just return input
return (!parsed) ? input : ((parsed[1]) ? '(' + parsed[1] + ') ' : '') + parsed[2] + '-' + parsed[3];
}
});
Use them simply:
<p>{{customer.phone | stripNonNumeric | phoneFormat}}</p>
The regex for the stripNonNumeric
filter came from here.
This happened to me when I branched code. To fix it I right-clicked my project in Visual Studio, chose manage Nu-get packages, uninstalled EntityFramework, then re-installed it. Problem solved
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.