The problem is with, you
def __init__(self, data):
when you create object from DHT class you should pass parameter the data should be dict type, like
data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)
But in your code youshould to change is
data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()
Or
if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()
Dec 10th 2019, Xcode Version 11.2.1, MacOS X 10.15.1
I was facing exactly same issue yesterday and I thought it might be network issues, at least it looks like so. But this morning I had tried couple different networks and several VPN connections, none of them is working!
The highest voted answer here asks me to reset a cache folder named .itmstransporter under my home dir, the run a program iTMSTransporter under a specific folder, but I can't find both of them.
But soon I figured that it is the cache folder for the people who uses the legacy uploader program: Application Loader, which is deprecated by Apple and can be no longer found in Xcode 11. Then I found that the latest Xcode has located iTMSTransporter here:
/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/itms/bin/iTMSTransporter
And its cache folder is here:
/Users/your_user_name/Library/Caches/com.apple.amp.itmstransporter/
I removed my existed cache folder, and run iTMSTransporter without any parameter, it soon started to output logs and download a bunch of files, and finished in 2 or 3 minutes. Then I tried again to upload my ipa file, it works!!!
CONCLUTION:
If you add static imports for Stream.concat and Stream.of, the first example could be written as follows:
Stream<Foo> stream = concat(stream1, concat(stream2, of(element)));
Importing static methods with generic names can result in code that becomes difficult to read and maintain (namespace pollution). So, it might be better to create your own static methods with more meaningful names. However, for demonstration I will stick with this name.
public static <T> Stream<T> concat(Stream<? extends T> lhs, Stream<? extends T> rhs) {
return Stream.concat(lhs, rhs);
}
public static <T> Stream<T> concat(Stream<? extends T> lhs, T rhs) {
return Stream.concat(lhs, Stream.of(rhs));
}
With these two static methods (optionally in combination with static imports), the two examples could be written as follows:
Stream<Foo> stream = concat(stream1, concat(stream2, element));
Stream<Foo> stream = concat(
concat(stream1.filter(x -> x!=0), stream2).filter(x -> x!=1),
element)
.filter(x -> x!=2);
The code is now significantly shorter. However, I agree that the readability hasn't improved. So I have another solution.
In a lot of situations, Collectors can be used to extend the functionality of streams. With the two Collectors at the bottom, the two examples could be written as follows:
Stream<Foo> stream = stream1.collect(concat(stream2)).collect(concat(element));
Stream<Foo> stream = stream1
.filter(x -> x!=0)
.collect(concat(stream2))
.filter(x -> x!=1)
.collect(concat(element))
.filter(x -> x!=2);
The only difference between your desired syntax and the syntax above is, that you have to replace concat(...) with collect(concat(...)). The two static methods can be implemented as follows (optionally used in combination with static imports):
private static <T,A,R,S> Collector<T,?,S> combine(Collector<T,A,R> collector, Function<? super R, ? extends S> function) {
return Collector.of(
collector.supplier(),
collector.accumulator(),
collector.combiner(),
collector.finisher().andThen(function));
}
public static <T> Collector<T,?,Stream<T>> concat(Stream<? extends T> other) {
return combine(Collectors.toList(),
list -> Stream.concat(list.stream(), other));
}
public static <T> Collector<T,?,Stream<T>> concat(T element) {
return concat(Stream.of(element));
}
Of course there is a drawback with this solution that should be mentioned. collect is a final operation that consumes all elements of the stream. On top of that, the collector concat creates an intermediate ArrayList each time it is used in the chain. Both operations can have a significant impact on the behaviour of your program. However, if readability is more important than performance, it might still be a very helpful approach.
What you need is a split user-defined function. With that, the solution looks like
With SplitValues As
(
Select T.Name, Z.Position, Z.Value
, Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
From Table As T
Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
)
Select Name
, FirstName.Value
, Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
Left Join SplitValues As SecondName
On S2.Name = S1.Name
And S2.Num = 2
Left Join SplitValues As ThirdName
On S2.Name = S1.Name
And S2.Num = 3
Where FirstName.Num = 1
Here's a sample split function:
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
MyISAM has been just mentioned. Simply try adding ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; at the end of a statement, assuming that your other tables were created with MyISAM.
CREATE TABLE IF NOT EXISTS `tablename` (
`key` bigint(20) NOT NULL AUTO_INCREMENT,
FOREIGN KEY `key` (`key`) REFERENCES `othertable`(`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I was able to handle that by simply overriding the method 'unsuccessfulAuthentication' in my filter. There, I send an error response to the client with the desired HTTP status code.
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
if (failed.getCause() instanceof RecordNotFoundException) {
response.sendError((HttpServletResponse.SC_NOT_FOUND), failed.getMessage());
}
}
I don't recommend changing apaches port itself, because it will need you remember changed port. Its also headache to tell your co-developers about port change.
Go to windows features(By searching turn on or off windows features) -> Find Internet information services(IIS) and uncheck if it checked. Please make a note when you disable it FTP server/ client will not work.(incase you are using it, change httpd.conf as giovannipds 's answer) -> If still port is not free, then change skype port through skype settings.
Edit (2017-10-12):
@MechaLynx and @Kevin-Weber note that unescape()
is deprecated from non-browser environments and does not exist in TypeScript. decodeURIComponent
is a drop-in replacement. For broader compatibility, use the below instead:
decodeURIComponent(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'
Original answer:
unescape(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'
You can offload all the work to JSON.parse
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
not sure if you solved your question, but I found this worked to increment the row number upon dragging.
= INDIRECT("'"&$A$5&"'!$G"&7+B1)
Where B1 refers to an index number, starting at 0.
So if you copy-drag both the index cell and the cell with the indirect formula, you'll increment the indirect. You could probably create a more elegant counter with the Index function too.
Hope this helps.
Use Column.DefaultCellStyle.Format property or set it in designer
The example below seemed to work. Just setting a height on the first element
<ul class="row">
<li class="span4" style="height: 100px"><h1>1</h1></li>
<li class="span4"><h1>2</h1></li>
<li class="span4"><h1>3</h1></li>
<li class="span4"><h1>4</h1></li>
<li class="span4"><h1>5</h1></li>
<li class="span4"><h1>6</h1></li>
<li class="span4"><h1>7</h1></li>
<li class="span4"><h1>8</h1></li>
</ul>
I can't help but thinking it's the wrong use of a row though.
Radio inputs must be inside of a form for 'checked' to work.
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.
Show Notificaton in android 8.0
@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void show_Notification(){
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
String CHANNEL_ID="MYCHANNEL";
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentText("Heading")
.setContentTitle("subheading")
.setContentIntent(pendingIntent)
.addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(android.R.drawable.sym_action_chat)
.build();
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(1,notification);
}
Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.
private class ExampleAdapter extends ArrayAdapter<String>{
public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(0);
return view;
}
/* The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it. */
var jq = $.noConflict();
(function($){
$('document').ready(function(){
$('button').click(function(){
alert($('.para').text());
})
})
})(jq);
Live view example on codepen that is easy to understand: http://codepen.io/kaushik/pen/QGjeJQ
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
Also a good script, although my laptop ran out of memory, but this was on a very large table
https://basitaalishan.com/2014/02/23/rebuild-all-indexes-on-all-tables-in-the-sql-server-database/
USE [<mydatabasename>]
Go
--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments Data Type Description
-------------- ------------ ------------
--@FillFactor [int] Specifies a percentage that indicates how full the Database Engine should make the leaf level
-- of each index page during index creation or alteration. The valid inputs for this parameter
-- must be an integer value from 1 to 100 The default is 0.
-- For more information, see http://technet.microsoft.com/en-us/library/ms177459.aspx.
--@PadIndex [varchar](3) Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
-- because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
-- for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
-- overrides the percentage to allow for the minimum. The number of rows on an intermediate
-- index page is never less than two, regardless of how low the value of fillfactor. The valid
-- inputs for this parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188783.aspx.
--@SortInTempDB [varchar](3) Specifies whether to store temporary sort results in tempdb. The valid inputs for this
-- parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188281.aspx.
--@OnlineRebuild [varchar](3) Specifies whether underlying tables and associated indexes are available for queries and data
-- modification during the index operation. The valid inputs for this parameter are ON or OFF.
-- The default is OFF.
-- Note: Online index operations are only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information, see http://technet.microsoft.com/en-us/library/ms191261.aspx.
--@DataCompression [varchar](4) Specifies the data compression option for the specified index, partition number, or range of
-- partitions. The options for this parameter are as follows:
-- > NONE - Index or specified partitions are not compressed.
-- > ROW - Index or specified partitions are compressed by using row compression.
-- > PAGE - Index or specified partitions are compressed by using page compression.
-- The default is NONE.
-- Note: Data compression feature is only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information about compression, see http://technet.microsoft.com/en-us/library/cc280449.aspx.
--@MaxDOP [int] Overrides the max degree of parallelism configuration option for the duration of the index
-- operation. The valid input for this parameter can be between 0 and 64, but should not exceed
-- number of processors available to SQL Server.
-- For more information, see http://technet.microsoft.com/en-us/library/ms189094.aspx.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
-- Ensure a USE <databasename> statement has been executed first.
SET NOCOUNT ON;
DECLARE @Version [numeric] (18, 10)
,@SQLStatementID [int]
,@CurrentTSQLToExecute [nvarchar](max)
,@FillFactor [int] = 100 -- Change if needed
,@PadIndex [varchar](3) = N'OFF' -- Change if needed
,@SortInTempDB [varchar](3) = N'OFF' -- Change if needed
,@OnlineRebuild [varchar](3) = N'OFF' -- Change if needed
,@LOBCompaction [varchar](3) = N'ON' -- Change if needed
,@DataCompression [varchar](4) = N'NONE' -- Change if needed
,@MaxDOP [int] = NULL -- Change if needed
,@IncludeDataCompressionArgument [char](1);
IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
DROP TABLE #Work_To_Do
CREATE TABLE #Work_To_Do
(
[sql_id] [int] IDENTITY(1, 1)
PRIMARY KEY ,
[tsql_text] [varchar](1024) ,
[completed] [bit]
)
SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))
IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
AND (
@Version >= 10.0
AND SERVERPROPERTY(N'EngineEdition') = 3
)
BEGIN
SET @IncludeDataCompressionArgument = N'Y'
END
IF @IncludeDataCompressionArgument IS NULL
BEGIN
SET @IncludeDataCompressionArgument = N'N'
END
INSERT INTO #Work_To_Do ([tsql_text], [completed])
SELECT 'ALTER INDEX [' + i.[name] + '] ON' + SPACE(1) + QUOTENAME(t2.[TABLE_CATALOG]) + '.' + QUOTENAME(t2.[TABLE_SCHEMA]) + '.' + QUOTENAME(t2.[TABLE_NAME]) + SPACE(1) + 'REBUILD WITH (' + SPACE(1) + + CASE
WHEN @PadIndex IS NULL
THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
WHEN 1
THEN 'ON'
WHEN 0
THEN 'OFF'
END
ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
END + CASE
WHEN @FillFactor IS NULL
THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
END + CASE
WHEN @SortInTempDB IS NULL
THEN ''
ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
END + CASE
WHEN @OnlineRebuild IS NULL
THEN ''
ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + CASE
WHEN @IncludeDataCompressionArgument = N'Y'
THEN CASE
WHEN @DataCompression IS NULL
THEN ''
ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
END
ELSE ''
END + CASE
WHEN @MaxDop IS NULL
THEN ''
ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
END + SPACE(1) + ')'
,0
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
AND i.[index_id] > 0
AND i.[type] IN (1, 2)
INNER JOIN [INFORMATION_SCHEMA].[TABLES] t2 ON t1.[name] = t2.[TABLE_NAME]
AND t2.[TABLE_TYPE] = 'BASE TABLE'
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
AND st.[name] = i.[name]
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
WHILE @SQLStatementID IS NOT NULL
BEGIN
SELECT @CurrentTSQLToExecute = [tsql_text]
FROM #Work_To_Do
WHERE [sql_id] = @SQLStatementID
PRINT @CurrentTSQLToExecute
EXEC [sys].[sp_executesql] @CurrentTSQLToExecute
UPDATE #Work_To_Do
SET [completed] = 1
WHERE [sql_id] = @SQLStatementID
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
END
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
TL;DR: Not caring about old browsers? Use form.reportValidity()
.
Need legacy browser support? Read on.
It actually is possible to trigger validation manually.
I'll use plain JavaScript in my answer to improve reusability, no jQuery is needed.
Assume the following HTML form:
<form>
<input required>
<button type="button">Trigger validation</button>
</form>
And let's grab our UI elements in JavaScript:
var form = document.querySelector('form')
var triggerButton = document.querySelector('button')
Don't need support for legacy browsers like Internet Explorer? This is for you.
All modern browsers support the reportValidity()
method on form
elements.
triggerButton.onclick = function () {
form.reportValidity()
}
That's it, we're done. Also, here's a simple CodePen using this approach.
Approach for older browsers
Below is a detailed explanation how
reportValidity()
can be emulated in older browsers.However, you don't need to copy&paste those code blocks into your project yourself — there is a ponyfill/polyfill readily available for you.
Where reportValidity()
is not supported, we need to trick the browser a little bit. So, what will we do?
form.checkValidity()
. This will tell us if the form is valid, but not show the validation UI.In code:
triggerButton.onclick = function () {
// Form is invalid!
if (!form.checkValidity()) {
// Create the temporary button, click and remove it
var tmpSubmit = document.createElement('button')
form.appendChild(tmpSubmit)
tmpSubmit.click()
form.removeChild(tmpSubmit)
} else {
// Form is valid, let the user proceed or do whatever we need to
}
}
This code will work in pretty much any common browser (I've tested it successfully down to IE11).
Just:
$('#edit-submitted-first-name').removeAttr('required');?????
If you're interested in further reading take a look here.
Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.
Example:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
newMethod();
super.save();
}
public void newMethod(){
//some codes
}
}
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
Modern C, aka C99, has variable length arrays, VLA. Unfortunately, not all compilers support this but if yours does this would be an alternative.
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).
mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.
wcs stand for Wide Char String and is an array of wchar_t.
For more background details on wide chars have a look at glibc documentation here.
How I redirect to an area is add it as a parameter
@Html.Action("Action", "Controller", new { area = "AreaName" })
for the href portion of a link I use
@Url.Action("Action", "Controller", new { area = "AreaName" })
As a side note, Gecko and WebKit support the the
text-rendering
property as well.
To run a non-executable sh
script, use:
sh myscript
To run a non-executable bash
script, use:
bash myscript
To start an executable (which is any file with executable permission); you just specify it by its path:
/foo/bar
/bin/bar
./bar
To make a script executable, give it the necessary permission:
chmod +x bar
./bar
When a file is executable, the kernel is responsible for figuring out how to execte it. For non-binaries, this is done by looking at the first line of the file. It should contain a hashbang
:
#! /usr/bin/env bash
The hashbang tells the kernel what program to run (in this case the command /usr/bin/env
is ran with the argument bash
). Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.
That means every script that is executable should have a hashbang. If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash
, perl
, python
, sh
, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh
and bash
).
/usr/bin/env
Most commonly, you'll see hash bangs like so:
#!/bin/bash
The result is that the kernel will run the program /bin/bash
to interpret the script. Unfortunately, bash
is not always shipped by default, and it is not always available in /bin
. While on Linux machines it usually is, there are a range of other POSIX machines where bash
ships in various locations, such as /usr/xpg/bin/bash
or /usr/local/bin/bash
.
To write a portable bash script, we can therefore not rely on hard-coding the location of the bash
program. POSIX already has a mechanism for dealing with that: PATH
. The idea is that you install your programs in one of the directories that are in PATH
and the system should be able to find your program when you want to run it by name.
Sadly, you cannot just do this:
#!bash
The kernel won't (some might) do a PATH
search for you. There is a program that can do a PATH
search for you, though, it's called env
. Luckily, nearly all systems have an env
program installed in /usr/bin
. So we start env
using a hardcoded path, which then does a PATH
search for bash
and runs it so that it can interpret your script:
#!/usr/bin/env bash
This approach has one downside: According to POSIX, the hashbang can have one argument. In this case, we use bash
as the argument to the env
program. That means we have no space left to pass arguments to bash
. So there's no way to convert something like #!/bin/bash -exu
to this scheme. You'll have to put set -exu
after the hashbang instead.
This approach also has another advantage: Some systems may ship with a /bin/bash
, but the user may not like it, may find it's buggy or outdated, and may have installed his own bash
somewhere else. This is often the case on OS X (Macs) where Apple ships an outdated /bin/bash
and users install an up-to-date /usr/local/bin/bash
using something like Homebrew. When you use the env
approach which does a PATH
search, you take the user's preference into account and use his preferred bash over the one his system shipped with.
In my case, the issue was of unsupported java version
Check the file /etc/init.d/jenkins
to find out which java versions are supported.
To find which java versions are supported, run
grep -m 1 "JAVA_ALLOWED_VERSIONS" /etc/init.d/jenkins
The output will be like this(your's might be different)
JAVA_ALLOWED_VERSIONS=( "1.8" "11" )
In my case version 1.8 and 11 are supported. I will be going with version 11.
Install the supported version of jre using command
For ubuntu/debian
sudo apt install openjdk-11-jre
For centOS use
sudo yum install java-11-openjdk-devel
Find the path to newly installed jre
For ubuntu/debian path is
/usr/lib/jvm/java-11-openjdk-amd64/bin/java
You can find the path on centOS under /usr/lib/jvm/
Modify the file /etc/init.d/jenkins
At line number 28, replace the JAVA=`type -p java`
with JAVA='/usr/lib/jvm/java-11-openjdk-amd64/bin/java'
Now run command to reload the systemctl daemon
sudo systemctl daemon-reload
Start the jenkins service
sudo systemctl start jenkins
As mentioned Pascal MARTIN, you should replace the '\' with DIRECTORY_SEPARATOR for example:
$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
include($filename);
Also I would suggest you to reorganize the dirrectory structure, to make the code more readable. This could be an alternative:
Directory structure:
ProjectRoot
|- lib
File: /ProjectRoot/lib/Person/Barnes/David/Class1.php
<?php
namespace Person\Barnes\David
class Class1
{
public function __construct()
{
echo __CLASS__;
}
}
?>
File: /ProjectRoot/test.php
define('BASE_PATH', realpath(dirname(__FILE__)));
function my_autoloader($class)
{
$filename = BASE_PATH . '/lib/' . str_replace('\\', '/', $class) . '.php';
include($filename);
}
spl_autoload_register('my_autoloader');
use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
UPDATE FOR NEW VERSION
Glide.with(context.applicationContext)
.load(url)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
listener?.onLoadFailed(e)
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
listener?.onLoadSuccess(resource)
return false
}
})
.into(this)
OLD ANSWER
@outlyer's answer is correct, but there're some changes in new Glide version
My version: 4.7.1
Code:
Glide.with(context.applicationContext)
.asBitmap()
.load(iconUrl)
.into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
callback.onReady(createMarkerIcon(resource, iconId))
}
})
Note: this code run in UI Thread, thus you can use AsyncTask, Executor or somethings else for concurrency (like @outlyer's code) If you want to get original size, put Target.SIZE_ORIGINA as my code. Don't use -1, -1
here, 2 in binary(8 bit) is 00000010 and its 1's complement is 11111101, subtract 1 from that 1's complement we get 11111101-1 = 11111100, here the sign is - as 8th character (from R to L) is 1 find 1's complement of that no. i.e. 00000011 = 3 and the sign is negative that's why we get -3 here.
An object is only once in memory. Your first addition to list
just adds the object references.
anotherList.addAll
will also just add the references. So still only 100 objects in memory.
If you change list
by adding/removing elements, anotherList
won't be changed. But if you change any object in list
, then it's content will be also changed, when accessing it from anotherList
, because the same reference is being pointed to from both lists.
SELECT name, city, count(*) as qty
FROM stuff
GROUP BY name, city HAVING count(*)> 1
SELECT * FROM USER_CONSTRAINTS
Similar to this answer, though I used a temporary table instead:
CREATE TEMPORARY TABLE duplicates (
SELECT payer_email
FROM paypal_ipn_orders
GROUP BY payer_email
HAVING COUNT(id) > 1
);
SELECT id, payer_email
FROM paypal_ipn_orders AS p
INNER JOIN duplicates AS d ON d.payer_email=p.payer_email;
For better understand how it works!
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
if(n == 0)
{
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
}
else if(n == 1)
{
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
}
else if (n == 2)
{
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
}
else if (n == -1)
{
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
}
OR
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
switch (n) {
case 0:
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
break;
case 1:
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
break;
case 2:
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
break;
case -1:
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
break;
default:
break;
}
In the terminal, I typed:
/usr/local/mysql/bin/mysql -u root -p
I was then prompted to enter the temporary password that was given to me upon completion of the installation.
You can write a for loop for this... %)
for x in *
do
if [ "$x" != "exclude_criteria" ]
then
rm -f $x;
fi
done;
The following helped me as I didn't have DBA access and also wanted the column names.
See: https://dataedo.com/kb/query/oracle/list-table-indexes
select ind.table_owner || '.' || ind.table_name as "TABLE",
ind.index_name,
LISTAGG(ind_col.column_name, ',')
WITHIN GROUP(order by ind_col.column_position) as columns,
ind.index_type,
ind.uniqueness
from sys.all_indexes ind
join sys.all_ind_columns ind_col
on ind.owner = ind_col.index_owner
and ind.index_name = ind_col.index_name
where ind.table_owner not in ('ANONYMOUS','CTXSYS','DBSNMP','EXFSYS',
'MDSYS', 'MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS', 'ORDSYS',
'SI_INFORMTN_SCHEMA','SYS','SYSMAN','SYSTEM', 'TSMSYS','WK_TEST',
'WKPROXY','WMSYS','XDB','APEX_040000','APEX_040200',
'DIP', 'FLOWS_30000','FLOWS_FILES','MDDATA', 'ORACLE_OCM', 'XS$NULL',
'SPATIAL_CSW_ADMIN_USR', 'SPATIAL_WFS_ADMIN_USR', 'PUBLIC',
'LBACSYS', 'OUTLN', 'WKSYS', 'APEX_PUBLIC_USER')
-- AND ind.table_name='TableNameGoesHereIfYouWantASpecificTable'
group by ind.table_owner,
ind.table_name,
ind.index_name,
ind.index_type,
ind.uniqueness
order by ind.table_owner,
ind.table_name;
The easiest option to get this working is to include Username and Password under of request. See sample below.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:typ="http://xml.demo.com/types" xmlns:ser="http://xml.demo.com/location/services"
xmlns:typ1="http://xml.demo.com/location/types">
<soapenv:Header>
<typ:requestHeader>
<typ:timestamp>?</typ:timestamp>
<typ:sourceSystemId>TEST</typ:sourceSystemId>
<!--Optional: -->
<typ:sourceSystemUserId>1</typ:sourceSystemUserId>
<typ:sourceServerId>1</typ:sourceServerId>
<typ:trackingId>HYD-12345</typ:trackingId>
</typ:requestHeader>
<wsse:Security soapenv:mustUnderstand="1"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-emmprepaid"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>your-username</wsse:Username>
<wsse:Password
Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">your-password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<ser:getLocation>
<!--Optional: -->
<ser:GetLocation>
<typ1:locationID>HYD-GoldenTulipsEstates</typ1:locationID>
</ser:GetLocation>
</ser:getLocation>
</soapenv:Body>
</soapenv:Envelope>
Fix the screen orientation (landscape or portrait) in AndroidManifest.xml
android:screenOrientation="portrait"
or android:screenOrientation="landscape"
for this your onResume()
method is not called.
Solution in Swift 4
extension UIImage {
var data : Data? {
return cgImage?.dataProvider?.data as Data?
}
}
head
section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and then the reference to your script eg: <script src="uploadfuntion.js"> </script>
4.Lastly you should ensure there are elements that match the selectors in the code.
I would use the yattag library. I think it's the most pythonic way:
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('food'):
with tag('name'):
text('French Breakfast')
with tag('price', currency='USD'):
text('6.95')
with tag('ingredients'):
for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
with tag('ingredient'):
text(ingredient)
print(doc.getvalue())
I solved the problem by installing the development related features of IIS.
By default, IIS doesn't install all the required features.
You should install the IIS development related features to fix the problem.
For express ~4.16.0, express.json with limit works directly
app.use(express.json({limit: '50mb'}));
I had this problem and it was solved by following the code below
var _path=MyFile.FileName;
using (var stream = new FileStream
(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
// Your Code! ;
}
I use jupyter notebooks daily and had never experienced this issue before... until today. I had the notebook open all day but it wasn't running anything and then for no apparent reason stopped auto-saving with the '_xsrf' argument missing from POST
error message in the top right. FYI - this is a python3 notebook.
I don't know the cause of this problem but I have recently upgraded my python3 version to 3.7.2 and upgraded all of my site-packages to their latest version as of a few days ago which could possibly be the cause.
As for a solution, as suggested in the comment by @AlexK, I opened the same notebook in a new window (different browser in fact), using
jupyter notebook list
in the terminal to get the URL with login token.
This resulted in me having the notebook open and savable again but the information I had entered since the last successful auto-save was missing. Thankfully, my broken instance was still open and working apart from saving so I was able to simply copy and paste the information across then hit save. So, keep the broken instance open if you try this!
oSheet.get_Range("A1", "AS1").Merge();
Go to the terminal and write:
rails new <project_name> -d mysql
Got this with Xcode 9.0 while deploying to a non-simulated iPhone 6s with iOS 10.3.
I had force-quit the app right before this arose. Otherwise, nothing had changed; all the developer signing credentials was still trusted, and the app was still marked Verified in the iPhone's Settings.
The trick that fixed it was turning the iPhone off and then turning it back on again.
Looking at my logs, it appears applicationWillTerminate
was triggered a while before this happened; the instance of the app that I thought I force-quit must have been some zombie process?
I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:
@Entity
@Table(name="users")
public class User {..}
Or change the table name manually.
Log into on your Server/PC with administrator account
Log into SQL Server Management Studio as "Windows Authentication"
Click Security -> Logins -> choose your -> right click then choose Properties or Double click -> click Server Roles -> then checklist 'dbcreator' and 'sysadmin' then click the OK button.
Refresh your databases.
Now, you can create new database.
Http is stateless. In order to authorize you, you have to "sign" every single request you're sending to server.
Token authentication
A request to the server is signed by a "token" - usually it means setting specific http headers, however, they can be sent in any part of the http request (POST body, etc.)
Pros:
<img src="http://bank.com?withdraw=1000&to=myself" />
, and if you're logged in via cookie authentication to bank.com, and bank.com doesn't have any means of XSRF protection, I'll withdraw money from your account simply by the fact that your browser will trigger an authorized GET request to that url.) Note there are anti forgery measure you can do with cookie-based authentication - but you have to implement those.Cookie authentication
Overall, I'd say tokens give you better flexibility, (since you're not bound to single domain). The downside is you have to do quite some coding by yourself.
One of the main motivations for using an abstract class is to enable polymorphism within your application -- i.e: you can substitute a different version at runtime. In fact, this is very much the same thing as using an interface except the abstract class provides some common plumbing, often referred to as a Template pattern.
From a unit testing perspective, there are two things to consider:
Interaction of your abstract class with it related classes. Using a mock testing framework is ideal for this scenario as it shows that your abstract class plays well with others.
Functionality of derived classes. If you have custom logic that you've written for your derived classes, you should test those classes in isolation.
edit: RhinoMocks is an awesome mock testing framework that can generate mock objects at runtime by dynamically deriving from your class. This approach can save you countless hours of hand-coding derived classes.
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img>
element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
I just ran into an instance where...
int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];
...did not produce the results I was looking for. In 'myVal' above, the value stored in the array in position 21 was '0'. It should have been a '1'. I'm not sure why I received an inaccurate value for this and it baffled me until I found another way in C# to convert an INT to a bit array:
int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];
This produced the result 'true' as a boolean value for 'myVal'.
I realize this may not be the most efficient way to obtain this value, but it was very straight forward, simple, and readable.
I use Kate as well. Kate's simplicity is its biggest feature. It doesn't get in your way. (This is of course highly subjective opinion.)
Kate includes a Python code browser plugin. But it isn't useful IMO. No automatic updates when you change the code/view. Also when you update, the whole tree is collapsed, and you have to expand it again yourself. Too many clicks.
Instead, I use the Source Browser plugin that comes with Pâté. It does cause Kate to freeze temporarily sometimes, but no crashes or anything of that sort so far.
Shameless blog plug: more on using Django with Kate (Pâté)
Use an array or vector of strings with matching values:
char *ErrorTypes[] =
{
"errorA",
"errorB",
"errorC"
};
cout << ErrorTypes[anError];
EDIT: The solution above is applicable when the enum is contiguous, i.e. starts from 0 and there are no assigned values. It will work perfectly with the enum in the question.
To further proof it for the case that enum doesn't start from 0, use:
cout << ErrorTypes[anError - ErrorA];
If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.
import { HostListener } from '@angular/core';
then use below function anywhere in your component ts file.
@HostListener('document:keyup', ['$event'])
handleDeleteKeyboardEvent(event: KeyboardEvent) {
if(event.key === 'Delete')
{
// remove something...
}
}
Indeed this relies on the programmer's preferences. I personally use: numeric(15,4)
to conform to the Generally Accepted Accounting Principles (GAAP).
I think we also need to give the fpm container the volume, dont we? So =>
fpm:
image: php:fpm
volumes:
- ./:/var/www/test/
If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:
[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"
Works in IE9 documentMode for me.
Without a X-UA-Compatible
header/meta to set an explicit documentMode, you'll get a mode based on:
You can change these settings from ‘Tools -> Compatibility view settings’ from the IE menu. Of course that menu is now sneakily hidden, so you won't see it until you press Alt.
As a site author, if you're confident that your site complies to standards (renders well in other browsers, and uses feature-sniffing to decide what browser workarounds to use), I suggest using:
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
or the HTTP header:
X-UA-Compatible: IE=Edge
to get the latest renderer whatever IE version is in use.
You can also use the extension "Configuration Transform" works the same as "SlowCheetah",
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
JS
$(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
$("#submit").click(function () {
alert('button clicked');
});
});
html
<input id="submit" type="submit" value="submit" name="submit">
I use the data.table package. With its :=
operator you can :
None of these operations copy the (potentially large) data.table
at all, not even once.
data.table
uses much less working memory.Related links :
if you really wanted to do that you could then do
<script type="text/javascript">
document.write(produceMessage())
</script>
Wherever in the document you want the message.
I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert
), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).
Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:
'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue
"B1" can be replaced by any cell on the sheet.
The problem with all suggested approaches: all RegEx is validating
All RegEx -based code is over-engineered: it will find only valid URLs! As a sample, it will ignore anything starting with "http://" and having non-ASCII characters inside.
Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package (filtering Email addresses from text) for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...
Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with "http://" etc., and to concatenate tokens into text again.
If you want to filter Emails from text (because later on you will do NLP staff etc) - just remove all tokens containing "@" inside.
This is simple text where RegEx of Java 6 fails. Try it in divverent variants of Java. It takes about 1000 milliseconds per RegEx call, in a long running single threaded test application:
pattern = Pattern.compile("[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})", Pattern.CASE_INSENSITIVE);
"Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna");
"@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.";
Do not rely on regular expressions if you only need to filter words with "@", "http://", "ftp://", "mailto:"; it is huge engineering overhead.
If you really want to use RegEx with Java, try Automaton
finally, I can find a new version for the right to left bootstrap. share here for use by all:
bootstrap-3-3-7-rtl and RTL Bootstrap 4.0.0-alpha.6.1
GitHub link:
https://github.com/parsmizban/RTL-Bootstrap
thank you parsmizban.com for creating and share.
It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.
The query will return all rows that
(common identical rows will be excluded).
"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.
select pk
,decode(a.rowid, null, null, 'A') as a
,decode(b.rowid, null, null, 'B') as b
,a.col1, b.col1
,a.col2, b.col2
,a.col3, b.col3
,...
from table1 a
full outer
join table2 b using(pk)
where decode(a.col1, b.col1, 1, 0) = 0
or decode(a.col2, b.col2, 1, 0) = 0
or decode(a.col3, b.col3, 1, 0) = 0
or ...;
Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.
with a as(
select 0 as col1 from dual union all
select 1 as col1 from dual union all
select null as col1 from dual
)
,b as(
select 1 as col1 from dual union all
select 2 as col1 from dual union all
select null as col1 from dual
)
select a.col1
,b.col1
,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2
from a,b
order
by a.col1
,b.col1;
col1 col1_1 approach_1 approach_2
==== ====== ========== ==========
0 1 Different Different
0 2 Different Different
0 null Different Same <---
1 1 Same Same
1 2 Different Different
1 null Different Same <---
null 1 Different Same <---
null 2 Different Same <---
null null Same Same
Try autoplay="autoplay"
instead of the "true"
value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.
well, the answer is yes... AND NO.
depends on the question. everybody here answered regarding Java >= 5, and some mentioned that Java < 5 does not feature covariant return types.
actually, the Java language spec >= 5 supports it, but the Java runtime does not. in particular, the JVM was not updated to support covariant return types.
in what was seen then as a "clever" move but ended up being one of the worst design decisions in Java's history, Java 5 implemented a bunch of new language features without modifying the JVM or the classfile spec at all. instead all features were implemented with trickery in javac: the compiler generates/uses plain classes for nested/inner classes, type erasure and casts for generics, synthetic accessors for nested/inner class private "friendship", synthetic instance fields for outer 'this' pointers, synthetic static fields for '.class' literals, etc, etc.
and covariant return types is yet more syntactic sugar added by javac.
for example, when compiling this:
class Base {
Object get() { return null; }
}
class Derived extends Base {
@Override
@SomeAnnotation
Integer get() { return null; }
}
javac will output two get methods in the Derived class:
Integer Integer:Derived:get() { return null; }
synthetic bridge Object Object:Derived:get() { return Integer:Derived:get(); }
the generated bridge method (marked synthetic
and bridge
in bytecode) is what actually overrides Object:Base:get()
because, to the JVM, methods with different return types are completely independent and cannot override each other. to provide the expected behavior, the bridge simply calls your "real" method. in the example above, javac will annotate both bridge and real methods in Derived with @SomeAnnotation.
note that you cannot hand-code this solution in Java < 5, because bridge and real methods only differ in return type and thus they cannot coexist in a Java program. but in the JVM world, method return types are part of the method signature (just like their arguments) and so the two methods named the same and taking the same arguments are nonetheless seen as completely independent by the JVM due to their differing return types, and can coexist.
(BTW, the types of fields are similarly part of the field signature in bytecode, so it is legal to have several fields of different types but named the same within a single bytecode class.)
so to answer your question fully: the JVM does not support covariant return types, but javac >= 5 fakes it at compile time with a coating of sweet syntactic sugar.
Just by looking at the image from the help pages, it makes a lot of sense.
So you have the blue boxes compileClasspath
and runtimeClassPath
.
The compileClasspath
is what is required to make a successful build when running gradle build
. The libraries that will be present on the classpath when compiling will be all libraries that are configured in your gradle build using either compileOnly
or implementation
.
Then we have the runtimeClasspath
and those are all packages that you added using either implementation
or runtimeOnly
. All those libraries will be added to the final build file (jar) that you deploy on the server.
As you also see in the image, if you want a library to be both used for compilation but you also want it added to the build file, then implementation
should be used.
An example of runtimeOnly
can be a database driver.
An example of compileOnly
can be servlet-api.
An example of implementation
can be spring-core.
Use inline styles:
<div class="button" style="width:60px;height:100px;">This is a button</div>
If there is no selection, you can use the properties .selectionStart
or .selectionEnd
(with no selection they're equal).
var cursorPosition = $('#myTextarea').prop("selectionStart");
Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.
I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.
Maybe a bit late, but this is my RE:
/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/
Explanation:
\w*
-> 0 or more alphanumeric digits, at the beginning
\d+[a-zA-Z]|[a-zA-Z]+\d
-> a digit + a letter OR a letter + a digit
\w*
-> 0 or more alphanumeric digits, again
I hope it was understandable
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart
is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize
is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1
and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET
item.
Add an extra apostrophe '
to the MessageFormat
pattern String
to ensure the '
character is displayed
String text =
java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
^
An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc
A single quote itself must be represented by doubled single quotes '' throughout a String.
The String
You\\'re
is equivalent to adding a backslash character to the String
so the only difference will be that You\re
will be produced rather than Youre
. (before double quote solution ''
applied)
You can also try this for Html.ActionLink DeleteId
If you are upgrading any 3.x.y to 3.x.z (patch) Python version, just go to Python downloads page get the latest version and start the installation. Since you already have Python installed on your machine installer will prompt you for "Upgrade Now". Click on that button and it will replace the existing version with a new one. You also will have to restart a computer after installation.
If you are upgrading from 3.x to 3.y (minor) then you will be prompted with "Install Now". In this case, you are not upgrading, but you are installing a new version of Python. You can have more than one version installed on your machine. They will be located in different directories. When you have more than one Python version on your machine you will need to use py lanucher to launch a specific version of Python.
For instance:
py -3.7
or
py -3.8
Make sure you have py launcher installed on your machine. It will be installed automatically if you are using default settings of windows installer. You can always check it if you click on "Customize installation" link on the installation window.
If you have several Python versions installed on your machine and you have a project that is using the previous version of Python using virtual environment e.g. (venv) you can upgrade Python just in that venv using:
python -m venv --upgrade "your virtual environment path"
For instance, I have Python 3.7 in my ./venv virtual environment and I would like upgrade venv to Python 3.8, I would do following
python -m venv --upgrade ./venv
removeChild
should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
It is possible that you have multiple versions of the dll(s) on your system. You can search your system to find out. The issue may be solved by simply changing the order of the directories in your path. This was my issue. (Cannot run Qt Creator GUI outside of Qt. "The application was unable to start correctly (0xc000007b)" error)
A loading indicator is simply an animated image (.gif) that is displayed until the completed event is called on the AJAX request. http://ajaxload.info/ offers many options for generating loading images that you can overlay on your modals. To my knowledge, Bootstrap does not provide the functionality built-in.
<%= link_to root_path do %><%= image_tag("Search.png",:alt=>'Vivek',:title=>'Vivek',:class=>'dock-item')%><%= content_tag(:span, "Search").html_safe%><% end %>
Assuming that you do not want to change orig
, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
Or without itertools:
dest = dict(list(orig.items()) + list(extra.items()))
Note that you only need to pass the result of items()
into list()
on Python 3, on 2.x dict.items()
already returns a list so you can just do dict(orig.items() + extra.items())
.
As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:
from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))
echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl
In the first place consider the Small grid, see: http://getbootstrap.com/css/#grid-options. A max container width of 750 px will maybe to small for you (also read: Why does Bootstrap 3 force the container width to certain sizes?)
When using the Small grid use media queries to set the max-container width:
@media (min-width: 768px) { .container { max-width: 750px; } }
Second also read this question: Bootstrap 3 - 940px width grid?, possible duplicate?
12 x 60 = 720px for the columns and 11 x 20 = 220px
there will also a gutter of 20px on both sides of the grid so 220 + 720 + 40 makes 980px
there is 'no' @ColumnWidth
You colums width will be calculated dynamically based on your settings in variables.less.
you could set @grid-columns
and @grid-gutter-width
. The width of a column will be set as a percentage via grid.less in mixins.less:
.calc-grid(@index, @class, @type) when (@type = width) {
.col-@{class}-@{index} {
width: percentage((@index / @grid-columns));
}
}
update Set @grid-gutter-width to 20px;, @container-desktop: 940px;, @container-large-desktop: @container-desktop and recompile bootstrap.
var fileName = 'file.txt';
// Getting Extension
var ext = fileName.split('.')[1];
// OR
var ext = fileName.split('.').pop();
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
In newer versions of Eclipse that use the M2E plugin it is:
Right-click on your project(s) --> Maven --> Update Project...
In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")
while not condition1 or not condition2 or val == -1:
But there was nothing wrong with your original of using an if inside of a while True.
Short snippet for future visitors - how to center horizontal table-cell (+ vertically)
html, body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center; /* the key */_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: inline-block; /* important !! */_x000D_
width: 100px;_x000D_
background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
<div class="cell">_x000D_
<div class="content" id="a">_x000D_
<p>Content</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The Javadoc for String reveals that String.split()
is what you're looking for in regard to explode
.
Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder
is one:
String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
if (i != split.length - 1) {
sb.append(" ");
}
}
String joined = sb.toString();
You can use Enum.Parse
to get an enum value from the name. You can iterate over all values with Enum.GetNames
, and you can just cast an int to an enum to get the enum value from the int value.
Like this, for example:
public MyColours GetColours(string colour)
{
foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
if (mc.ToString().Contains(colour)) {
return mc;
}
}
return MyColours.Red; // Default value
}
or:
public MyColours GetColours(string colour)
{
return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}
The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.
No! There is no 64-bit version of Visual Studio.
How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0
As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
Just delete the bin folder and then then the project recreates all again and it will be working now .
You can use Reflection to obtain the actual names of the properties.
http://www.csharp-examples.net/reflection-property-names/
If you need a way to assign a "String Name" to a property, why don't you write an attribute that you can reflect over to get the string name?
[StringName("MyStringName")]
private string MyProperty
{
get { ... }
}
Your code makes no sense, maybe because it's out of context.
If you mean code like this:
$('a').click(function () {
callFunction();
return false;
});
The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.
As @Vlad from Moscow says,
Take into account that value_type
for std::map
is defined the following way:
typedef pair<const Key, T> value_type
This then means that if you wish to replace the keyword auto
with a more explicit type specifier, then you could this;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Just for understanding what auto
will translate to in this case.
I know this is an old question, but I think this is the definitive answer.
listViewRamos.Items[i].Focused = true;
listViewRamos.Items[i].Selected = true;
listViewRemos.Items[i].EnsureVisible();
If there is a chance the control does not have the focus but you want to force the focus to the control, then you can add the following line.
listViewRamos.Select();
Why Microsoft didn't just add a SelectItem()
method that does all this for you is beyond me.
This should work for every default repo:
git pull origin master
If your default branch is different than master
, you will need to specify the branch name:
git pull origin my_default_branch_name
If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:
---- foo_proxy.py ----
tmp = __import__('foo-bar')
globals().update(vars(tmp))
---- main.py ----
from foo_proxy import *
Fiddle 1: a replica of the modal used on the twitter bootstrap site. (This is the modal that doesn't display by default, but that launches when you click on the demo button.)
Fiddle 2: a replica of the modal described in the bootstrap documentation,
but that incorporates the necessary elements to avoid the use of any javascript.
Note especially the inclusion of the hide
class on #myModal
div, and the use of data-dismiss="modal"
on the Close button.
<a class="btn" data-toggle="modal" href="#myModal">Launch Modal</a>
<div class="modal hide" id="myModal"><!-- note the use of "hide" class -->
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a><!-- note the use of "data-dismiss" -->
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>?
It's also worth noting that the site you are using is running on bootstrap 2.0, while the official twitter bootstrap site is on 2.0.3.
Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding
swift 3
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
I am using Chrome version 75.
add the muted property to video tag
<video id="myvid" muted>
then play it using javascript and set muted to false
var myvideo = document.getElementById("myvid");
myvideo.play();
myvideo.muted = false;
edit: need user interaction (at least click anywhere in the page to work)
In Azure environment with Basic website that has 1 Instance.I tried to insert a Batch of 1000 records at a time out of 25000 records using for loop it took 11.5 min but in parallel execution it took less than a minute.So I recommend using TPL(Task Parallel Library).
var count = (you collection / 1000) + 1;
Parallel.For(0, count, x =>
{
ApplicationDbContext db1 = new ApplicationDbContext();
db1.Configuration.AutoDetectChangesEnabled = false;
var records = members.Skip(x * 1000).Take(1000).ToList();
db1.Members.AddRange(records).AsParallel();
db1.SaveChanges();
db1.Dispose();
});
If somebody is looking for solution respecting holidays (without any huge library like pandas), try this function:
import holidays
import datetime
def previous_working_day(check_day_, holidays=holidays.US()):
offset = max(1, (check_day_.weekday() + 6) % 7 - 3)
most_recent = check_day_ - datetime.timedelta(offset)
if most_recent not in holidays:
return most_recent
else:
return previous_working_day(most_recent, holidays)
check_day = datetime.date(2020, 12, 28)
previous_working_day(check_day)
which produce:
datetime.date(2020, 12, 24)
I had several inconveniences with all the solutions because I needed the type of Instant variable and the Time Zone always interfered changing everything, then combining solutions I saw that this is a good option.
LocalDate today = LocalDate.now();
Instant startDate = Instant.parse(today.toString()+"T00:00:00Z");
Instant endDate = Instant.parse(today.toString()+"T23:59:59Z");
and we have as a result
startDate = 2020-01-30T00:00:00Z
endDate = 2020-01-30T23:59:59Z
I hope it helps you
From the Publish
tab go to application Files
.
Then, click unnecessary files
.
After that, do the exclude press ok
.
Finally, build the project files and run the projects.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
You can use the Windows API function ShellExecute
to do so:
Option Explicit
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Public Sub OpenUrl()
Dim lSuccess As Long
lSuccess = ShellExecute(0, "Open", "www.google.com")
End Sub
Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute
would execute any command with the user's permissions, also a format c:
would be executed if the user is an administrator.
Just some python 3.5 options to complete the answers above. (I would have loved to find them here).
import os
import shutil
from send2trash import send2trash # (shutil delete permanently)
Delete folder if empty
root = r"C:\Users\Me\Desktop\test"
for dir, subdirs, files in os.walk(root):
if subdirs == [] and files == []:
send2trash(dir)
print(dir, ": folder removed")
Delete also folder if it contains this file
elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file
if files[0]== "desktop.ini" or:
send2trash(dir)
print(dir, ": folder removed")
else:
print(dir)
delete folder if it contains only .srt or .txt file(s)
elif subdirs == []: #if dir doesn’t contains subdirectory
ext = (".srt", ".txt")
contains_other_ext=0
for file in files:
if not file.endswith(ext):
contains_other_ext=True
if contains_other_ext== 0:
send2trash(dir)
print(dir, ": dir deleted")
Delete folder if its size is less than 400kb :
def get_tree_size(path):
"""Return total size of files in given path and subdirs."""
total = 0
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
total += get_tree_size(entry.path)
else:
total += entry.stat(follow_symlinks=False).st_size
return total
for dir, subdirs, files in os.walk(root):
If get_tree_size(dir) < 400000: # ˜ 400kb
send2trash(dir)
print(dir, "dir deleted")
I got the same error in this case:
var result = Db.SystemLog
.Where(log =>
eventTypeValues.Contains(log.EventType)
&& (
search.Contains(log.Id.ToString())
|| log.Message.Contains(search)
|| log.PayLoad.Contains(search)
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
)
)
.OrderByDescending(log => log.Id)
.Select(r => r);
After spending way too much time debugging, I figured out that error appeared in the logic expression.
The first line search.Contains(log.Id.ToString())
does work fine, but the last line that deals with a DateTime object made it fail miserably:
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
Remove the problematic line and problem solved.
I do not fully understand why, but it seems as ToString() is a LINQ expression for strings, but not for Entities. LINQ for Entities deals with database queries like SQL, and SQL has no notion of ToString(). As such, we can not throw ToString() into a .Where() clause.
But how then does the first line work? Instead of ToString(), SQL have CAST
and CONVERT
, so my best guess so far is that linq for entities uses that in some simple cases. DateTime objects are not always found to be so simple...
Here is a relatively simple recursive solution. I think a breadth-first search is appropriate here. This will return the first element matching the class that is found.
function getDescendantWithClass(element, clName) {
var children = element.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].className &&
children[i].className.split(' ').indexOf(clName) >= 0) {
return children[i];
}
}
for (var i = 0; i < children.length; i++) {
var match = getDescendantWithClass(children[i], clName);
if (match !== null) {
return match;
}
}
return null;
}
I was getting this error while trying to show DatePicker
from Fragment
.
I changed
val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)
to
val datePickerDialog = DatePickerDialog(requireContext(), ...)
and it worked just fine.
Short answer:
There is no difference in semantic.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
Further reading:
RequestMapping
can be used at class level:
This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
while GetMapping
only applies to method:
Annotation for mapping HTTP GET requests onto specific handler methods.
It's simpler to use, the -a option :
cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]
Just for completeness (because nobody else posted the most obvious answer):
Oracle:
DECODE(PC_SL_LDGR_CODE, '02', 'DR', 'CR')
MSSQL (2012+):
IIF(PC_SL_LDGR_CODE='02', 'DR', 'CR')
The bad news:
DECODE
with more than 4 arguments would result in an ugly IIF
cascade
Did you change conf/hdfs-site.xml
dfs.name.dir
?
Format namenode after you change it.
$ bin/hadoop namenode -format
$ bin/hadoop start-all.sh
This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and str.join
was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported str
methods including join
) was released in Oct 2000.
str.join(seq)
seq.join(str)
seq.reduce(str)
join
as a built-in functionlist
s, tuple
s, but all sequences/iterables.seq.reduce(str)
is difficult for new-comers.seq.join(str)
introduces unexpected dependency from sequences to str/unicode.join()
as a built-in function would support only specific data types. So using a built in namespace is not good. If join()
supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__
method then it's O(n²).sep
) should not be omitted. Explicit is better than implicit.There are no other reasons offered in this thread.
Here are some additional thoughts (my own, and my friend's):
Guido's decision is recorded in a historical mail, deciding on str.join(seq)
:
Funny, but it does seem right! Barry, go for it...
--Guido van Rossum
Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.
Look at https://stackoverflow.com/a/4726838/2963099
Turn off pre compiled headers:
Project Properties -> C++ -> Precompiled Headers
set Precompiled Header
to "Not Using Precompiled Header"
.
With the latest version, you are recommended to switch to the embedded JDK like in the image below, and this will solve your error
Treat function as variable in your program so you can just pass them to other functions easily:
def test ():
print "test was invoked"
def invoker(func):
func()
invoker(test) # prints test was invoked
You could also set the default format for float :
pd.options.display.float_format = '{:.2%}'.format
Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
For those of you installing ELK on virtual machine in GCP (Google Cloud Platform), make sure that you created firewall rule of Ingress
type (i.e. for incoming to VM traffic). You can specify in the rule multiple ports at a time by separating them with comma: 5000,5044,5601,9200,9300,9600
.
In that rule you may want to specify a tag (pick tag's name as you like, for example docker-elk
that will target your VM (Targets column):
On VM's settings page assign that tag to your VM:
After doing that I was able to access Elasticsearch in my browser via port 9200. And I didn't have to edit elasticsearch.yml
file whatsoever.
There is no command based text editors in windows (at least from Windows 7). But you can try the vi windows clone available here : http://www.vim.org/
In general Android OS leverages a “theme” to allow app developers to globally apply a universal set of UI element styling parameters to Android applications as a whole, or, alternatively, to a single Activity subclass.
So there are three mainstream Android OS “system themes,” which you can specify in your Android Manifest XML file when you are developing apps for Version 3.0 and later versions
I am referring the (APPCOMPAT)support library here:-- So the three themes are 1. AppCompat Light Theme (Theme.AppCompat.Light)
AndroidManifest.xml and see the tag, the android theme is mentioned as:-- android:theme="@style/AppTheme"
Open the Styles.xml and we have base application theme declared there:--
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
We need to override these parent theme elements to style the action bar.
ActionBar with different color background:--
To do this we need to create a new style MyActionBar(you can give any name) with a parent reference to @style/Widget.AppCompat.Light.ActionBar.Solid.Inverse that holds the style characteristics for the Android ActionBar UI element. So definition would be
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@color/red</item>
</style>
And this definition we need to reference in our AppTheme, pointing to overridden ActionBar styling as--
Change the title bar text color (e.g black to white):--
Now to change the title text color, we need to override the parent reference parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
So the style definition would be
<style name="MyActionBarTitle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/white</item>
</style>
We’ll reference this style definition inside the MyActionBar style definition, since the TitleTextStyle modification is a child element of an ActionBar parent OS UI element. So the final definition of MyActionBar style element will be
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@color/red</item>
<item name="titleTextStyle">@style/MyActionBarTitle</item>
</style>
SO this is the final Styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- This is the styling for action bar -->
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@color/red</item>
<item name="titleTextStyle">@style/MyActionBarTitle</item>
</style>
<style name="MyActionBarTitle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/white</item>
</style>
</resources>
For further ActionBar options Menu styling, refer this link
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask =
client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from
getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length
value.
return urlContents.Length;
}
Previous answers assume that the branch to be reset is the current branch (checked out). In comments, OP hap497 clarified that the branch is indeed checked out, but this is not explicitly required by the original question. Since there is at least one "duplicate" question, Reset branch completely to repository state, which does not assume that the branch is checked out, here's an alternative:
If branch "mybranch" is not currently checked out, to reset it to remote branch "myremote/mybranch"'s head, you can use this low-level command:
git update-ref refs/heads/mybranch myremote/mybranch
This method leaves the checked out branch as it is, and the working tree untouched. It simply moves mybranch's head to another commit, whatever is given as the second argument. This is especially helpful if multiple branches need to be updated to new remote heads.
Use caution when doing this, though, and use gitk
or a similar tool to double check source and destination. If you accidentally do this on the current branch (and git will not keep you from this), you may become confused, because the new branch content does not match the working tree, which did not change (to fix, update the branch again, to where it was before).
With WAMP
it's all pretty easy
WAMP
Icon > PHP > PHP Settings > upload_max_filesize = nM > n = (2M, 4M, 8M, 16M, 32M, 64M, 128M, 256M, 512M, or Choose (custom)).
Service(s) reload automatically.
But, if you truly have no access to the server, you might want to explore writing a chunking
API.
There are some good answers here, but I wanted to point out a couple of other things. Function parameters are actually a place where PowerShell shines. For example, you can have either named or positional parameters in advanced functions like so:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[int] $Id
)
}
Then you could either call it by specifying the parameter name, or you could just use positional parameters, since you explicitly defined them. So either of these would work:
Get-Something -Id 34 -Name "Blah"
Get-Something "Blah" 34
The first example works even though Name
is provided second, because we explicitly used the parameter name. The second example works based on position though, so Name
would need to be first. When possible, I always try to define positions so both options are available.
PowerShell also has the ability to define parameter sets. It uses this in place of method overloading, and again is quite useful:
function Get-Something
{
[CmdletBinding(DefaultParameterSetName='Name')]
Param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Name')]
[string] $Name,
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Id')]
[int] $Id
)
}
Now the function will either take a name, or an id, but not both. You can use them positionally, or by name. Since they are a different type, PowerShell will figure it out. So all of these would work:
Get-Something "some name"
Get-Something 23
Get-Something -Name "some name"
Get-Something -Id 23
You can also assign additional parameters to the various parameter sets. (That was a pretty basic example obviously.) Inside of the function, you can determine which parameter set was used with the $PsCmdlet.ParameterSetName property. For example:
if($PsCmdlet.ParameterSetName -eq "Name")
{
Write-Host "Doing something with name here"
}
Then, on a related side note, there is also parameter validation in PowerShell. This is one of my favorite PowerShell features, and it makes the code inside your functions very clean. There are numerous validations you can use. A couple of examples are:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern('^Some.*')]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateRange(10,100)]
[int] $Id
)
}
In the first example, ValidatePattern accepts a regular expression that assures the supplied parameter matches what you're expecting. If it doesn't, an intuitive exception is thrown, telling you exactly what is wrong. So in that example, 'Something' would work fine, but 'Summer' wouldn't pass validation.
ValidateRange ensures that the parameter value is in between the range you expect for an integer. So 10 or 99 would work, but 101 would throw an exception.
Another useful one is ValidateSet, which allows you to explicitly define an array of acceptable values. If something else is entered, an exception will be thrown. There are others as well, but probably the most useful one is ValidateScript. This takes a script block that must evaluate to $true, so the sky is the limit. For example:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[ValidateScript({ (Get-Item $_ | select -Expand Extension) -eq ".csv" })]
[string] $Path
)
}
In this example, we are assured not only that $Path exists, but that it is a file, (as opposed to a directory) and has a .csv extension. ($_ refers to the parameter, when inside your scriptblock.) You can also pass in much larger, multi-line script blocks if that level is required, or use multiple scriptblocks like I did here. It's extremely useful and makes for nice clean functions and intuitive exceptions.
NOTE: The make tool reads the makefile and checks the modification time-stamps of the files at both the side of ':' symbol in a rule.
In a directory 'test' following files are present:
prerit@vvdn105:~/test$ ls
hello hello.c makefile
In makefile a rule is defined as follows:
hello:hello.c
cc hello.c -o hello
Now assume that file 'hello' is a text file containing some data, which was created after 'hello.c' file. So the modification (or creation) time-stamp of 'hello' will be newer than that of the 'hello.c'. So when we will invoke 'make hello' from command line, it will print as:
make: `hello' is up to date.
Now access the 'hello.c' file and put some white spaces in it, which doesn't affect the code syntax or logic then save and quit. Now the modification time-stamp of hello.c is newer than that of the 'hello'. Now if you invoke 'make hello', it will execute the commands as:
cc hello.c -o hello
And the file 'hello' (text file) will be overwritten with a new binary file 'hello' (result of above compilation command).
If we use .PHONY in makefile as follow:
.PHONY:hello
hello:hello.c
cc hello.c -o hello
and then invoke 'make hello', it will ignore any file present in the pwd 'test' and execute the command every time.
Now suppose, that 'hello' target has no dependencies declared:
hello:
cc hello.c -o hello
and 'hello' file is already present in the pwd 'test', then 'make hello' will always show as:
make: `hello' is up to date.
Note to other people finding this: The heart of the solution to make nginx not manipulate the URL, is to remove the slash at the end of the Copy: proxy_pass directive. http://my_app_upstream vs http://my_app_upstream/ – Hugo Josefson
I found this above in the comments but I think it really should be an answer.
You've probably got Option Strict turned on (which is a good thing), and the compiler is telling you that you can't add a string and an int. Try this:
t = s1 & i.ToString()
I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs
Used in my comic book reader: https://github.com/codedread/kthoom (also open source).
HTH!
In case you don't want to use a temporary variable, you can also do like this:
final int len = arr.length;
for (int i=0; i < (len/2); i++) {
arr[i] += arr[len - 1 - i]; // a = a+b
arr[len - 1 - i] = arr[i] - arr[len - 1 - i]; // b = a-b
arr[i] -= arr[len - 1 - i]; // a = a-b
}
If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name
under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com
and one for redirect-to.final-destination.com
. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.
Do the following steps for file/folder:
Remove File:
For example:
I want to delete test.txt file. I accidentally pushed to GitHub want to remove commands will be followed as:
1st add test.txt in .gitignore
git rm --cached test.txt
git add .
git commit -m "test.txt removed"
git push
Remove Folder:
For example:
I want to delete the .idea folder/dir. I accidentally pushed to GitHub want to remove commands will be followed as:
1st add .idea in .gitignore
git rm -r --cached .idea
git add .
git commit -m ".idea removed"
git push
If using async & await and desire to use a time out without blocking, then an alternative and simpler approach from the answer provide by mcandal is to execute the connect on a background thread and await the result. For example:
Task<bool> t = Task.Run(() => client.ConnectAsync(ipAddr, port).Wait(1000));
await t;
if (!t.Result)
{
Console.WriteLine("Connect timed out");
return; // Set/return an error code or throw here.
}
// Successful Connection - if we get to here.
See the Task.Wait MSDN article for more info and other examples.
If your command is:
$ ssh -p 1122 path/to/pemfile user@[hostip/hostname]
You will also face the same error
ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known
when you miss the option -i /path/to/pemfile
of ssh
So Command should be:
$ ssh -p 1122 -i path/to/pemfile user@[hostip/hostname]
go to Help
-> Install New Software...
-> Add
-> Archive...
. Done.
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
Try this:
$("div[class]").filter(function() {
var classNames = this.className.split(/\s+/);
for (var i=0; i<classNames.length; ++i) {
if (classNames[i].substr(0, 6) === "apple-") {
return true;
}
}
return false;
})
If you are really like to know that handle CSV files perfectly in Java, it's not good to try to implement CSV reader/writer by yourself. Check below out.
http://opencsv.sourceforge.net/
When your CSV document includes double-quotes or newlines, you will face difficulties.
To learn object-oriented approach at first, seeing other implementation (by Java) will help you. And I think it's not good way to manage one row in a List. CSV doesn't allow you to have difference column size.
If you want exactly one byte, uint8_t defined in cstdint would be the most expressive.
Here's the source code of an HttpHandler which does that, maybe it'll help you
These are Open Source projects (or developers) which can use donations to fund to help support their business.
In npm the command npm fund
will list the urls where you can fund
In composer the command composer fund
will do the same.
While there are options mentioned above using which one can use to get rid of the funding message, but try to support the cause if you can.
I had same issue but finally i got success by doing this please go throw this image Plase Run all the command in the PHONE TOOL COMMAND PROMPT
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis
only affects the x-axis is not true:
set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)
at least for me with:
> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
[5] LC_MONETARY=C LC_MESSAGES=en_GB.UTF-8
[7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] grid stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8 reshape_0.8.3 plyr_1.2.1
loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1
Also, cex.axis
affects the labelling of tick marks. cex.lab
is used to control what R call the axis labels.
plot(Y ~ X, data = foo, cex.lab = 3)
but even that works for both the x- and y-axis.
Following up Jens' comment about using barplot()
. Check out the cex.names
argument to barplot()
, which allows you to control the bar labels:
dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)
As you mention that cex.axis
was only affecting the x-axis I presume you had horiz = TRUE
in your barplot()
call as well? As the bar labels are not drawn with an axis()
call, applying Joris' (otherwise very useful) answer with individual axis()
calls won't help in this situation with you using barplot()
HTH
Is http://api.xxx.com/
part of your domain? If not, you are being blocked by the same origin policy.
You may want to check out the following Stack Overflow post for a few possible workarounds:
If you use the Date
property for DB Entities you will get exception:
"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
You can use something like this:
DateTime date = DateTime.Now.Date;
var result = from client in context.clients
where client.BirthDate >= date
&& client.BirthDate < date.AddDays(1)
select client;
@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.
If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:
Link Your Containers
When you docker run
your containers, typically by inputting a shell script into User Data
, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:
#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx
So in this example, the API
container isn't linked to any others, but the
App
container is linked to API
and Nginx
is linked to both API
and App
.
The result of this is changes to the env
vars and the /etc/hosts
files that reside within the API
and App
containers. The results look like so:
/etc/hosts
Running cat /etc/hosts
within your Nginx
container will produce the following:
172.17.0.5 0fd9a40ab5ec
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 App
172.17.0.2 API
ENV Vars
Running env
within your Nginx
container will produce the following:
API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2
APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3
I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.
To obtain a shell to run the above commands within a running container, use the following:
sudo docker exec -i -t Nginx bash
You can see that you now have both /etc/hosts
file entries and env
vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx
within your Nginx
container.
Configuring Nginx
This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts
file that docker
created, or you can utilize the ENV
vars and run a string replacement (I used sed
) on your nginx.conf
and any other conf files that may be in your /etc/nginx/sites-enabled
folder to insert the IP values.
OPTION A: Configure Nginx Using ENV Vars
This is the option that I went with because I couldn't get the
/etc/hosts
file option to work. I'll be trying Option B soon enough and update this post with any findings.
The key difference between this option and using the /etc/hosts
file option is how you write your Dockerfile
to use a shell script as the CMD
argument, which in turn handles the string replacement to copy the IP values from ENV
to your conf file(s).
Here's the set of configuration files I ended up with:
Dockerfile
FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>
RUN apt-get update && apt-get install -y nano htop git nginx
ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh
EXPOSE 80 443
CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]
nginx.conf
daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;
events {
worker_connections 1024;
}
http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 33;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging Settings
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip Settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 3;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/xml text/css application/x-javascript application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# Virtual Host Configs
include /etc/nginx/sites-enabled/*;
# Error Page Config
#error_page 403 404 500 502 /srv/Splash;
}
NOTE: It's important to include
daemon off;
in yournginx.conf
file to ensure that your container doesn't exit immediately after launching.
api.myapp.conf
upstream api_upstream{
server APP_IP:3000;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.myapp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
Nginx-Startup.sh
#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com
service nginx start
I'll leave it up to you to do your homework about most of the contents of nginx.conf
and api.myapp.conf
.
The magic happens in Nginx-Startup.sh
where we use sed
to do string replacement on the APP_IP
placeholder that we've written into the upstream
block of our api.myapp.conf
and app.myapp.conf
files.
This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands
GOTCHA On OSX,
sed
handles options differently, the-i
flag specifically. On Ubuntu, the-i
flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the-i
flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the-i
flag.GOTCHA To use ENV vars within the regex that
sed
uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.
So docker has launched our container and triggered the Nginx-Startup.sh
script to run, which has used sed
to change the value APP_IP
to the corresponding ENV
variable we provided in the sed
command. We now have conf files within our /etc/nginx/sites-enabled
directory that have the IP addresses from the ENV
vars that docker set when starting up the container. Within your api.myapp.conf
file you'll see the upstream
block has changed to this:
upstream api_upstream{
server 172.0.0.2:3000;
}
The IP address you see may be different, but I've noticed that it's usually 172.0.0.x
.
You should now have everything routing appropriately.
GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So
api.myapp.com
will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. ButNginx
will have already set the first IP into its conf files, or in its/etc/hosts
file, so it won't be able to determine the new IP forapi.myapp.com
. The solution to this is likely to useCoreOS
and itsetcd
service which, in my limited understanding, acts like a sharedENV
for all machines registered into the sameCoreOS
cluster. This is the next toy I'm going to play with setting up.
OPTION B: Use /etc/hosts
File Entries
This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts
entry into your api.myapp.conf
and app.myapp.conf
files, but I couldn't get this method to work.
UPDATE: See @Wes Tod's answer for instructions on how to make this method work.
Here's the attempt that I made in api.myapp.conf
:
upstream api_upstream{
server API:3000;
}
Considering that there's an entry in my /etc/hosts
file like so: 172.0.0.2 API
I figured it would just pull in the value, but it doesn't seem to be.
I also had a couple of ancillary issues with my Elastic Load Balancer
sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.
First, I realize I am late in answering this question.
Before discussing synchronous and asynchronous, let us briefly look at how programs run.
In the synchronous case, each statement completes before the next statement is run. In this case the program is evaluated exactly in order of the statements.
This is how asynchronous works in JavaScript. There are two parts in the JavaScript engine, one part that looks at the code and enqueues operations and another that processes the queue. The queue processing happens in one thread, that is why only one operation can happen at a time.
When an asynchronous operation (like the second database query) is seen, the code is parsed and the operation is put in the queue, but in this case a callback is registered to be run when this operation completes. The queue may have many operations in it already. The operation at the front of the queue is processed and removed from the queue. Once the operation for the database query is processed, the request is sent to the database and when complete the callback will be executed on completion. At this time, the queue processor having "handled" the operation moves on the next operation - in this case
console.log("Hello World");
The database query is still being processed, but the console.log operation is at the front of the queue and gets processed. This being a synchronous operation gets executed right away resulting immediately in the output "Hello World". Some time later, the database operation completes, only then the callback registered with the query is called and processed, setting the value of the variable result to rows.
It is possible that one asynchronous operation will result in another asynchronous operation, this second operation will be put in the queue and when it comes to the front of the queue it will be processed. Calling the callback registered with an asynchronous operation is how JavaScript run time returns the outcome of the operation when it is done.
A simple method of knowing which JavaScript operation is asynchronous is to note if it requires a callback - the callback is the code that will get executed when the first operation is complete. In the two examples in the question, we can see only the second case has a callback, so it is the asynchronous operation of the two. It is not always the case because of the different styles of handling the outcome of an asynchronous operation.
To learn more, read about promises. Promises are another way in which the outcome of an asynchronous operation can be handled. The nice thing about promises is that the coding style feels more like synchronous code.
Many libraries like node 'fs', provide both synchronous and asynchronous styles for some operations. In cases where the operation does not take long and is not used a lot - as in the case of reading a config file - the synchronous style operation will result in code that is easier to read.
install django-registration-redux==1.1 instead django-registration, if you using django 1.7
I used
failed_when: not(promtool_version.stdout.find('1.5.2') != -1)
means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.
View Data
==============
@model IEnumerable<DemoApp.Models.BankInfo>
<p>
<b>Search Results</b>
</p>
@if (!Model.Any())
{
<tr>
<td colspan="4" style="text-align:center">
No Bank(s) found
</td>
</tr>
}
else
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Postcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
<input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
</td>
</tr>
}
</table>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").off("click.search").on("click.search", function () {
if ($("#SearchBy").val() != '') {
$.ajax({
url: '/home/searchByName',
data: { 'name': $("#SearchBy").val() },
dataType: 'html',
success: function (data) {
$('#dvBanks').html(data);
}
});
}
else {
alert('Please enter Bank Name');
}
});
}
});
public ActionResult SearchByName(string name)
{
var banks = GetBanksInfo();
var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
return PartialView("_banks", filteredBanks);
}
/// <summary>
/// Get List of Banks Basically it should get from Database
/// </summary>
/// <returns></returns>
private List<BankInfo> GetBanksInfo()
{
return new List<BankInfo>
{
new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" },
new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" },
new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" },
new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" },
new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" }
};
}
As for the connect by
use case, this approach should work for you:
select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
We found the asnwer of at techieshelp..its the htaccess thats the issue...
I had same error on Ubuntu 18.04
Delete your node_modules folder and run
sudo npm install --unsafe-perm=true
Java Heap Memory is part of memory allocated to JVM by Operating System.
Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.
You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:
Young , Tenured and Perm generation
PermGen has been replaced with Metaspace since Java 8 release.
Regarding your queries:
Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.
I believe you can do something like:
$('iframe').contents().click(function(){function to record click here });
using jQuery to accomplish this.
Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.
It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.
Your Box
class is attempting to define multiple constructor implementations.
Only the last constructor overload signature is used as the class constructor implementation.
In the below example, note the constructor implementation is defined such that it does not contradict either of the preceding overload signatures.
interface IBox = {
x: number;
y: number;
width: number;
height: number;
}
class Box {
public x: number;
public y: number;
public width: number;
public height: number;
constructor() /* Overload Signature */
constructor(obj: IBox) /* Overload Signature */
constructor(obj?: IBox) /* Implementation Constructor */ {
if (obj) {
this.x = obj.x;
this.y = obj.y;
this.width = obj.width;
this.height = obj.height;
} else {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0
}
}
get frame(): string {
console.log(this.x, this.y, this.width, this.height);
}
}
new Box().frame; // 0 0 0 0
new Box({ x:10, y:10, width: 70, height: 120 }).frame; // 10 10 70 120
// You could also write the Box class like so;
class Box {
public x: number = 0;
public y: number = 0;
public width: number = 0;
public height: number = 0;
constructor() /* Overload Signature */
constructor(obj: IBox) /* Overload Signature */
constructor(obj?: IBox) /* Implementation Constructor */ {
if (obj) {
this.x = obj.x;
this.y = obj.y;
this.width = obj.width;
this.height = obj.height;
}
}
get frame(): string { ... }
}
strncpy
combats buffer overflow by requiring you to put a length in it. strcpy
depends on a trailing \0
, which may not always occur.
Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n
characters, where n
is the third argument.
The n
functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy
.
If they're block level elements they won't be affected by text-align: center;
. Someone may have set img { display: block; }
and that's throwing it out of whack. You can try:
td { text-align: center; }
td * { display: inline; }
and if it looks as desired you should definitely replace * with the desired elements like:
td img, td foo { display: inline; }
http://php.net/manual/en/reserved.variables.post.php
The first comment answers this.
<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>
<?php
var_dump($_POST['person']);
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>
The name tag can work as an array.
There is also a package called npm-check
:
npm-check
Check for outdated, incorrect, and unused dependencies.
It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheck
module mentioned in the other answer.
Edit: This answer doesn't work for Xcode 10 and higher. See turkenh's answer.
I had experienced this problem and was able to find an answer.
The answer which this is coming from can be found here.
Here is what you have to do:
These steps solved the problem for me.
G45,
I faced same issue , i have created one directive , please check below hope it may be helpful
Directive :
app.directive('formSubmitValidation', function () {
return {
require: 'form',
compile: function (tElem, tAttr) {
tElem.data('augmented', true);
return function (scope, elem, attr, form) {
elem.on('submit', function ($event) {
scope.$broadcast('form:submit', form);
if (!form.$valid) {
$event.preventDefault();
}
scope.$apply(function () {
scope.submitted = true;
});
});
}
}
};
})
HTML :
<form name="loginForm" class="c-form-login" action="" method="POST" novalidate="novalidate" form-submit-validation="">
<div class="form-group">
<input type="email" class="form-control c-square c-theme input-lg" placeholder="Email" ng-model="_username" name="_username" required>
<span class="glyphicon glyphicon-user form-control-feedback c-font-grey"></span>
<span ng-show="submitted || loginForm._username.$dirty && loginForm._username.$invalid">
<span ng-show="loginForm._username.$invalid" class="error">Please enter a valid email.</span>
</span>
</div>
<button type="submit" class="pull-right btn btn-lg c-theme-btn c-btn-square c-btn-uppercase c-btn-bold">Login</button>
</form>
As per George Jempty's
request to have the algorithm account for ties, I propose a modified version of Matthew Flaschen's
algorithm.
function modeString(array) {
if (array.length == 0) return null;
var modeMap = {},
maxEl = array[0],
maxCount = 1;
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null) modeMap[el] = 1;
else modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
} else if (modeMap[el] == maxCount) {
maxEl += "&" + el;
maxCount = modeMap[el];
}
}
return maxEl;
}
This will now return a string with the mode element(s) delimited by a &
symbol. When the result is received it can be split on that &
element and you have your mode(s).
Another option would be to return an array of mode element(s) like so:
function modeArray(array) {
if (array.length == 0) return null;
var modeMap = {},
maxCount = 1,
modes = [];
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null) modeMap[el] = 1;
else modeMap[el]++;
if (modeMap[el] > maxCount) {
modes = [el];
maxCount = modeMap[el];
} else if (modeMap[el] == maxCount) {
modes.push(el);
maxCount = modeMap[el];
}
}
return modes;
}
In the above example you would then be able to handle the result of the function as an array of modes.
In my case, i had deleted the original branch from which my current branch derived from. So in the .git/config file i had:
[branch "simil2.1.12"]
remote = origin
merge = refs/heads/simil2.0.5
rebase = false
the simil2.0.5 was deleted. I replaced it with the same branch name:
[branch "simil2.1.12"]
remote = origin
merge = refs/heads/simil2.1.12
rebase = false
and it worked
0.00 is actually 0. If you need to have the 0.00 when you echo, simply use number_format this way:
number_format($number, 2);
Sometimes dict()
is a good choice:
a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))
mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],
[random.randint(0,100) for x in range(0,7)]))
Using pattern and check validate:
var input = '33/15/2000';
var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;
alert(pattern.test(input));
It is simple.
Thats it. Hope this helps.
Check out this plugin:
moment-countdown is a tiny moment.js plugin that integrates with Countdown.js. The file is here.
How it works?
//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'
//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'
//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'
//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'
I had this issue while reloading data in UITableView. Simply dispatching reload as follows fixed the issue for me.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
Try this:
> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
Code Value
1 A 1
2 B 2
1.1 A 1
1.2 A 1
JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.
NamedParameterJDBCTemplate supports named parameters, you can use them like that:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("name", name);
paramSource.addValue("city", city);
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
It is Aug 2011, Xcode 4.1 and it continues to be nightmare. Why not allow Cmd+ and Cmd- like everywhere else. < end rant >
As suggested by other respondents I suggest that you copy your preferred theme before you tweak the fonts for there is no ease way to undo.
In my case, all I wanted to do was increase the font size. Mercifully you can select multiple items (Shift+select or Cmd+select) and set the font for all the ones selected in one fell swoop.
Minor relief for a major irritation.
One more solution to use this Unicode black circle >>
Start >> All Programs >> Accessories >> System Tools >> Character Map
Then select Arial font
and choose the Black circle
copy it and paste it into PasswordChar
property of the textbox.
That's it....
You can try this:
var b = str.match(/[^\x00-\xff]/g);
return (str.length + (!b ? 0: b.length));
It worked for me.
You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.
also see this answer: C++ check if element exists in array
Don't use array_values
on your $row
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, $row);
}
Also, the preferred way to add a value to an array is writing $array[] = $value;
, not using array_push
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC)
but to use mysql_fetch_assoc($result)
directly.
$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
{
$res_arr_values[] = $row;
}