select date_format(date_parse(t.payDate,'%Y-%m-%d %H:%i:%S'),'%Y-%m-%d') as payDate
from testTable t
where t.paydate is not null and t.paydate <> '';
I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.
var shot1=imagify($('#widget')[0], (base64) => {
$('img.screenshot').attr('src', base64);
});
Take a look at htmlshot package , then, check deeply the client side section:
npm install htmlshot
I have found xdocdiff WinMerge Plugin. It is a plugin for WinMerge (both OpenSource and Freeware, you doesn't need to write a VBA nor save an excel to csv or xml). It works just for the celd's contains.
This plugin supports also:
Regard, Andres
"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.
You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.
If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...
Example..
Month varchar2(3) --Month code in Alpha..
Year NUMBER -- Year in number
or
Month number(2) --Month Number in Year.
Year NUMBER -- Year in number
[Required(ErrorMessage = "Please enter Social Email id")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
If storing less then 1 mil records, and high performance is not an issue go for varchar(20)/char(20) otherwise I've found that for storing even 100 milion global business phones or personal phones, int is best. Reason : smaller key -> higher read/write speed, also formatting can allow for duplicates.
1 phone in char(20) = 20 bytes vs 8 bytes bigint
(or 10 vs 4 bytes int
for local phones, up to 9 digits) , less entries can enter the index block => more blocks => more searches, see this for more info (writen for Mysql but it should be true for other Relational Databases).
Here is an example of phone tables:
CREATE TABLE `phoneNrs` (
`internationalTelNr` bigint(20) unsigned NOT NULL COMMENT 'full number, no leading 00 or +, up to 19 digits, E164 format',
`format` varchar(40) NOT NULL COMMENT 'ex: (+NN) NNN NNN NNN, optional',
PRIMARY KEY (`internationalTelNr`)
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
or with processing/splitting before insert (2+2+4+1 = 9 bytes)
CREATE TABLE `phoneNrs` (
`countryPrefix` SMALLINT unsigned NOT NULL COMMENT 'countryCode with no leading 00 or +, up to 4 digits',
`countyPrefix` SMALLINT unsigned NOT NULL COMMENT 'countyCode with no leading 0, could be missing for short number format, up to 4 digits',
`localTelNr` int unsigned NOT NULL COMMENT 'local number, up to 9 digits',
`localLeadingZeros` tinyint unsigned NOT NULL COMMENT 'used to reconstruct leading 0, IF(localLeadingZeros>0;LPAD(localTelNr,localLeadingZeros+LENGTH(localTelNr),'0');localTelNr)',
PRIMARY KEY (`countryPrefix`,`countyPrefix`,`localLeadingZeros`,`localTelNr`) -- ordered for fast inserts
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
;
Also "the phone number is not a number", in my opinion is relative to the type of phone numbers. If we're talking of an internal mobile phoneBook, then strings are fine, as the user may wish to store GSM Hash Codes. If storing E164 phones, bigint is the best option.
Try to use target size you need insted of TRUNCATEONLY in DBCC:
DBCC SHRINKFILE ('Wxlog0', 1)
And check this to articles:
http://msdn.microsoft.com/en-us/library/ms189493(SQL.90).aspx
http://support.microsoft.com/kb/907511
Edit:
You can try to move allocated pages to the beginning of the log file first with
DBCC SHRINKFILE ('Wxlog0', NOTRUNCATE)
and after that
DBCC SHRINKFILE ('Wxlog0', 1)
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.
A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
EDIT: The below answer no longer works see here
If the file you try to recover has Content-Encoding: gzip
in the header section, and you are using linux (or as in my case, you have Cygwin installed) you can do the following:
chrome://view-http-cache/
and click the page you want to recoverxxd -r a.txt| gzip -d
Note that other answers suggest passing -p
option to xxd
- I had troubles with that presumably because the fourth section of the cache is not in the "postscript plain hexdump style" but in a "default style".
It also does not seem necessary to replace double spaces with a single space, as chrome_xxd.py
is doing (in case it is necessary you can use sed 's/ / /g'
for that).
It's a 32-bit signed integer type on most legacy platforms. However, that causes your code to suffer from the year 2038 bug. So modern C libraries should be defining it to be a signed 64-bit int instead, which is safe for a few billion years.
I assume you have different sized images. I tested this myself, and it works as you describe (always centered, images widths appropriately)
/*CSS*/
div.c-wrapper{
width: 80%; /* for example */
margin: auto;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}
<!--html-->
<div class="c-wrapper">
<div id="carousel-example-generic" class="carousel slide">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="http://placehold.it/600x400">
<div class="carousel-caption">
hello
</div>
</div>
<div class="item">
<img src="http://placehold.it/500x400">
<div class="carousel-caption">
hello
</div>
</div>
<div class="item">
<img src="http://placehold.it/700x400">
<div class="carousel-caption">
hello
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="icon-next"></span>
</a>
</div>
</div>
This creates a "jump" due to variable heights... to solve that, try something like this: Select the tallest image of a list
Or use media-query to set your own fixed height.
Add the type for the script
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
So the important part is the type text/javascript.
I know its stupid but in my case i was outside of my project folder i didn't have spark file.
If you're using Google Maps v2, call checkResize()
on your map after resizing the container. link
UPDATE
Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.
This can be more complicated than it looks depending on how you want to count things. For instance, if you have a list of ints, do you want the size of the list containing the references to the ints? (ie. list only, not what is contained in it), or do you want to include the actual data pointed to, in which case you need to deal with duplicate references, and how to prevent double-counting when two objects contain references to the same object.
You may want to take a look at one of the python memory profilers, such as pysizer to see if they meet your needs.
The equivalent of offsetHeight and offsetWidth in jQuery is $(window).width(), $(window).height() It's not the clientHeight and clientWidth
This method is even easier if you're ok with fewer options:
FileCopy source, destination
You have to use Embedded Documents (stringfy the path object)
let update = {}
Object.getOwnPropertyNames(new_info).forEach(param => {
update['some_key.' + param] = new_info[param]
})
And so, in JavaScript you can use Spread Operator (...) to update
db.collection.update( { _id:...} , { $set: { ...update } }
In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});
It might help you to understand.
import * as Rx from 'rxjs';
const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.
const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);
const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.
const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2
You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.
Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.
Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.
Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).
Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.
Do it like this: Remember to close iframe tag.
<iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe>
No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.
This works for me
v.getBackground().setTint(Color.parseColor("#212121"));
That way only changes the color of the background without change the background itself. This is usefull for example if you have a background with rounded corners.
if you need a fallback function you could use this
function session_register($name){
global $$name;
$_SESSION[$name] = $$name;
$$name = &$_SESSION[$name];
}
Force a method to get the struct (the constructor way).
From this post:
A good design is to make your type unexported, but provide an exported constructor function like
NewMyType()
in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.
This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.
Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
Extending from the correct answer of Andrey-Egorov using .executeScript()
to conclude my own question example:
inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);
A binary tree is a tree whose children are never more than two. A binary search tree follows the invariant that the left child should have a smaller value than the root node's key, while the right child should have a greater value than the root node's key.
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
You can use C function gettimeofday : http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html
Here C library 'ul_time', function sec_usec resides in 'time' global table and returns seconds, useconds. Copy DLL to Lua folder, open it with require 'ul_time'.
All the above mentioned answers will almost fullfill the purpose. However, You need to drop the temp table after all the operation on it. You can follow-
INSERT INTO #TempTable (ID, Date, Name) SELECT id, date, name FROM physical_table;
IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULL DROP TABLE #TempTable;
Not sure if I understand well, but maybe you could form the CREATE statement inside a string, then execute that String? That way you could add as many columns as you want.
There's a Windows answer, and a Debian answer, so here's a Mac one:
This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:
os.system( "say beep" )
Disclaimer: You can replace os.system
with a call to the subprocess
module if you're worried about someone hacking on your beep code.
I tried the solutions above and none worked for me out of the box.
However http://www.baeldung.com/httpclient-post-http-request. Line 6 POST Multipart Request worked within seconds
public void whenSendMultipartRequestUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "John");
builder.addTextBody("password", "pass");
builder.addBinaryBody("file", new File("test.txt"),
ContentType.APPLICATION_OCTET_STREAM, "file.ext");
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = client.execute(httpPost);
client.close();
}
Member functions that do not modify the class instance should be declared as const
:
int getId() const {
return id;
}
string getName() const {
return name;
}
Anytime you see "discards qualifiers", it's talking about const
or volatile
.
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
It is very simple to update using join query in SQL .You can do it without using FROM
clause. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
I believe buffer length needs to be specified, as memory is finite and you may run out of it
Example:
InputStream in = new FileInputStream(strFileName);
long length = fileFileName.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + fileFileName.getName());
}
in.close();
In my experience with regex you really need to focus on what EXACTLY you are trying to match, rather than what NOT to match.
for example
\d{2}
[1-9][0-9]
The first expression will match any 2 digits....and the second will match 1 digit from 1 to 9 and 1 digit - any digit. So if you type 07 the first expression will validate it, but the second one will not.
See this for advanced reference:
http://www.regular-expressions.info/refadv.html
EDITED:
^((?!my string).)*$
Is the regular expression for does not contain "my string".
Just go to File -> Settings -> select Project Interpreter under Project tab -> click on the small gear icon -> Add -> System Interpreter -> select the python version you want in the drop down menu
this seemed to work for me
You can do this easily by using the library cryptocode
. Here is how you install:
pip install cryptocode
Encrypting a message (example code):
import cryptocode
encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")
Documentation can be found here
No. Not like you have your code. There isn't any class named Boolean. Now with all the answers you have you should be able to create one and use it. You do know how to create classes don't you? I only came here because I was just wondering this idea myself. Many people might say "Why? You have to just know how Ruby uses Boolean". Which is why you got the answers you did. So thanks for the question. Food for thought. Why doesn't Ruby have a Boolean class?
NameError: uninitialized constant Boolean
Keep in mind that Objects do not have types. They are classes. Objects have data. So that's why when you say data types it's a bit of a misnomer.
Also try rand 2 because rand 1 seems to always give 0. rand 2 will give 1 or 0 click run a few times here. https://repl.it/IOPx/7
Although I wouldn't know how to go about making a Boolean class myself. I've experimented with it but...
class Boolean < TrueClass
self
end
true.is_a?(Boolean) # => false
false.is_a?(Boolean) # => false
At least we have that class now but who knows how to get the right values?
you can also get this if you are trying to hit the same URL with multiple HTTP request at the same time.Many curl requests wont be able to connect and so return with error
Make sure that your project is targeting the .NET framework 4.0. Visual Studio 2010 supports .NET 3.5 framework target also, but .NET 3.5 does not support the dynamic
keyword.
You can adjust the framework version in the project properties. See http://msdn.microsoft.com/en-us/library/bb398202.aspx for more info.
Another feature:
instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml
(according to tomcat docs)
like this:
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
username="dbUsername" password="dbPasswd"
url="jdbc:postgresql://localhost/dbname"
driverClassName="org.postgresql.Driver"
initialSize="5" maxWait="5000"
maxActive="120" maxIdle="5"
validationQuery="select 1"
poolPreparedStatements="true"/>
</Context>
The build context menu has a Cancel build in Visual Studio 2013.
You should override toString()
method in your Dog
class. which will be called when you use this object in sysout.
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
There are some args for the date() function that should help. If you check date("w") it will give you a number for the day of the week, from 0 for Sunday through 6 for Saturday. So.. maybe something like..
$busDays = 3;
$day = date("w");
if( $day > 2 && $day <= 5 ) { /* if between Wed and Fri */
$day += 2; /* add 2 more days for weekend */
}
$day += $busDays;
This is just a rough example of one possibility..
There is an appropriate PHP function: substr_replace($text, $replacement, $start).
For your case, because you already know all the possibilities of the text length (100, 1000 or 10000 words), you can simply use that PHP function like this:
echo substr_replace($your_text, "...", 20);
PHP will automatically return a 20 character only text with ...
.
Se the documentation by clicking here.
If you are simply interested to know whether a registry value is present or not then how about:
[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").PathName)
will return: $true while
[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ValueNotThere)
will return: $false as it's not there ;)
You could adapt it into a scriptblock like:
$CheckForRegValue = { Param([String]$KeyPath, [String]$KeyValue)
return [bool]((Get-itemproperty -Path $KeyPath).$KeyValue) }
and then just call it by:
& $CheckForRegValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" PathName
Have fun,
Porky
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
As far as I know, basic animates can't animate non-numeric CSS properties.
I believe you could get this done using a step function and the appropriate css3 transform for the users browser. CSS3 transform is a bit tricky to cover all your browsers in (IE6 you need to use the Matrix filter, for instance).
EDIT: here's an example that works in webkit browsers (Chrome, Safari): http://jsfiddle.net/ryleyb/ERRmd/
If you wanted to support IE9 only, you could use transform
instead of -webkit-transform
, or -moz-transform
would support FireFox.
The trick used is to animate a CSS property we don't care about (text-indent
) and then use its value in a step function to do the rotation:
$('#foo').animate(
..
step: function(now,fx) {
$(this).css('-webkit-transform','rotate('+now+'deg)');
}
...
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
This was driving me bonkers as the .astype()
solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')
print pd.Timedelta(t2 - t1).seconds / 3600.0
...if you want hours. Or:
print pd.Timedelta(t2 - t1).seconds / 60.0
...if you want minutes.
C++03's categories are too restricted to capture the introduction of rvalue references correctly into expression attributes.
With the introduction of them, it was said that an unnamed rvalue reference evaluates to an rvalue, such that overload resolution would prefer rvalue reference bindings, which would make it select move constructors over copy constructors. But it was found that this causes problems all around, for example with Dynamic Types and with qualifications.
To show this, consider
int const&& f();
int main() {
int &&i = f(); // disgusting!
}
On pre-xvalue drafts, this was allowed, because in C++03, rvalues of non-class types are never cv-qualified. But it is intended that const
applies in the rvalue-reference case, because here we do refer to objects (= memory!), and dropping const from non-class rvalues is mainly for the reason that there is no object around.
The issue for dynamic types is of similar nature. In C++03, rvalues of class type have a known dynamic type - it's the static type of that expression. Because to have it another way, you need references or dereferences, which evaluate to an lvalue. That isn't true with unnamed rvalue references, yet they can show polymorphic behavior. So to solve it,
unnamed rvalue references become xvalues. They can be qualified and potentially have their dynamic type different. They do, like intended, prefer rvalue references during overloading, and won't bind to non-const lvalue references.
What previously was an rvalue (literals, objects created by casts to non-reference types) now becomes an prvalue. They have the same preference as xvalues during overloading.
What previously was an lvalue stays an lvalue.
And two groupings are done to capture those that can be qualified and can have different dynamic types (glvalues) and those where overloading prefers rvalue reference binding (rvalues).
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j;
int b=0;
for (i=2;i<=100;i++){
for (j=2;j<=i;j++){
if (i%j==0){
break;
}
}
if (i==j)
print f("\n%d",j);
}
getch ();
}
new {var_data[counter] =new [] {
new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
}
};
Check existing row with Any.
public static void insertOrUpdateCustomer(Customer customer)
{
using (var db = getDb())
{
db.Entry(customer).State = !db.Customer.Any(f => f.CustomerId == customer.CustomerId) ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
}
}
Setting setOnClickListener(null)
is a good idea to remove click listener at runtime.
And also someone commented that calling View.hasOnClickListeners()
after this will return true
, NO my friend.
Here is the implementation of hasOnClickListeners()
taken from android.view.View
class
public boolean hasOnClickListeners() {
ListenerInfo li = mListenerInfo;
return (li != null && li.mOnClickListener != null);
}
Thank GOD. It checks for null
.
So everything is safe. Enjoy :-)
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
You can define a callback as an attribute of your XML layout. The article Custom XML Attributes For Your Custom Android Widgets will show you how to do it for a custom widget. Credit goes to Kevin Dion :)
I'm investigating whether I can add styleable attributes to the base Fragment class.
The basic idea is to have the same functionality that View implements when dealing with the onClick callback.
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
if it is showing error 2003 (HY000): Can't connect to MySQL server on localhost (10061) than
I know this is an older question, but I wanted to present yet another way which is the appassembler-maven-plugin. Here's the relevant part from my POM that includes a lot of additional option values we found useful:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<configuration>
<generateRepository>true</generateRepository>
<repositoryLayout>flat</repositoryLayout>
<useWildcardClassPath>true</useWildcardClassPath>
<includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
<configurationDirectory>config</configurationDirectory>
<target>${project.build.directory}</target>
<daemons>
<daemon>
<id>${installer-target}</id>
<mainClass>${mainClass}</mainClass>
<commandLineArguments>
<commandLineArgument>--spring.profiles.active=dev</commandLineArgument>
<commandLineArgument>--logging.config=${rpmInstallLocation}/config/${installer-target}-logback.xml</commandLineArgument>
</commandLineArguments>
<platforms>
<platform>jsw</platform>
</platforms>
<generatorConfigurations>
<generatorConfiguration>
<generator>jsw</generator>
<includes>
<include>linux-x86-64</include>
</includes>
<configuration>
<property>
<name>wrapper.logfile</name>
<value>logs/${installer-target}-wrapper.log</value>
</property>
<property>
<name>wrapper.logfile.maxsize</name>
<value>5m</value>
</property>
<property>
<name>run.as.user.envvar</name>
<value>${serviceUser}</value>
</property>
<property>
<name>wrapper.on_exit.default</name>
<value>RESTART</value>
</property>
</configuration>
</generatorConfiguration>
</generatorConfigurations>
<jvmSettings>
<initialMemorySize>256M</initialMemorySize>
<maxMemorySize>1024M</maxMemorySize>
<extraArguments>
<extraArgument>-server</extraArgument>
</extraArguments>
</jvmSettings>
</daemon>
</daemons>
</configuration>
<executions>
<execution>
<id>generate-jsw-scripts</id>
<phase>package</phase>
<goals>
<goal>generate-daemons</goal>
</goals>
</execution>
</executions>
</plugin>
If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.
My solution: use to_dict()
dict_of_lists = df.to_dict(orient='split')
This will give you a dictionary with three lists: index
, columns
, data
. If you decide you really don't need the columns and index names, you get the data with
dict_of_lists['data']
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
I was facing the same issue. I realised that I was using the Wrong provider class in persistence.xml
For Hibernate it should be
<provider>org.hibernate.ejb.HibernatePersistence</provider>
And for EclipseLink it should be
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
might be surprised to know.. its PHP. read all about it here
You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.
System.out.printf("%2d. %-20s $%.2f%n", i + 1, BOOK_TYPE[i], COST[i]);
Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.
import 'rxjs/add/observable/of';
shows a requirement of rxjs-compat
require("rxjs-compat/add/observable/of");
I did not have this installed. Installed by
npm install rxjs-compat --save-dev
and rerunning fixed my issue.
I just wanted to say thank you to the topmost first post by a user whom I think is named "coobird". I am new to this stackoverflow.com web site, but I cant believe how useful and helpful this community is...so thanks to all of you for posting some great tips and advise to others. Thats what a community is all about.
Now coobird correctly said:
As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea in a JScrollPane. This will allow scrolling of the view area of the JTextArea.
I would like to say:
The above statement is absolutely true. In fact, I had been struggling with this in Eclipse using the WindowBuilder Pro plugin because I could not figure out what combination of widgets would help me achieve that. However, thanks to the post by coobird, I was able to resolve this frustration which took me days.
I would also like to add that I am relatively new to Java even though I have a solid foundation in the principles. The code snippets and advise you guys give here are tremendously useful.
I just want to add one other tid-bit that may help others. I noticed that Coobird put some code as follows (in order to show how to create a Scrollable text area). He wrote:
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
I would like to say thanks to the above code snippet from coobird. I have not tried it directly like that but I am sure it would work just fine. However, it may be useful to some to let you know that when I did this using the WindowBuilder Pro tool, I got something more like the following (which I think is just a slightly longer more "indirect" way for WindowBuilder to achieve what you see in the two lines above. My code kinda reads like this:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(23, 40, 394, 191);
frame.getContentPane().add(scrollPane);
JTextArea textArea_1 = new JTextArea();
scrollPane.setViewportView(textArea_1);`
Notice that WindowBuilder basically creates a JScrollPane called scrollpane (in the first three lines of code)...then it sets the viewportview by the following line: scrollPane.setViewportView(textArea_1). So in essence, this line is adding the textArea_1 in my code (which is obviously a JTextArea) to be added to my JScrollPane **which is precisely what coobird was talking about).
Hope this is helpful because I did not want the WindowBuilder Pro developers to get confused thinking that Coobird's advise was not correct or something.
Best Wishes to all and happy coding :)
Typically async method returns Task class. If you use Wait()
method or Result
property and code throws exception - exception type gets wrapped up into AggregateException
- then you need to query Exception.InnerException
to locate correct exception.
But it's also possible to use .GetAwaiter().GetResult()
instead -
it will also wait async task, but will not wrap exception.
So here is short example:
public async Task MyMethodAsync()
{
}
public string GetStringData()
{
MyMethodAsync().GetAwaiter().GetResult();
return "test";
}
You might want also to be able to return some parameter from async function - that can be achieved by providing extra Action<return type>
into async function, for example like this:
public string GetStringData()
{
return MyMethodWithReturnParameterAsync().GetAwaiter().GetResult();
}
public async Task<String> MyMethodWithReturnParameterAsync()
{
return "test";
}
Please note that async methods typically have ASync
suffix naming, just to be able to avoid collision between sync functions with same name. (E.g. FileStream.ReadAsync
) - I have updated function names to follow this recommendation.
Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
In case anybody stumbles upon this question who cannot reload their webserver (long running console command like a queue runner) or needs to reload their .env file mid-request, i found a way to properly reload .env variables in laravel 5.
use Dotenv;
use InvalidArgumentException;
try {
Dotenv::makeMutable();
Dotenv::load(app()->environmentPath(), app()->environmentFile());
Dotenv::makeImmutable();
} catch (InvalidArgumentException $e) {
//
}
RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php%{QUERY_STRING} [L]
Put these two lines at the top of your .htaccess file. It will show .html in the URL for your .php pages.
RewriteEngine on
RewriteRule ^(.*)\.php$ $1.html%{QUERY_STRING} [L]
Use this for showing .php in URL for your .html pages.
You can find the latest windows version of flex & bison here: http://sourceforge.net/projects/winflexbison/
Every time you create an ajax request you could use a variable to store it:
var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){}
});
Then you can abort the request:
request.abort();
You could use an array keeping track of all pending ajax requests and abort them if necessary.
You should be using
git stash save
and not
git stash create
because this creates a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. Hence won't be accessible with stash apply.
Use git stash save "some comment"
is used when you have unstaged changes you wanna replicate/move onto another branch
Use git stash apply stash@{0}
(assuming your saved stash index is 0) when you want your saved(stashed) changes to reflect on your current branch
you can always use git stash list
to check all you stash indexes
and use git stash drop stash@{0}
(assuming your saved stash index is 0 and you wanna delete it) to delete a particular stash.
Have read the documentation you've linked. That's totally silly! xclip
is just a clipboard. You'll find other ways to copy paste the key... (I'm sure)
If you aren't working from inside a graphical X session you need to pass the $DISPLAY
environment var to the command. Run it like this:
DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub
Of course :0
depends on the display you are using. If you have a typical desktop machine it is likely that it is :0
here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
Basic JavaScript:
if (document.getElementById("elementId").style.display == 'block') {
alert('this Element is block');
}
It's not supported just yet... If you want to use it you will have to install Babel.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
I think the bulletproof way is:
if (typeof $.cookie('token') === 'undefined'){
//no cookie
} else {
//have cookie
}
Checking the type of a null, empty or undefined var always returns 'undefined'
Edit: You can get there even easier:
if (!!$.cookie('token')) {
// have cookie
} else {
// no cookie
}
!!
will turn the falsy values to false. Bear in mind that this will turn 0
to false!
I think you can use this
Bitmap bmImg = BitmapFactory.decodeFile("path of your img1");
imageView.setImageBitmap(bmImg);
function prettyJSON(obj) {
console.log(JSON.stringify(obj, null, 2));
}
// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level
Most simple way is to use boost::lexical_cast:
double value;
try
{
value = boost::lexical_cast<double>(my_string);
}
catch (boost::bad_lexical_cast const&)
{
value = 0;
}
If you want to set Min 1 count and no Max length,
^.{1,}$
try
{
$tableAresults = $dbHandler->doSomethingWithTableA();
if(!tableAresults)
{
throw new Exception('Problem with tableAresults');
}
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if(!tableBresults)
{
throw new Exception('Problem with tableBresults');
}
} catch (Exception $e)
{
echo $e->getMessage();
}
Look at the WAITFOR command.
E.g.
-- wait for 1 minute
WAITFOR DELAY '00:01'
-- wait for 1 second
WAITFOR DELAY '00:00:01'
This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001'
is likely to result in no wait at all.
You cal also do this
SELECT SUM(amnt) `value`,DATE_FORMAT(dtrg,'%m-%y') AS label FROM rentpay GROUP BY YEAR(dtrg) DESC, MONTH(dtrg) DESC LIMIT 12
to order by year and month. Lets say you want to order from this year and this month all the way back to 12 month
First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).
You just have to put your const outside your class declaration.
Two possibilities : Declare your const in your class file (your const have a clear relation with your class)
private const val CONST_USED_BY_MY_CLASS = 1
class MyClass {
// I can use my const in my class body
}
Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :
package com.project.constants
const val URL_PATH = "https:/"
Then you just have to import it where you need it :
import com.project.constants
MyClass {
private fun foo() {
val url = URL_PATH
System.out.print(url) // https://
}
}
This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :
MyClass {
companion object {
private const val URL_PATH = "https://"
const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
}
}
Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :
MyClass {
companion object {
val URL_PATH = "https://"
}
}
In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.
@JvmField val foo = Foo()
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
MAMP if you are on a MAC MAMP
You can set the IP while running it.
docker run --cap-add=NET_ADMIN -dit imagename /bin/sh -c "/sbin/ip addr add 172.17.0.12 dev eth0; bash"
See my example at https://github.com/RvdGijp/mariadb-10.1-galera
The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.
If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.
Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.
One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.
Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.
No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug
and app\release
folders.
I had the same problem, I had the package and class named the same. I renamed the class, then clean and build. Then I set the main class in the "run" under the properties of the project. I works now.
I think this works, at least partially (have not investigated):
nvm uninstall <VERSION_TO_UNINSTALL>
eg:
nvm uninstall 4.4.5
Here's a way!
<?php
$url = "http://www.google.com";
if(@file_get_contents($url)){
echo "Url Exists!";
} else {
echo "Url Doesn't Exist!";
}
?>
This simple script simply makes a request to the URL for its source code. If the request is completed successfully, it will output "URL Exists!". If not, it will output "URL Doesn't Exist!".
We can use the rank() window function (where you would choose the rank = 1) rank just adds a number for every row of a group (in this case it would be the hour)
here's an example. ( from https://github.com/jaceklaskowski/mastering-apache-spark-book/blob/master/spark-sql-functions.adoc#rank )
val dataset = spark.range(9).withColumn("bucket", 'id % 3)
import org.apache.spark.sql.expressions.Window
val byBucket = Window.partitionBy('bucket).orderBy('id)
scala> dataset.withColumn("rank", rank over byBucket).show
+---+------+----+
| id|bucket|rank|
+---+------+----+
| 0| 0| 1|
| 3| 0| 2|
| 6| 0| 3|
| 1| 1| 1|
| 4| 1| 2|
| 7| 1| 3|
| 2| 2| 1|
| 5| 2| 2|
| 8| 2| 3|
+---+------+----+
For a typical XAMPP install on windows you probably have the php_sockets.dll in your C:\xampp\php\ext directory. All you got to do is go to php.ini in the C:\xampp\php directory and change the ;extension=php_sockets.dll
to extension=php_sockets.dll
.
Solution from proxy side, I faced some problems in the SSL handshake process and I had to force my proxy server to send requests using HTTP/1.0 to solve the problem by setting this argument in the httpd.conf SetEnv force-proxy-request-1.0 1
SetEnv proxy-nokeepalive 1
after that I faced the 417 error as my clients application was using HTTP/1.1 and the proxy was forced to use HTTP/1.0, the problem was solved by setting this parameter in the httpd.conf on the proxy side RequestHeader unset Expect early
without the need to change anything in the client side, hope this helps.
xcopy /y /d "$(ProjectDir)External\*.dll" "$(TargetDir)"
You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.
xcopy /y /d "$(ProjectDir)..\External\*.dll" "$(TargetDir)"
The /y
option copies without confirmation.
The /d
option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.
I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir)
is undefined and had to use $(ProjectDir)
instead.
Leaving out a target folder in xcopy
should default to the output directory. That is important to understand reason $(OutDir)
alone is not helpful.
$(OutDir)
, at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug
. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug
.
Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir)
.
However $(TargetDir)
will provide the output directory in one step.
Microsoft's list of MSBuild macros for current and previous versions of Visual Studio
show all apps heroku have access with
heroku apps
And check you app exist then
execute heroku git:remote -a yourapp_exist
My problem was a missing translation. I had a settings.xml that was not translated as it was not needed, so I had to add "translatable="false" to the strings:
This string doesn't need translation
For the noobs out there who find this stuff fun and interesting, the fastest way to read an entire file into a string in most cases (according to these benchmarks) is by the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = sr.ReadToEnd();
}
//you then have to process the string
However, the absolute fastest to read a text file overall appears to be the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do what you have to here
}
}
Put up against several other techniques, it won out most of the time, including against the BufferedReader.
To extend @ChrisG's idea, a little, consider using process.MainWindowHandle and seeing if the window message loop is responding. Use p/invoke this Win32 api: SendMessageTimeout. From that link:
If the function succeeds, the return value is nonzero. SendMessageTimeout does not provide information about individual windows timing out if HWND_BROADCAST is used.
If the function fails or times out, the return value is 0. To get extended error information, call GetLastError. If GetLastError returns ERROR_TIMEOUT, then the function timed out.
Need to include jquery-ui too:
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.
See AES in ASP.NET with VB.NET for more information about encryption in .NET.
Loading the values in an array would be much faster:
Dim data(), dict As Object, r As Long
Set dict = CreateObject("Scripting.Dictionary")
data = ActiveSheet.UsedRange.Columns(1).Value
For r = 1 To UBound(data)
dict(data(r, some_column_number)) = Empty
Next
data = WorksheetFunction.Transpose(dict.keys())
You should also consider early binding for the Scripting.Dictionary:
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
Note that using a dictionary is way faster than Range.AdvancedFilter on large data sets.
As a bonus, here's a procedure similare to Range.RemoveDuplicates to remove duplicates from a 2D array:
Public Sub RemoveDuplicates(data, ParamArray columns())
Dim ret(), indexes(), ids(), r As Long, c As Long
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
If VarType(data) And vbArray Then Else Err.Raise 5, , "Argument data is not an array"
ReDim ids(LBound(columns) To UBound(columns))
For r = LBound(data) To UBound(data) ' each row '
For c = LBound(columns) To UBound(columns) ' each column '
ids(c) = data(r, columns(c)) ' build id for the row
Next
dict(Join$(ids, ChrW(-1))) = r ' associate the row index to the id '
Next
indexes = dict.Items()
ReDim ret(LBound(data) To LBound(data) + dict.Count - 1, LBound(data, 2) To UBound(data, 2))
For c = LBound(ret, 2) To UBound(ret, 2) ' each column '
For r = LBound(ret) To UBound(ret) ' each row / unique id '
ret(r, c) = data(indexes(r - 1), c) ' copy the value at index '
Next
Next
data = ret
End Sub
The following revision seeks to more clearly delineate PHP's array_filer(), array_map(), and array_walk(), all of which originate from functional programming:
array_filter() filters out data, producing as a result a new array holding only the desired items of the former array, as follows:
<?php
$array = array(1, "apples",2, "oranges",3, "plums");
$filtered = array_filter( $array, "ctype_alpha");
var_dump($filtered);
?>
live code here
All numeric values are filtered out of $array, leaving $filtered with only types of fruit.
array_map() also creates a new array but unlike array_filter() the resulting array contains every element of the input $filtered but with altered values, owing to applying a callback to each element, as follows:
<?php
$nu = array_map( "strtoupper", $filtered);
var_dump($nu);
?>
live code here
The code in this case applies a callback using the built-in strtoupper() but a user-defined function is another viable option, too. The callback applies to every item of $filtered and thereby engenders $nu whose elements contain uppercase values.
In the next snippet, array walk() traverses $nu and makes changes to each element vis a vis the reference operator '&'. The changes occur without creating an additional array. Every element's value changes in place into a more informative string specifying its key, category and value.
<?php
$f = function(&$item,$key,$prefix) {
$item = "$key: $prefix: $item";
};
array_walk($nu, $f,"fruit");
var_dump($nu);
?>
See demo
Note: the callback function with respect to array_walk() takes two parameters which will automatically acquire an element's value and its key and in that order, too when invoked by array_walk(). (See more here).
Go to your mysql bin directory and install mysql service again:
c:
cd \mysql\bin
mysqld-nt.exe --install
or if mysqld-nt.exe is missing (depending on version):
mysqld.exe --install
Then go to services, start the service and set it to automatic start.
FIDDLE: https://jsfiddle.net/1ytxfcwx/
NPM: https://www.npmjs.com/package/typescript-string-operations
GITHUB: https://github.com/sevensc/typescript-string-operations
I implemented a class for String. Its not perfect but it works for me.
use it i.e. like this:
var getFullName = function(salutation, lastname, firstname) {
return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}
export class String {
public static Empty: string = "";
public static isNullOrWhiteSpace(value: string): boolean {
try {
if (value == null || value == 'undefined')
return false;
return value.replace(/\s/g, '').length < 1;
}
catch (e) {
return false;
}
}
public static Format(value, ...args): string {
try {
return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
var s = match.split(':');
if (s.length > 1) {
i = i[0];
match = s[1].replace('}', '');
}
var arg = String.formatPattern(match, args[i]);
return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
});
}
catch (e) {
return String.Empty;
}
}
private static formatPattern(match, arg): string {
switch (match) {
case 'L':
arg = arg.toLowerCase();
break;
case 'U':
arg = arg.toUpperCase();
break;
default:
break;
}
return arg;
}
}
EDIT:
I extended the class and created a repository on github. It would be great if you can help to improve it!
https://github.com/sevensc/typescript-string-operations
or download the npm package
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
You can use below query to update or create comment on already created table.
SYNTAX:
COMMENT ON COLUMN TableName.ColumnName IS 'comment text';
Example:
COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';
It seems to me that this implementation works in more cases (generic class and interface with or without initiated parameters, regardless of the number of child and parameters):
public static class ReflexionExtension
{
public static bool IsSubClassOfGeneric(this Type child, Type parent)
{
if (child == parent)
return false;
if (child.IsSubclassOf(parent))
return true;
var parameters = parent.GetGenericArguments();
var isParameterLessGeneric = !(parameters != null && parameters.Length > 0 &&
((parameters[0].Attributes & TypeAttributes.BeforeFieldInit) == TypeAttributes.BeforeFieldInit));
while (child != null && child != typeof(object))
{
var cur = GetFullTypeDefinition(child);
if (parent == cur || (isParameterLessGeneric && cur.GetInterfaces().Select(i => GetFullTypeDefinition(i)).Contains(GetFullTypeDefinition(parent))))
return true;
else if (!isParameterLessGeneric)
if (GetFullTypeDefinition(parent) == cur && !cur.IsInterface)
{
if (VerifyGenericArguments(GetFullTypeDefinition(parent), cur))
if (VerifyGenericArguments(parent, child))
return true;
}
else
foreach (var item in child.GetInterfaces().Where(i => GetFullTypeDefinition(parent) == GetFullTypeDefinition(i)))
if (VerifyGenericArguments(parent, item))
return true;
child = child.BaseType;
}
return false;
}
private static Type GetFullTypeDefinition(Type type)
{
return type.IsGenericType ? type.GetGenericTypeDefinition() : type;
}
private static bool VerifyGenericArguments(Type parent, Type child)
{
Type[] childArguments = child.GetGenericArguments();
Type[] parentArguments = parent.GetGenericArguments();
if (childArguments.Length == parentArguments.Length)
for (int i = 0; i < childArguments.Length; i++)
if (childArguments[i].Assembly != parentArguments[i].Assembly || childArguments[i].Name != parentArguments[i].Name || childArguments[i].Namespace != parentArguments[i].Namespace)
if (!childArguments[i].IsSubclassOf(parentArguments[i]))
return false;
return true;
}
}
Here are my 70 76 test cases:
[TestMethod]
public void IsSubClassOfGenericTest()
{
Assert.IsTrue(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(BaseGeneric<>)), " 1");
Assert.IsFalse(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(WrongBaseGeneric<>)), " 2");
Assert.IsTrue(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), " 3");
Assert.IsFalse(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(IWrongBaseGeneric<>)), " 4");
Assert.IsTrue(typeof(IChildGeneric).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), " 5");
Assert.IsFalse(typeof(IWrongBaseGeneric<>).IsSubClassOfGeneric(typeof(ChildGeneric2<>)), " 6");
Assert.IsTrue(typeof(ChildGeneric2<>).IsSubClassOfGeneric(typeof(BaseGeneric<>)), " 7");
Assert.IsTrue(typeof(ChildGeneric2<Class1>).IsSubClassOfGeneric(typeof(BaseGeneric<>)), " 8");
Assert.IsTrue(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(BaseGeneric<Class1>)), " 9");
Assert.IsFalse(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(WrongBaseGeneric<Class1>)), "10");
Assert.IsTrue(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "11");
Assert.IsFalse(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(IWrongBaseGeneric<Class1>)), "12");
Assert.IsTrue(typeof(IChildGeneric).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "13");
Assert.IsFalse(typeof(BaseGeneric<Class1>).IsSubClassOfGeneric(typeof(ChildGeneric2<Class1>)), "14");
Assert.IsTrue(typeof(ChildGeneric2<Class1>).IsSubClassOfGeneric(typeof(BaseGeneric<Class1>)), "15");
Assert.IsFalse(typeof(ChildGeneric).IsSubClassOfGeneric(typeof(ChildGeneric)), "16");
Assert.IsFalse(typeof(IChildGeneric).IsSubClassOfGeneric(typeof(IChildGeneric)), "17");
Assert.IsFalse(typeof(IBaseGeneric<>).IsSubClassOfGeneric(typeof(IChildGeneric2<>)), "18");
Assert.IsTrue(typeof(IChildGeneric2<>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "19");
Assert.IsTrue(typeof(IChildGeneric2<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "20");
Assert.IsFalse(typeof(IBaseGeneric<Class1>).IsSubClassOfGeneric(typeof(IChildGeneric2<Class1>)), "21");
Assert.IsTrue(typeof(IChildGeneric2<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "22");
Assert.IsFalse(typeof(IBaseGeneric<Class1>).IsSubClassOfGeneric(typeof(BaseGeneric<Class1>)), "23");
Assert.IsTrue(typeof(BaseGeneric<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "24");
Assert.IsFalse(typeof(IBaseGeneric<>).IsSubClassOfGeneric(typeof(BaseGeneric<>)), "25");
Assert.IsTrue(typeof(BaseGeneric<>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "26");
Assert.IsTrue(typeof(BaseGeneric<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "27");
Assert.IsFalse(typeof(IBaseGeneric<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "28");
Assert.IsTrue(typeof(BaseGeneric2<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<Class1>)), "29");
Assert.IsFalse(typeof(IBaseGeneric<>).IsSubClassOfGeneric(typeof(BaseGeneric2<>)), "30");
Assert.IsTrue(typeof(BaseGeneric2<>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "31");
Assert.IsTrue(typeof(BaseGeneric2<Class1>).IsSubClassOfGeneric(typeof(IBaseGeneric<>)), "32");
Assert.IsTrue(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(BaseGenericA<,>)), "33");
Assert.IsFalse(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(WrongBaseGenericA<,>)), "34");
Assert.IsTrue(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "35");
Assert.IsFalse(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(IWrongBaseGenericA<,>)), "36");
Assert.IsTrue(typeof(IChildGenericA).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "37");
Assert.IsFalse(typeof(IWrongBaseGenericA<,>).IsSubClassOfGeneric(typeof(ChildGenericA2<,>)), "38");
Assert.IsTrue(typeof(ChildGenericA2<,>).IsSubClassOfGeneric(typeof(BaseGenericA<,>)), "39");
Assert.IsTrue(typeof(ChildGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(BaseGenericA<,>)), "40");
Assert.IsTrue(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(BaseGenericA<ClassA, ClassB>)), "41");
Assert.IsFalse(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(WrongBaseGenericA<ClassA, ClassB>)), "42");
Assert.IsTrue(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "43");
Assert.IsFalse(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(IWrongBaseGenericA<ClassA, ClassB>)), "44");
Assert.IsTrue(typeof(IChildGenericA).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "45");
Assert.IsFalse(typeof(BaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(ChildGenericA2<ClassA, ClassB>)), "46");
Assert.IsTrue(typeof(ChildGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(BaseGenericA<ClassA, ClassB>)), "47");
Assert.IsFalse(typeof(ChildGenericA).IsSubClassOfGeneric(typeof(ChildGenericA)), "48");
Assert.IsFalse(typeof(IChildGenericA).IsSubClassOfGeneric(typeof(IChildGenericA)), "49");
Assert.IsFalse(typeof(IBaseGenericA<,>).IsSubClassOfGeneric(typeof(IChildGenericA2<,>)), "50");
Assert.IsTrue(typeof(IChildGenericA2<,>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "51");
Assert.IsTrue(typeof(IChildGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "52");
Assert.IsFalse(typeof(IBaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IChildGenericA2<ClassA, ClassB>)), "53");
Assert.IsTrue(typeof(IChildGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "54");
Assert.IsFalse(typeof(IBaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(BaseGenericA<ClassA, ClassB>)), "55");
Assert.IsTrue(typeof(BaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "56");
Assert.IsFalse(typeof(IBaseGenericA<,>).IsSubClassOfGeneric(typeof(BaseGenericA<,>)), "57");
Assert.IsTrue(typeof(BaseGenericA<,>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "58");
Assert.IsTrue(typeof(BaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "59");
Assert.IsFalse(typeof(IBaseGenericA<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "60");
Assert.IsTrue(typeof(BaseGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "61");
Assert.IsFalse(typeof(IBaseGenericA<,>).IsSubClassOfGeneric(typeof(BaseGenericA2<,>)), "62");
Assert.IsTrue(typeof(BaseGenericA2<,>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "63");
Assert.IsTrue(typeof(BaseGenericA2<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericA<,>)), "64");
Assert.IsFalse(typeof(BaseGenericA2<ClassB, ClassA>).IsSubClassOfGeneric(typeof(IBaseGenericA<ClassA, ClassB>)), "65");
Assert.IsFalse(typeof(BaseGenericA<ClassB, ClassA>).IsSubClassOfGeneric(typeof(ChildGenericA2<ClassA, ClassB>)), "66");
Assert.IsFalse(typeof(BaseGenericA2<ClassB, ClassA>).IsSubClassOfGeneric(typeof(BaseGenericA<ClassA, ClassB>)), "67");
Assert.IsTrue(typeof(ChildGenericA3<ClassA, ClassB>).IsSubClassOfGeneric(typeof(BaseGenericB<ClassA, ClassB, ClassC>)), "68");
Assert.IsTrue(typeof(ChildGenericA4<ClassA, ClassB>).IsSubClassOfGeneric(typeof(IBaseGenericB<ClassA, ClassB, ClassC>)), "69");
Assert.IsFalse(typeof(ChildGenericA3<ClassB, ClassA>).IsSubClassOfGeneric(typeof(BaseGenericB<ClassA, ClassB, ClassC>)), "68-2");
Assert.IsTrue(typeof(ChildGenericA3<ClassA, ClassB2>).IsSubClassOfGeneric(typeof(BaseGenericB<ClassA, ClassB, ClassC>)), "68-3");
Assert.IsFalse(typeof(ChildGenericA3<ClassB2, ClassA>).IsSubClassOfGeneric(typeof(BaseGenericB<ClassA, ClassB, ClassC>)), "68-4");
Assert.IsFalse(typeof(ChildGenericA4<ClassB, ClassA>).IsSubClassOfGeneric(typeof(IBaseGenericB<ClassA, ClassB, ClassC>)), "69-2");
Assert.IsTrue(typeof(ChildGenericA4<ClassA, ClassB2>).IsSubClassOfGeneric(typeof(IBaseGenericB<ClassA, ClassB, ClassC>)), "69-3");
Assert.IsFalse(typeof(ChildGenericA4<ClassB2, ClassA>).IsSubClassOfGeneric(typeof(IBaseGenericB<ClassA, ClassB, ClassC>)), "69-4");
Assert.IsFalse(typeof(bool).IsSubClassOfGeneric(typeof(IBaseGenericB<ClassA, ClassB, ClassC>)), "70");
}
Classes and interfaces for testing :
public class Class1 { }
public class BaseGeneric<T> : IBaseGeneric<T> { }
public class BaseGeneric2<T> : IBaseGeneric<T>, IInterfaceBidon { }
public interface IBaseGeneric<T> { }
public class ChildGeneric : BaseGeneric<Class1> { }
public interface IChildGeneric : IBaseGeneric<Class1> { }
public class ChildGeneric2<Class1> : BaseGeneric<Class1> { }
public interface IChildGeneric2<Class1> : IBaseGeneric<Class1> { }
public class WrongBaseGeneric<T> { }
public interface IWrongBaseGeneric<T> { }
public interface IInterfaceBidon { }
public class ClassA { }
public class ClassB { }
public class ClassC { }
public class ClassB2 : ClassB { }
public class BaseGenericA<T, U> : IBaseGenericA<T, U> { }
public class BaseGenericB<T, U, V> { }
public interface IBaseGenericB<ClassA, ClassB, ClassC> { }
public class BaseGenericA2<T, U> : IBaseGenericA<T, U>, IInterfaceBidonA { }
public interface IBaseGenericA<T, U> { }
public class ChildGenericA : BaseGenericA<ClassA, ClassB> { }
public interface IChildGenericA : IBaseGenericA<ClassA, ClassB> { }
public class ChildGenericA2<ClassA, ClassB> : BaseGenericA<ClassA, ClassB> { }
public class ChildGenericA3<ClassA, ClassB> : BaseGenericB<ClassA, ClassB, ClassC> { }
public class ChildGenericA4<ClassA, ClassB> : IBaseGenericB<ClassA, ClassB, ClassC> { }
public interface IChildGenericA2<ClassA, ClassB> : IBaseGenericA<ClassA, ClassB> { }
public class WrongBaseGenericA<T, U> { }
public interface IWrongBaseGenericA<T, U> { }
public interface IInterfaceBidonA { }
The solution for those who use composer is to use a volume pointing to the parent folder:
#docker-composer.yml
foo:
build: foo
volumes:
- ./:/src/:ro
But I'm pretty sure the can be done playing with volumes in Dockerfile.
You can apply multiple conditions in xpath using and, or
//input[@class='_2zrpKA _1dBPDZ' and @type='text']
//input[@class='_2zrpKA _1dBPDZ' or @type='text']
If it´s in the global scope it´s better to use:
function foo()
{
alert('foo');
}
var a = 'foo';
window[a]();
than eval()
. Because eval()
is evaaaaaal.
Exactly like Nosredna said 40 seconds before me that is >.<
Assuming you already have a JFrame to call this from:
JOptionPane.showMessageDialog(frame, "thank you for using java");
I want to get the ASCII value of characters in a string in C#.
Everyone confer answer in this structure. If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
but in console we work frankness so we get a char and print the ASCII code if i wrong so please correct my answer.
static void Main(string[] args)
{
Console.WriteLine(Console.Read());
Convert.ToInt16(Console.Read());
Console.ReadKey();
}
I had the same problem as Marko and come across a solution like this:
/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS
/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal
/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
SELECT oi.Quantity * p.Price AS columnGrandTotal
FROM OrderItem oi
JOIN Product p ON oi.Id = p.Id
/*And return the sum of columnGrandTotal from the newly created table*/
SELECT SUM(columnGrandTotal) as [Grand Total]
FROM tableGrandTotal
And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)
EXEC GetGrandTotal
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
git push origin amd_qlp_tester
will work for you. If you just type git push
, then the remote of the current branch is the default value.
Syntax of push looks like this - git push <remote> <branch>
. If you look at your remote in .git/config
file, you will see an entry [remote "origin"]
which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.
As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);
GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.
I had the same issue after an upgrade from VS2013 to VS2015.
The project I was working at referenced itself. While VS2013 didn't care, VS2015 didn't like that and I got that error. After deleting the reference, the error was gone. It took me around 4 hours to find that out...
I can also propose following solution for C++11.
for (auto p = 0U; p < sys.size(); p++) {
}
(C++ is not smart enough for auto p = 0, so I have to put p = 0U....)
Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.
Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct
for data-only items and class
for objects with methods, even though you can legally put methods on a struct
; my habit is similar in Python, with dict
and tuple
in place of struct
.
For coordinate sets, I'll use a tuple
rather than a point class
or a dict
(and note that you can use a tuple
as a dictionary key, so dict
s make great sparse multidimensional arrays).
If I'm going to be iterating over a list of things, I prefer unpacking tuple
s on the iteration:
for score,id,name in scoreAllTheThings():
if score > goodScoreThreshold:
print "%6.3f #%6d %s"%(score,id,name)
...as the object version is more cluttered to read:
for entry in scoreAllTheThings():
if entry.score > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)
...let alone the dict
.
for entry in scoreAllTheThings():
if entry['score'] > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])
If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.
Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict
because that's best suited to JSON serialization.
You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"
Use a tool like iBatis Migrations (manual, short tutorial video) which allows you to version control the changes you make to a database throughout the lifecycle of a project, rather than the database itself.
This allows you to selectively apply individual changes to different environments, keep a changelog of which changes are in which environments, create scripts to apply changes A through N, rollback changes, etc.
I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...
), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).
Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...
). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.
Here are several approaches that will work:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
Then one of the following:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
DataFrame
conveniently expands a single row to match the index, so you can do this:df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
join
instead of concat
(may be less efficient):df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
with multiple column arguments.I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols) # add empty cols
df[new_cols] = new_vals # multi-column assignment works for existing cols
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame
You can use \D
which means non digits.
var removedText = self.val().replace(/\D+/g, '');
You could also use the HTML5 number input.
<input type="number" name="digit" />
If you are using vs 2010 then you can get it in
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools
Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:
public class Graph extends JFrame {
JPanel jp;
public Graph() {
super("Simple Drawing");
super.setSize(300, 300);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
jp = new GPanel();
super.add(jp);
}
public static void main(String[] args) {
Graph g1 = new Graph();
g1.setVisible(true);
}
class GPanel extends JPanel {
public GPanel() {
super.setPreferredSize(new Dimension(300, 300));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//rectangle originated at 10,10 and end at 240,240
g.drawRect(10, 10, 240, 240);
//filled Rectangle with rounded corners.
g.fillRoundRect(50, 50, 100, 100, 80, 80);
}
}
}
Use the extraData
property on your FlatList component.
As the documentation states:
By passing
extraData={this.state}
toFlatList
we make sureFlatList
will re-render itself when thestate.selected
changes. Without setting this prop,FlatList
would not know it needs to re-render any items because it is also aPureComponent
and the prop comparison will not show any changes.
Out of all the combinations you tried, %ld
and %lu
are the only ones which are valid printf format specifiers at all. %lu
(long unsigned decimal), %lx
or %lX
(long hex with lowercase or uppercase letters), and %lo
(long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the %
and the l
).
if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:
import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';
const temp = (
<div>
<img src={logo} />
<img src={image} />
</div>
);
ReactDOM.render(temp,document.getElementByID("app"));
Happy Coding :")
resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/
This solution works for arbitrary nesting depths - not just the "list of lists" depth that some (all?) of the other solutions are limited to:
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
It's the recursion which allows for arbitrary depth nesting - until you hit the maximum recursion depth, of course...
I also faced the same problem and the problem was that the libraries were missing in some of the following files.
settings.gradle, app/build.gradle, package.json, MainApplication.java
Suppose the library is react-native-vector-icons then it should be mentioned in following files;
compile project(':react-native-vector-icons')
include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;
and then add: new VectorIconsPackage() in getPackages() method.
Here are the steps:
click File > Import. The Import window opens.
Under Select an import source, click J2EE > App Client JAR file.
Click Next.
In the Application Client file field, enter the location and name of the application client JAR file that you want to import. You can click the Browse button to select the JAR file from the file system.
In the Application Client project field, type a new project name or select an application client project from the drop-down list. If you type a new name in this field, the application client project will be created based on the version of the application client JAR file, and it will use the default location.
In the Target runtime drop-down list, select the application server that you want to target for your development. This selection affects the run time settings by modifying the class path entries for the project.
If you want to add the new module to an enterprise application project, select the Add project to an EAR check box and then select an existing enterprise application project from the list or create a new one by clicking New.
Note: If you type a new enterprise application project name, the enterprise application project will be created in the default location with the lowest compatible J2EE version based on the version of the project being created. If you want to specify a different version or a different location for the enterprise application, you must use the New Enterprise Application Project wizard.
Click Finish to import the application client JAR file.
I remember seeing this posted somewhere else (I couldn't find where), but this works really well:
setTimeout(() => {
window.scrollTo(0, 0);
}, 0);
It's weird, but the way it works is based off of the way JavaScript's stack queue works. The full explanation is found here in the Zero Delays section.
The basic idea is that the time for setTimeout
doesn't actually specify the set amount of time it will wait, but the minimum amount of time it will wait. So when you tell it to wait 0ms, the browser runs all the other queued processes (like scrolling the window to where you were last) and then executes the callback.
A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:
using System;
namespace Service.Support
{
public static class Base64
{
public static string ToBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return Convert.ToBase64String(textAsBytes);
}
public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
{
if (encodedText == null)
{
decodedText = null;
return false;
}
try
{
byte[] textAsBytes = Convert.FromBase64String(encodedText);
decodedText = encoding.GetString(textAsBytes);
return true;
}
catch (Exception)
{
decodedText = null;
return false;
}
}
}
}
Not trying to take any credits here, all credit goes to @theazureshadow for his reply, but I personally had to adapt it for a table that has some <th>
instead of <td>
for it's first row's cells.
I'm just posting the modified version here in case some of you want to use @theazureshadow's solution, but like me, have some <th>
in the first <tr>
. The class "reportTable" only have to be applied to the table itself.:
table.reportTable {
border-collapse: separate;
border-spacing: 0;
}
table.reportTable td {
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable td:last-child {
border-right: solid gray 1px;
}
table.reportTable tr:last-child td{
border-bottom: solid gray 1px;
}
table.reportTable th{
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable th:last-child{
border-right: solid gray 1px;
border-top-right-radius: 10px;
}
table.reportTable th:first-child{
border-top-left-radius: 10px;
}
table.reportTable tr:last-child td:first-child{
border-bottom-left-radius: 10px;
}
table.reportTable tr:last-child td:last-child{
border-bottom-right-radius: 10px;
}
Feel free to adjust the paddings, radiuses, etc to fit your needs. Hope that helps people!
So for people who want semantics similar to:
$ chmod 755 somefile
Use:
$ python -c "import os; os.chmod('somefile', 0o755)"
If your Python is older than 2.6:
$ python -c "import os; os.chmod('somefile', 0755)"
To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well
dat.dropna(subset=['x'])
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/
I bashed my head on this for hours until I thought about checking my .bash_profile. I didn't have a path listed for python3 so I added the following code:
# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH
And then re-installed matplotlib with sudo pip3 install matplotlib
. All is working beautifully now.
You can implement a static formatting method or an HTML helper, then use this syntaxe :
@using class_of_method_namespace
...
// HTML page here
@className.MethodName()
or in case of HTML Helper
@Html.MehtodName()
First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.
Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:
os.path.dirname(sys.argv[0])
Py2exe does not provide an __file__
variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
I have checked a variable if it is a boolean or not as below
console.log(isBoolean(this.myVariable));
Similarly we have
isNumber(this.myVariable);
isString(this.myvariable);
and so on.
If you want to get full screen without actionBar and Title.
Add it in style.xml
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
and use the style at manifest.xml.
android:theme="@style/AppTheme.NoActionBar"
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
Update
Now that I've karma wh..err mined enough from this answer everyone should know that this should have been fixed.
re: via Ownatik again bundle install fails with SSL certificate verification error
gem update --system
My answer is still correct and left below for reference if that ends up not working for you.
Honestly the best temporary solution is to
[...] use the non-ssl version of rubygems in your gemfile as a temporary workaround.
via user Ownatik
what they mean is at the top of the Gemfile
in your rails application directory change
source 'https://rubygems.org'
to
source 'http://rubygems.org'
note that the second version is http instead of https
Boost is a good suggestion. But if you would like to roll your own, it's not so hard.
Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.
I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.
Low reputation (too many years of lurking, sigh) so I can't yet comment inline, but I found the answer from @laktak to be the only one that worked as intended on Ubuntu 18.04 -- using tar -cjf site1.tar.bz2 -C /var/www/site1 .
on my machine resulted in all the files I wanted being under ./
inside the tar.bz2 file, which is probably ok but there is some risk of inconsistent behavior across OSs when un-tarring.
View single commit:
https://github.com/<user>/<project>/commit/<hash>
View log:
https://github.com/<user>/<project>/commits/<hash>
View full repo:
https://github.com/<user>/<project>/tree/<hash>
<hash>
can be any length as long as it is unique.
Date
is Comparable
& Equatable
(as of Swift 3)This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires that Date
implement the operators: <
, <=
, >
, >=
.Equatable
requires that Date
implement the ==
operator.Equatable
allows Date
to use the default implementation of the !=
operator (which is the inverse of the Equatable
==
operator implementation).The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.
just set the width of the td/column you want to be fixed and the rest will expand.
<td width="200"></td>
Following @dennmatt 's answer, I noticed that InternetAddress.lookup
may return successful results even if the internet connection is off - I tested it by connecting from my simulator to my home WiFi, and then disconnecting my router's cable. I think the reason is that the router caches the domain-lookup results so it does not have to query the DNS servers on each lookup request.
Anyways, if you use Firestore like me, you can replace the try-SocketException-catch block with an empty transaction and catch TimeoutExceptions:
try {
await Firestore.instance.runTransaction((Transaction tx) {}).timeout(Duration(seconds: 5));
hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
hasConnection = false;
} on TimeoutException catch(_) {
hasConnection = false;
}
Also, please notice that previousConnection
is set before the async intenet-check, so theoretically if checkConnection()
is called multiple times in a short time, there could be multiple hasConnection=true
in a row or multiple hasConnection=false
in a row.
I'm not sure if @dennmatt did it on purpose or not, but in our use-case there were no side effects (setState
was only called twice with the same value).
Just follow 3 steps
Enable mode_rewrite using following command
sudo a2enmod rewrite
Password will be asked. So enter your password
Update your 000-default.conf or default.conf file located at /etc/apache2/sites-available/ directory. you can not edit it directly. so use following command to open
sudo gedit /etc/apache2/sites-available/000-default.conf
Or sudo gedit /etc/apache2/sites-available/default.conf
you will get
DocumentRoot /var/www/html
OR
DocumentRoot /var/www
line. Add following code after it.
<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Make user the directory tag path is same as shown in your file.
Restart your apache server using following command
sudo service apache2 restart
In many cases what you need is just
[self tintColor]
// or if in a ViewController
[self.view tintColor]
or for swift
self.tintColor
// or if in a ViewController
self.view.tintColor
I had the same issue as OP (I think!), but I couldn't get it to work in the way that Lastalda specified. I don't know if I have interpreted the question properly, but I have found another solution (it probably is a really bad way of doing it though).
This was the way that I did it:
plt.hist([1,11,21,31,41], bins=[0,10,20,30,40,50], weights=[10,1,40,33,6]);
Which creates this:
So the first parameter basically 'initialises' the bin - I'm specifically creating a number that is in between the range I set in the bins parameter.
To demonstrate this, look at the array in the first parameter ([1,11,21,31,41]) and the 'bins' array in the second parameter ([0,10,20,30,40,50]):
Then I'm using the 'weights' parameter to define the size of each bin. This is the array used for the weights parameter: [10,1,40,33,6].
So the 0 to 10 bin is given the value 10, the 11 to 20 bin is given the value of 1, the 21 to 30 bin is given the value of 40, etc.
"Just set the MaxSelectionCount
to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString()
. There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
I use git log to see what has changed on a feature branch from master branch
git log does_this_branch..contain_this_branch_changes
e.g. - to see what commits are in a feature branch that has/not been merged to master:
git log master..feature_branch
If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception
and check "Constructors from superclass" and it will generate the following:
package com.example.exception;
public class MyException extends Exception {
public MyException() {
// TODO Auto-generated constructor stub
}
public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
In response to the question below about not calling super()
in the defualt constructor, Oracle has this to say:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
simple example of a function parent_by_selector which return a parent or null (no selector matches):
function parent_by_selector(node, selector, stop_selector = 'body') {
var parent = node.parentNode;
while (true) {
if (parent.matches(stop_selector)) break;
if (parent.matches(selector)) break;
parent = parent.parentNode; // get upper parent and check again
}
if (parent.matches(stop_selector)) parent = null; // when parent is a tag 'body' -> parent not found
return parent;
};
You do not need to take a pointer to the array in order to pass it to an array-generating function, because arrays already decay to pointers when you pass them to functions. Simply make the parameter int a[]
, and use it as a regular array inside the function, the changes will be made to the array that you have passed in.
void generateArray(int a[], int si) {
srand(time(0));
for (int j=0;j<*si;j++)
a[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
As a side note, you do not need to pass the size by pointer, because you are not changing it inside the function. Moreover, it is not a good idea to pass a pointer to constant to a parameter that expects a pointer to non-constant.
It is an extra part to the answer to this question here but I thought it might be useful. As many people mentioned, Visual Studio Code has the OUTLINE part which provides the ability to browse to different function and show them on the side.
I also wanted to add that if you check the follow cursor mark, it highlights that function name in the OUTLINE view, which is very helpful in browsing and seeing which function you are in.
I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.
The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).
Those who need a single tool to connect to multiple database engines can now use SQL Developer.
/Users/{user}/Library/Application Support/Sublime Text 2/Packages
Get to it quickly from within Sublime via the menu at Sublime Text 2... Preferences... Browse Packages
Google Chrome in its last beta version finally uses the input type=date
, and the format is DD-MM-YYYY
.
So there must be a way to force a specific format. I'm developing a HTML5 web page and the date searches now fail with different formats.
Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = @"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:@"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(@"Trying to call ws %@",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"Response:%@",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(@"%@: %@", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(@"%@",json_response);
}
}
else {
NSLog(@"Error serializing JSON: %@", error);
NSLog(@"RAW RESPONSE: %@",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"Response:%@",returnString2);
}
}
}];
Hope this helps!
since answers are disappointing I would like suggest a way in which I got deleted stuff back.
I use an ide to code and accidently I used rm -rf from terminal to remove complete folder. Thanks to ide I recoved it back by reverting the change from ide's local history.
(my ide is intelliJ but all ide's support history backup)
Use this code instead of it:
<frameset rows="100%,*">
<frame src="-------------------------URL-------------------------------">
<noframes>
<body>
Your browser does not support frames. To wiew this page please use supporting browsers.
</body>
</noframes>
</frameset>
There's JS function to deal with &#xxxx styled entities:
function at GitHub
// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var entity = '高级程序设计';
var str = '??????';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
Firebase: https://firebase.google.com/docs/cloud-messaging/
GCM(Deprecated): http://developer.android.com/google/gcm/index.html
I don't have much knowledge about C2DM. Use GCM, it's very easy to implement and configure.
How about the alternate form of for
mentioned in (bashref)Looping Constructs?
To get a user Input :
set /p pathName=Enter The Value:%=%
@echo %pathName%
p.s. this is also valid :
set /p pathName=Enter The Value:
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And then use it with piping:
ls -1 | python parse.py
an alterable way to run an .jar app is create an .bat cmd for it. for example, you have jre10 and jre8 installed on your pc,and jre10 is your default jre. but your jar is specified to work with jre8,following cmd will work:
"C:\Program Files\Java\jre1.8.0_181\bin\java.exe" -jar JabRef-4.3.1.jar
The downloads have moved, it says that on that very page: