SHORT ANSWER: We don't know how to do garbage collection efficiently (with minor time and space overhead) and correctly all the time (in all possible cases).
LONG ANSWER: Just like C, C++ is a systems language; this means it is used when you are writing system code, e.g., operating system. In other words, C++ is designed, just like C, with best possible performance as the main target. The language' standard will not add any feature that might hinder the performance objective.
This pauses the question: Why garbage collection hinders performance? The main reason is that, when it comes to implementation, we [computer scientists] do not know how to do garbage collection with minimal overhead, for all cases. Hence it's impossible to the C++ compiler and runtime system to perform garbage collection efficiently all the time. On the other hand, a C++ programmer, should know his design/implementation and he's the best person to decide how to best do the garbage collection.
Last, if control (hardware, details, etc.) and performance (time, space, power, etc.) are not the main constraints, then C++ is not the write tool. Other language might serve better and offer more [hidden] runtime management, with the necessary overhead.
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
so:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>
I'm thinking that your output parameter is coming back with a DBNull value. Add a check for that like this
var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");
if(!(outputParam is DBNull))
DataTO.Id = Convert.ToInt64(outputParam);
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);
though i take the url from an input, it's easy adjustable to the real url.
var value = 0;
$('#check').click(function()
{
var originalURL = $('#test').val();
var exists = originalURL.indexOf('&view-all');
if(exists === -1)
{
$('#test').val(originalURL + '&view-all=value' + value++);
}
else
{
$('#test').val(originalURL.substr(0, exists + 15) + value++);
}
});
If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.
In your code you simply use
x1.index
and the returned array is the indexes relating to the original positions in x.
A rather roundabout way, just for completeness:
for /f "delims=" %i in ('type CON') do set inp=%i
Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.
Click on Tools > SDK Manager or click SDK Manager after If you are unable to see the location of your Android SDK Location, click on edit and create a folder where you want to keep it and then click Next and Finish
Better Way to Provide Choice inside a django Model :
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
If you want an interactive heatmap from a Pandas DataFrame and you are running a Jupyter notebook, you can try the interactive Widget Clustergrammer-Widget, see interactive notebook on NBViewer here, documentation here
And for larger datasets you can try the in-development Clustergrammer2 WebGL widget (example notebook here)
Another way to do this:
first_value = df['Btime'].values[0]
This way seems to be faster than using .iloc
:
In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Your pattern is fine. But you shouldn't be split()
ting it away, you should find()
it. Following code gives the output you are looking for:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
The percentage %
sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20
is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".
Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?
var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"
Javascript has both decodeURI
and decodeURIComponent
which differ slightly in respect to their encodeURI
and encodeURIComponent
counterparts - you should familiarise yourself with the documentation.
In simple words:
var x = (day == "yes") ? "Good Day!" : (day == "no") ? "Good Night!" : "";
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
The accepted answer made radio button disappear on Chrome. This works:
input:not([type="radio"]):not([type="checkbox"]) {
-webkit-appearance: none;
border-radius: 0;
}
You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE @num1 int = 3 DECLARE @num2 int = 2
SELECT @num1/@num2
SELECT @num1/CONVERT(decimal(4,2), @num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
Go TO Window>Show View >Markers
than you will get java task .
java task have all TODOs of your project
In a crontab
file, the fields are:
So:
10 * * * * blah
means execute blah
at 10 minutes past every hour.
If you want every five minutes, use either:
*/5 * * * * blah
meaning every minute but only every fifth one, or:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah
for older cron
executables that don't understand the */x
notation.
If it still seems to be not working after that, change the command to something like:
date >>/tmp/debug_cron_pax.txt
and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron
daemon.
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
<%@ Page Language="C#" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Redirect("new.aspx");
}
</script>
Just add the <mat-icon>
inside mat-button
or mat-raised-button
. See the example below. Note that I am using material icon instead of your svg for demo purpose:
<button mat-button>
<mat-icon>mic</mat-icon>
Start Recording
</button>
OR
<button mat-raised-button color="accent">
<mat-icon>mic</mat-icon>
Start Recording
</button>
Here is a link to stackblitz demo.
First Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Second way:
You created an empty file with the desired name, which then prevented you from creating the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Third way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fourth Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fifth way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Correct way:
File
for your desired directory (e.g., File path=new File(getFilesDir(),"myfolder");
)mkdirs()
on that File
to create the directory if it does not existFile
for the output file (e.g., File mypath=new File(path,"myfile.txt");
)File
(e.g., using new BufferedWriter(new FileWriter(mypath))
)You can use str()
to cast it, or formatters:
"ME%d.txt" % (num,)
Multiply the value you want to insert (ex. 2.99) by 100
Then insert the division by 100 of the result adding .01 to the end:
299.01/100
I had this happen when I was trying to use a deployment key because that is exactly what I wanted.
I could connect via ssh -T [email protected]
and it would tell me I had access to read the repository I wanted, but git clone
would fail.
Clearing out ~/.ssh/known_hosts
, generating a new key via ssh-keygen
, adding that new key to bitbucket, and retrying fixed it for me.
Call this method to check the network Connection.
public static bool IsConnectedToInternet()
{
bool returnValue = false;
try
{
int Desc;
returnValue = Utility.InternetGetConnectedState(out Desc, 0);
}
catch
{
returnValue = false;
}
return returnValue;
}
Put this below line of code.
[DllImport("wininet.dll")]
public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
See my select for paginator
SELECT TOP @limit * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (
-- YOU SELECT HERE
SELECT * FROM mytable
) myquery
) paginator
WHERE offset > @offset
This solves the pagination ;)
Use this code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open !");
conn.Close();
Simply You Can Use It
$sql="select * from tbl_publication where id='5'";
$result=mysql_query($sql);
$res=mysql_fetch_array($result);
//Getting File Name From DB
$pdfname = $res1['pdfname'];
//pdf is directory where file exist
unlink("pdf/".$pdfname);
Use a dot or a pipe as the field separator:
awk -v FS='[.|]' '{
printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END
gives:
Emailclient [email protected]
Socialsite [email protected]
PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains ,
use as join('-')
parametr character (can be utf) which is not used in strings
array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
This is Very Good Example of minus Length of an array in java, i am giving here both examples
public static int linearSearchArray(){
int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
int key = 7;
int i = 0;
int count = 0;
for ( i = 0; i< arrayOFInt.length; i++){
if ( arrayOFInt[i] == key ){
System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
count ++;
}
}
System.out.println("this Element found the ("+ count +") number of Times");
return i;
}
this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.
Outline indeed does apply to the whole element.
Now that I see your image, here's how to achieve it.
.element {_x000D_
padding: 5px 0;_x000D_
background: #CCC;_x000D_
}_x000D_
.element:before {_x000D_
content: "\a0";_x000D_
display: block;_x000D_
padding: 2px 0;_x000D_
line-height: 1px;_x000D_
border-top: 1px dashed #000; _x000D_
}_x000D_
.element p {_x000D_
padding: 0 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
<p>Some content comes here...</p>_x000D_
</div>
_x000D_
(Or see external demo.)
All sizes and colors are just placeholders, you can change it to match the exact desired result.
Important note: .element must have display:block;
(default for a div) for this to work. If it's not the case, please provide your full code, so that i can elaborate a specific answer.
nginx or G-WAN
http://nbonvin.wordpress.com/2011/03/24/serving-small-static-files-which-server-to-use/
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
output: 25933473
The most significant advantage of shared libraries is that there is only one copy of code loaded in memory, no matter how many processes are using the library. For static libraries each process gets its own copy of the code. This can lead to significant memory wastage.
OTOH, a advantage of static libraries is that everything is bundled into your application. So you don't have to worry that the client will have the right library (and version) available on their system.
You can use regexp or strcmp to eliminate .
and ..
Or you could use the isdir
field if you only want files in the directory, not folders.
list=dir(pwd); %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
filenames={list(isfile).name}; %create cell array of file names
or combine the last two lines:
filenames={list(~[list.isdir]).name};
For a list of folders in the directory excluding . and ..
dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));
From this point, you should be able to throw the code in a nested for loop, and continue searching each subfolder until your dirnames returns an empty cell for each subdirectory.
If you do not use a tool to merge, first copy your code outside:
- `checkout master`
- `git pull` / get new commit
- `git checkout` to your branch
- `git rebase master`
It resolve conflict and you can copy your code.
If you are using PHP you can get it this way:
<?php
$dbname = 'base.db';
$db = new SQLite3($dbname);
$sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");
$table = $sturturequery->fetchArray();
echo '<pre>' . $table['sql'] . '</pre>';
$db->close();
?>
System.Diagnostics.Process.Start( @"C:\Windows\System32\Notepad.exe" );
<form>
<fieldset class="form-group"><input type="text" class="form-control" placeholder="Input"/></fieldset>
<fieldset class="form-group"><button class="btn btn-primary"/>Button</fieldset>
</form>
http://v4-alpha.getbootstrap.com/components/forms/#form-controls
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
you must be using Laravel 5 the command
class User_Controller extends Controller {
public $restful = true;
public function get_index(){
return View('user.index');
}
}
and in routes.php
Route::get('/', function()
{
return view('home.index');
});
Route::get('user', function()
{
return view('user.index');
});
Laravel 5 command changes for view and controller see the documentation i was having same error before
I found this post more relevant in this scenario:
WITH upsert AS (
UPDATE spider_count SET tally=tally+1
WHERE date='today' AND spider='Googlebot'
RETURNING *
)
INSERT INTO spider_count (spider, tally)
SELECT 'Googlebot', 1
WHERE NOT EXISTS (SELECT * FROM upsert)
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
You can have return
in a void method, you just can't return any value (as in return 5;
), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:
void someFunct(int arg)
{
if (arg == 0)
{
//Leave because this is a bad value
return;
}
//Otherwise, do something
}
Use the "+" symbol to cast a string to a number.
window.location.hash = +page_number;
On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.
Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/
$(document).ready(function () {
var $obj = $('#comment');
var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$obj.addClass('fixed');
} else {
// otherwise remove it
$obj.removeClass('fixed');
}
});
});
<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>
<!--Insert more code here-->
<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.
The /etc/apache2/httpd.conf
is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf
!
“httpd.conf is for user options.” No it isn't, it's there for historic reasons.
Using Apache server, all user options should go into a new *.conf
-file inside /etc/apache2/conf.d/
. This method should be "update-safe", as httpd.conf
or apache2.conf
may get overwritten on the next server update.
Inside /etc/apache2/apache2.conf
, you will find the following line, which includes those files:
# Include generic snippets of statements
Include conf.d/
As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/
. Use a2enconf FILENAME_WITHOUT_SUFFIX
to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/
. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf
(e.g. conf-available/my-settings.conf
);
If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE
and 0 == FALSE
to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE
.
NASDAQ Stock lists ftp://ftp.nasdaqtrader.com/symboldirectory
The 2 files nasdaqlisted.txt and otherlisted.txt are | pipe separated. That should give you a good list of all stocks.
Got the IDE working again. The solution is quite funny - and even a re-install, and deleting the IDE does not fix it on windows. What you need to do in that case, is to go to the testNG run configurations - and delete them all. This is for the TestNG XML classpath error on windows OS. I am using spring tools suite 3.6.4.
Make certain that you delete all the configurations, make sure the project can build, and if there are no problems, the test should run now.
Regards -Anthony Toorie
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
The length of an array is available as
int l = array.length;
The size of a List
is availabe as
int s = list.size();
From my understanding matplotlib is a plotting library.
If you want to change the image data (e.g. draw a rectangle on an image), you could use PIL's ImageDraw, OpenCV, or something similar.
Here is PIL's ImageDraw method to draw a rectangle.
Here is one of OpenCV's methods for drawing a rectangle.
Your question asked about Matplotlib, but probably should have just asked about drawing a rectangle on an image.
Here is another question which addresses what I think you wanted to know: Draw a rectangle and a text in it using PIL
I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :(
<
= less than <
, >
= greater than >
You can use [].reduce
for a more compact implementation of RobG's approach:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
I got this same error inside a stored procedure, in the where clause. i discovered that the problem ocurred with a local declared variable, previously loaded by the same table/column.
I resolved it casting the data to single char type.
You can write the below code:-
create procedure spCreateTable
as
begin
create table testtb(Name varchar(20))
end
execute it as:-
exec spCreateTable
Synchronize the data/object that you have saved into NSUserDefaults
-(void)saveCustomObject:(Player *)object
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[prefs setObject:myEncodedObject forKey:@"testing"];
[prefs synchronize];
}
Hope this will help you. Thanks
Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
Here is how to do a quick check to see if n.fn.init[0]
is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout
function like this:
function timeout(){
...your selector function that returns n.fn.init[0] goes here...
}
setTimeout(timeout, 5000)
This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.
This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.
The preferred ways to check if the DOM is loaded before executing your function are as follows:
1) Wrap your selector function in
$(document).ready(function(){ ... your selector function... };
2) If that doesn't work, use DOMContentLoaded
3) Try window.onload, which waits for all the images to load first, so its least preferred
window.onload = function () { ... your selector function... }
4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.
5) Finally, you can stick with hard-coded setTimeout
function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.
This list of fixes is probably far from perfect so everyone is welcome to edit it.
For Visual Studio 2017
Find "References" in Solution explorer
Right click "References"
Choose "Add Reference..."
Find "Presentation.Core" list and check checkbox
Click OK
from the Chrome Rest client make a GET request or
curl -XGET 'http://localhost:9200'
in console
rest client: http://localhost:9200
{
"name": "node",
"cluster_name": "elasticsearch-cluster",
"version": {
"number": "2.3.4",
"build_hash": "dcxbgvzdfbbhfxbhx",
"build_timestamp": "2016-06-30T11:24:31Z",
"build_snapshot": false,
"lucene_version": "5.5.0"
},
"tagline": "You Know, for Search"
}
where number field denotes the elasticsearch
version. Here elasticsearch
version is 2.3.4
I'll take a stab at it:
/^[a-z](?:_?[a-z0-9]+)*$/i
Explained:
/
^ # match beginning of string
[a-z] # match a letter for the first char
(?: # start non-capture group
_? # match 0 or 1 '_'
[a-z0-9]+ # match a letter or number, 1 or more times
)* # end non-capture group, match whole group 0 or more times
$ # match end of string
/i # case insensitive flag
The non-capture group takes care of a) not allowing two _
's (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.
Some test strings:
"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match
Arrays.asList() would do the trick here.
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);
For converting to Set, you can do as below
Set<T> mySet = new HashSet<T>(Arrays.asList(words));
It appears that the :include
functionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
This example allows to upload PNG image only.
HTML
<input type="file" class="form-control" id="FileUpload1" accept="image/png" />
JS
$('#FileUpload1').change(
function () {
var fileExtension = ['png'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.png' format is allowed.");
this.value = ''; // Clean field
return false;
}
});
Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.
The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".
It is actually stripping the package information from the name, but this is hidden from you.
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
this question asked in 2009 but i want to share my codes:
Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable
Dim x As Integer
Dim y As Integer
Dim bln As Boolean
Dim dttable2 As New DataTable
For x = 0 To dttable.Columns.Count - 1
dttable2.Columns.Add(dttable.Columns(x).ColumnName)
Next
For x = 0 To dttable.Rows.Count - 1
For y = 0 To searchcolumns.Length - 1
If String.IsNullOrEmpty(searchcolumns(y)) = False Then
If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
bln = True
Else
bln = False
Exit For
End If
End If
Next
If bln = True Then
dttable2.Rows.Add(dttable.Rows(x).ItemArray)
End If
Next
Return dttable2
End Function
In the R help section, as pointed out above, just disabling quoting altogether, by simply adding:
quote = ""
to the read.csv() worked for me.
The error, "EOF within quoted string", occurred with:
> iproscan.53A.neg = read.csv("interproscan.53A.neg.n.csv",
+ colClasses=c(pb.id = "character",
+ genLoc = "character",
+ icode = "character",
+ length = "character",
+ proteinDB = "character",
+ protein.id = "character",
+ prot.desc = "character",
+ start = "character",
+ end = "character",
+ evalue = "character",
+ tchar = "character",
+ date = "character",
+ ipro.id = "character",
+ prot.name = "character",
+ go.cat = "character",
+ reactome.id= "character"),
+ as.is=T,header=F)
Warning message:
In scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, :
EOF within quoted string
> dim(iproscan.53A.neg)
[1] 69383 16
And the file read in was missing 6,619 lines. But by disabling quoting
> iproscan.53A.neg = read.csv("interproscan.53A.neg.n.csv",
+ colClasses=c(pb.id = "character",
+ genLoc = "character",
+ icode = "character",
+ length = "character",
+ proteinDB = "character",
+ protein.id = "character",
+ prot.desc = "character",
+ start = "character",
+ end = "character",
+ evalue = "character",
+ tchar = "character",
+ date = "character",
+ ipro.id = "character",
+ prot.name = "character",
+ go.cat = "character",
+ reactome.id= "character"),
+ as.is=T,header=F,**quote=""**)
>
> dim(iproscan.53A.neg)
[1] 76002 16
Worked without error and all lines were successfully read in.
I also have same problem and in my case I injected reducer properly but still I couldn't type in field. It turns out if you are using immutable
you have to use redux-form/immutable
.
import {reducer as formReducer} from 'redux-form/immutable';
const reducer = combineReducers{
form: formReducer
}
import {Field, reduxForm} from 'redux-form/immutable';
/* your component */
Notice that your state should be like state->form
otherwise you have to explicitly config the library also the name for state should be form
.
see this issue
Firstly, thanks to Andrei as I've based my solution on his example.
I'm including mine as it's a more complete sample and might save readers some time.
The limitation of Andrei's approach is that doesn't handle logging, capturing potentially useful request variables and content negotiation (it will always return JSON no matter what the client has requested - XML / plain text etc).
My approach is to use an ObjectResult which allows us to use the functionality baked into MVC.
This code also prevents caching of the response.
The error response has been decorated in such a way that it can be serialized by the XML serializer.
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate next;
private readonly IActionResultExecutor<ObjectResult> executor;
private readonly ILogger logger;
private static readonly ActionDescriptor EmptyActionDescriptor = new ActionDescriptor();
public ExceptionHandlerMiddleware(RequestDelegate next, IActionResultExecutor<ObjectResult> executor, ILoggerFactory loggerFactory)
{
this.next = next;
this.executor = executor;
logger = loggerFactory.CreateLogger<ExceptionHandlerMiddleware>();
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
logger.LogError(ex, $"An unhandled exception has occurred while executing the request. Url: {context.Request.GetDisplayUrl()}. Request Data: " + GetRequestData(context));
if (context.Response.HasStarted)
{
throw;
}
var routeData = context.GetRouteData() ?? new RouteData();
ClearCacheHeaders(context.Response);
var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);
var result = new ObjectResult(new ErrorResponse("Error processing request. Server error."))
{
StatusCode = (int) HttpStatusCode.InternalServerError,
};
await executor.ExecuteAsync(actionContext, result);
}
}
private static string GetRequestData(HttpContext context)
{
var sb = new StringBuilder();
if (context.Request.HasFormContentType && context.Request.Form.Any())
{
sb.Append("Form variables:");
foreach (var x in context.Request.Form)
{
sb.AppendFormat("Key={0}, Value={1}<br/>", x.Key, x.Value);
}
}
sb.AppendLine("Method: " + context.Request.Method);
return sb.ToString();
}
private static void ClearCacheHeaders(HttpResponse response)
{
response.Headers[HeaderNames.CacheControl] = "no-cache";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
response.Headers.Remove(HeaderNames.ETag);
}
[DataContract(Name= "ErrorResponse")]
public class ErrorResponse
{
[DataMember(Name = "Message")]
public string Message { get; set; }
public ErrorResponse(string message)
{
Message = message;
}
}
}
From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:
dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059
And here's the code I used (Python 3.6)
from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit
def is_date_parsing(date_str):
try:
return bool(date_parser.parse(date_str))
except ValueError:
return False
def is_date_matching(date_str):
try:
return bool(datetime.strptime(date_str, '%Y-%m-%d'))
except ValueError:
return False
if __name__ == '__main__':
print("dateutil.parser (valid date):", end=' ')
print(timeit("is_date_parsing('2021-01-26')",
setup="from __main__ import is_date_parsing",
number=100000))
print("dateutil.parser (invalid date):", end=' ')
print(timeit("is_date_parsing('meh')",
setup="from __main__ import is_date_parsing",
number=100000))
print("datetime.strptime (valid date):", end=' ')
print(timeit("is_date_matching('2021-01-26')",
setup="from __main__ import is_date_matching",
number=100000))
print("datetime.strptime (invalid date):", end=' ')
print(timeit("is_date_matching('meh')",
setup="from __main__ import is_date_matching",
number=100000))
You can define a a click function and then set the onclick
attribute for the element.
function imageClick(url) {
window.location = url;
}
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />
This approach lets you get rid of the surrounding <a>
element. If you want to keep it, then define the onclick
attribute on <a>
instead of on <img>
.
The value for BYTES PER CLUSTER - 65536 = 64K
C:\temp>fsutil fsinfo drives
Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\ N:\ O:\ P:\ S:\
C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number : 0xfe5a90935a9049f3
NTFS Version : 3.1
LFS Version : 2.0
Number Sectors : 0x00000002e15befff
Total Clusters : 0x000000005c2b7dff
Free Clusters : 0x000000005c2a15f0
Total Reserved : 0x0000000000000000
Bytes Per Sector : 512
Bytes Per Physical Sector : 512
Bytes Per Cluster : 4096
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x0000000000040000
Mft Start Lcn : 0x00000000000c0000
Mft2 Start Lcn : 0x0000000000000002
Mft Zone Start : 0x00000000000c0000
Mft Zone End : 0x00000000000cc820
Resource Manager Identifier : 560F51B2-CEFA-11E5-80C9-98BE94F91273
C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number : 0x36acd4b1acd46d3d
NTFS Version : 3.1
LFS Version : 2.0
Number Sectors : 0x00000002e15befff
Total Clusters : 0x0000000005c2b7df
Free Clusters : 0x0000000005c2ac28
Total Reserved : 0x0000000000000000
Bytes Per Sector : 512
Bytes Per Physical Sector : 512
Bytes Per Cluster : 65536
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x0000000000010000
Mft Start Lcn : 0x000000000000c000
Mft2 Start Lcn : 0x0000000000000001
Mft Zone Start : 0x000000000000c000
Mft Zone End : 0x000000000000cca0
Resource Manager Identifier : 560F51C3-CEFA-11E5-80C9-98BE94F91273
One option from DOM directly:
$(document).find("title").text();
Tested only on chrome & IE9, but logically should work on all browsers.
Or more generic
var title = document.getElementsByTagName("title")[0].innerHTML;
Math.random()
will return a number between 0 and 1(exclusive). So, if you want 0-40, you can multiple it by 40, the highest the result can ever be is what you're multiplying by.
var arr = [];
for (var i=0, t=40; i<t; i++) {
arr.push(Math.round(Math.random() * t))
}
document.write(arr);
There are at least 4 ways to do this thing, however,each has some difference. We using u_id to group and using lift value to order/sort
1 dplyr traditional way
library(dplyr)
top10_final_subset1 = final_subset %>% arrange(desc(lift)) %>% group_by(u_id) %>% slice(1:10)
and if you switch the order of arrange(desc(lift)) and group_by(u_id) the result is essential the same.And if there is tie for equal lift value,it will slice to make sure each group has no more than 10 values, if you only have 5 lift value in the group, it will only gives you 5 results for that group.
2 dplyr topN way
library(dplyr)
top10_final_subset2 = final_subset %>% group_by(u_id) %>% top_n(10,lift)
this one if you have tie in lift value, say 15 same lift for the same u_id, you will got all 15 observations
3 data.table tail way
library(data.table)
final_subset = data.table(final_subset,key = "lift")
top10_final_subset3 = final_subset[,tail(.SD,10),,by = c("u_id")]
It has the same row numbers as the first way, however, there are some rows are different, I guess they are using diff random algorithm dealing with tie.
4 data.table .SD way
library(data.table)
top10_final_subset4 = final_subset[,.SD[order(lift,decreasing = TRUE),][1:10],by = "u_id"]
This way is the most "uniform" way,if in a group there are only 5 observation it will repeat value to make it to 10 observations and if there are ties it will still slice and only hold for 10 observations.
If you want the editor to work with git operations, setting the $EDITOR
environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:
git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.
If you want Sublime to work correctly with git, you should configure it using:
git config --global core.editor "sublime -n -w"
I came here looking for this and found the solution in this gist on github.
You can do it (albeit not lightning-quickly) like so:
people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));
That is, "select all people where there isn't another different person in the list with the same ID."
Mind you, in your example, that would just select person 3. I'm not sure how to tell which you want, out of the previous two.
There is a dynamic comparison chart over at the versioncontrolblog where you can compare several different version control systems.
The obvious, simple answer is missing, so for completeness:
But is there any way to have values in an object literal's properties depend on other properties declared earlier?
No. All of the solutions here defer it until after the object is created (in various ways) and then assign the third property. The simplest way is to just do this:
var foo = {
a: 5,
b: 6
};
foo.c = foo.a + foo.b;
All others are just more indirect ways to do the same thing. (Felix's is particularly clever, but requires creating and destroying a temporary function, adding complexity; and either leaves an extra property on the object or [if you delete
that property] impacts the performance of subsequent property accesses on that object.)
If you need it to all be within one expression, you can do that without the temporary property:
var foo = function(o) {
o.c = o.a + o.b;
return o;
}({a: 5, b: 6});
Or of course, if you need to do this more than once:
function buildFoo(a, b) {
var o = {a: a, b: b};
o.c = o.a + o.b;
return o;
}
then where you need to use it:
var foo = buildFoo(5, 6);
If you want to call the main method of another class you can do it this way assuming I understand the question.
public class MyClass {
public static void main(String[] args) {
System.out.println("main() method of MyClass");
OtherClass obj = new OtherClass();
}
}
class OtherClass {
public OtherClass() {
// Call the main() method of MyClass
String[] arguments = new String[] {"123"};
MyClass.main(arguments);
}
}
Check the errorlevel
in an if
statement, and then exit /b
(exit the batch file only, not the entire cmd.exe process) for values other than 0.
same-executable-over-and-over.exe /with different "parameters"
if %errorlevel% neq 0 exit /b %errorlevel%
If you want the value of the errorlevel to propagate outside of your batch file
if %errorlevel% neq 0 exit /b %errorlevel%
but if this is inside a for
it gets a bit tricky. You'll need something more like:
setlocal enabledelayedexpansion
for %%f in (C:\Windows\*) do (
same-executable-over-and-over.exe /with different "parameters"
if !errorlevel! neq 0 exit /b !errorlevel!
)
Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command.com batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.
On my windows installation, I get these results:
>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> sys.platform
'win32'
>>>
(You can also look in sys.path
for reasonable locations.)
I did use following solution to this:
findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);
Absolutely it must be work!
chown -Rf www-data:www-data /var/www/html
You may want to try using the inttypes.h library that gives you types such as
int32_t
, int64_t
, uint64_t
etc.
You can then use its macros such as:
uint64_t x;
uint32_t y;
printf("x: %"PRId64", y: %"PRId32"\n", x, y);
This is "guaranteed" to not give you the same trouble as long
, unsigned long long
etc, since you don't have to guess how many bits are in each data type.
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().
This is what worked for me:
To add safe environment variables, in command line, type:
export MY_SUDO_PASS="user_password_here"
To test if it's working type:
echo $MY_SUDO_PASS
> user_password_here
To run it at system startup add it to the end of this file:
nano ~/.bashrc
#.bashrc
...
existing_content:
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
...
export MY_SUDO_PASS="user_password_here"
You can add all your environment variables passwords, usernames, host, etc here later.
If your variables are ready you can run:
To update:
echo $MY_SUDO_PASS | sudo -S apt-get update
Or to install Midnight Commander
echo $MY_SUDO_PASS | sudo -S apt-get install mc
To start Midnight Commander with sudo
echo $MY_SUDO_PASS | sudo -S mc
Or from python shell (or Django/Celery), to change directory ownership recursively:
python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)
Hope it helps.
You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt
cp server.key /opt/lampp/etc/ssl.key/domainname.key
(Use sudo with each command if you are not the super user)
Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:
LoadModule ssl_module modules/mod_ssl.so
Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:
<virtualhost 127.0.1.4:443>
ServerName localhost.domainname.com
ServerAlias localhost.domainname.com *.localhost.domainname.com
ServerAdmin admin@localhost
DocumentRoot "/opt/lampp/htdocs/"
DirectoryIndex index.php
ErrorLog /opt/lampp/logs/domainname.local.error.log
CustomLog /opt/lampp/logs/domainname.local.access.log combined
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key
<directory /opt/lampp/htdocs/>
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</directory>
BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>
Add the following entry to /etc/hosts:
127.0.1.4 localhost.domainname.com
Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.
I am really grooving to Stripes. Total setup includes some cut-and-paste XML into your app's web.xml, and then you're off. No configuration is required, since Stripes is a convention-over-configuration framework. Overriding the default behavior is accomplished via Java 1.5 annotations. Documentation is great. I spent about 1-2 hours reading the tutorial and setting up my first app.
I can't do an in-depth comparison to Struts or Spring-MVC yet, since I haven't built a full-scale in it yet (as I have in Struts), but it looks like it would scale to that level of architecture quite well.
Python 3: new exec (execfile dropped) !
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0's changelog and Hi-Angels comment suggest:
use
exec(open(<filename.py>).read())
instead of
execfile(<filename.py>)
You are confusing a Mock
with a Spy
.
In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.
In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.
What you want is
MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);
A quick example:
static class TestClass {
public String getThing() {
return "Thing";
}
public String getOtherThing() {
return getThing();
}
}
public static void main(String[] args) {
final TestClass testClass = Mockito.spy(new TestClass());
Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
System.out.println(testClass.getOtherThing());
}
Output is:
Some Other thing
NB: You should really try to mock the dependencies for the class being tested not the class itself.
Writing JSON Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject
and looping through each json item. Below i am creating an instance of JSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I recommend using React.createRef()
and ref=this.elementRef
to get the DOM element reference instead of ReactDOM.findDOMNode(this)
. This way you can get the reference to the DOM element as an instance variable.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MenuItem extends Component {
constructor(props) {
super(props);
this.elementRef = React.createRef();
}
handleNVFocus = event => {
console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
}
componentDidMount() {
this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
}
componentWillUnmount() {
this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
}
render() {
return (
<element ref={this.elementRef} />
)
}
}
export default MenuItem;
Check out numpy.count_nonzero.
>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
Use del /F /Q
to force deletion of read-only files (/F
) and directories and not ask to confirm (/Q
) when deleting via wildcard.
This is also a very useful function if you are looking for a rows or data with where condition affected
function num_rows($table)
{
return $this->db->affected_rows($table);
}
And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os
Python module.
>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'
This way you can get hold of the directory structure.
Since at least version 0.16 of pandas, it does not take the parameter "rows"
As of 0.23, the solution would be:
df2.pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique)
which returns:
Z Z1 Z2 Z3
Y
Y1 1.0 1.0 NaN
Y2 NaN NaN 1.0
If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:
df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
left_on = 'key2', right_on = 'key1').drop('key1')
The .drop('key1')
part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.
Microsoft's answer to backing up all user databases on SQL Express is here:
The process is: copy, paste, and execute their code (see below. I've commented some oddly non-commented lines at the top) as a query on your database server. That means you should first install the SQL Server Management Studio (or otherwise connect to your database server with SSMS). This code execution will create a stored procedure on your database server.
Create a batch file to execute the stored procedure, then use Task Scheduler to schedule a periodic (e.g. nightly) run of this batch file. My code (that works) is a slightly modified version of their first example:
sqlcmd -S .\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='E:\SQLBackups\', @backupType='F'"
This worked for me, and I like it. Each time you run it, new backup files are created. You'll need to devise a method of deleting old backup files on a routine basis. I already have a routine that does that sort of thing, so I'll keep a couple of days' worth of backups on disk (long enough for them to get backed up by my normal backup routine), then I'll delete them. In other words, I'll always have a few days' worth of backups on hand without having to restore from my backup system.
I'll paste Microsoft's stored procedure creation script below:
--// Copyright © Microsoft Corporation. All Rights Reserved.
--// This code released under the terms of the
--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
@databaseName sysname = null,
@backupType CHAR(1),
@backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE @DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from @DBs
INSERT INTO @DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=@DatabaseName
OR @DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF @backupType='F'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF @backupType='D'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF @backupType='L'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE @BackupName varchar(100)
DECLARE @BackupFile varchar(100)
DECLARE @DBNAME varchar(300)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @dateTime NVARCHAR(20)
DECLARE @Loop int
-- Loop through the databases one by one
SELECT @Loop = min(ID) FROM @DBs
WHILE @Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF @backupType = 'F'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'D'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'L'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF @backupType = 'F'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
IF @backupType = 'D'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
IF @backupType = 'L'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
IF @backupType = 'F'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'D'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'L'
BEGIN
SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END?
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
Two points:
Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:
DateTime startTime = Convert.ToDateTime("7:00 AM");
DateTime endtime = Convert.ToDateTime("2:00 PM");
TimeSpan duration = startTime - endtime;
... I get -07:00:00
as the result. And even if I forget to provide the AM/PM value:
DateTime startTime = Convert.ToDateTime("7:00");
DateTime endtime = Convert.ToDateTime("2:00");
TimeSpan duration = startTime - endtime;
... I get 05:00:00
. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.
To find the difference between a start and end time, you need to do endTime - startTime
, not the other way around.
If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:
@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
@Context HttpServletResponse response) throws IOException {
try {
//Get your File or Object from wherever you want...
//you can use the key parameter to indentify your file
//otherwise it can be removed
//let's say your file is called "object"
response.setContentLength((int) object.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ object.getName());
ServletOutputStream outStream = response.getOutputStream();
byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
DataInputStream in = new DataInputStream(
object.getDataInputStream());
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outStream.write(bbuf, 0, length);
}
in.close();
outStream.flush();
} catch (S3ServiceException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
return Response.ok().build();
}
Recursive traverse object or array with array or objects elements:
function traverse(&$objOrArray)
{
foreach ($objOrArray as $key => &$value)
{
if (is_array($value) || is_object($value))
{
traverse($value);
}
else
{
// DO SOMETHING
}
}
}
Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }}
won't work in your templates. To fix this,in your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS
.
Sometimes you can pass multiple strings separated by a space and it will be interpreted as \n
.
For example when using a shell script for multi-line notifcations:
#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`
select *
from table
where keyword like '%a%'
and keyword like '%b%'
ps This will be super slow. You may want to investigate full text indexing solutions.
Use
__DIR__
to get the current path of the script and this should fix your problem.
So:
require_once(__DIR__.'/../class/user.php');
This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.
Edit: slash problem fixed
To complement Justus Thane's helpful answer:
As Joey notes in a comment, PowerShell has a powerful, regex-based -split
operator.
-split '...'
), -split
behaves like awk
's default field splitting, which means that:
In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object
cmdlet became available: the .ForEach()
array (collection) method, as described in this blog post (alongside the .Where()
method, a more powerful, expression-based alternative to Where-Object
).
Here's a solution based on these features:
PS> (-split ' One for the money ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]
Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One
and for
were treated as a single separator.
If you are using Visual Studio 2005 and up, you can create a setter/getter real fast using the insert snippet command.
Right click on your code, click on Insert Snippet (Ctrl+K,X), and then choose "prop" from the list.
You can write different sheets as follows
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){
if($work_sheet==0){
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
if($work_sheet==1){
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
if($work_sheet==2){
$objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
$work_sheet++;
}
$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.
My question is when should a use a double and when should I use a decimal type?
decimal
for when you work with values in the range of 10^(+/-28) and where you have expectations about the behaviour based on base 10 representations - basically money.
double
for when you need relative accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - double
covers more than 10^(+/-300). Scientific calculations are the best example here.
which type is suitable for money computations?
decimal, decimal, decimal
Accept no substitutes.
The most important factor is that double
, being implemented as a binary fraction, cannot accurately represent many decimal
fractions (like 0.1) at all and its overall number of digits is smaller since it is 64-bit wide vs. 128-bit for decimal
. Finally, financial applications often have to follow specific rounding modes (sometimes mandated by law). decimal
supports these; double
does not.
here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.
https://dl-ssl.google.com/android/repository/docs-17_r02.zip (129 MB)
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
if u want to use them as an array u already knew, else u can use every one of them as a different parameter ... try this :
parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
You can use the strong
element in html, which is great semantically (also good for screen readers etc.), which typically renders as bold text:
See here, some <strong>emphasized text</strong>.
_x000D_
Or you can use the font-weight
css property to style any element's text as bold:
span { font-weight: bold; }
_x000D_
<p>This is a paragraph of <span>bold text</span>.</p>
_x000D_
@Krytox answer with MVVM
<DataGrid
Grid.Column="1"
Grid.Row="1"
Margin="10" Grid.RowSpan="2"
ItemsSource="{Binding Data_Table}"
SelectedItem="{Binding Select_Request, Mode=TwoWay}" SelectionChanged="DataGrid_SelectionChanged"/>//The binding
#region View Model
private DataRowView select_request;
public DataRowView Select_Request
{
get { return select_request; }
set
{
select_request = value;
OnPropertyChanged("Select_Request"); //INotifyPropertyChange
OnSelect_RequestChange();//do stuff
}
}
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
from a table?
You can use this if you have no foreign keys to other tables
truncate table TableName
or
delete TableName
if you want all tables
sp_msforeachtable 'delete ?'
Most code I've seen is camelCase
functions (lower case initial letter), and ProperCase/PascalCase
class names, and (most usually), snake_case
variables.
But, to be honest, this is all just guidance. The single most important thing is to be consistent across your code base. Pick what seems natural / works for you, and stick to it. If you're joining a project in progress, follow their standards.
See the String method trim()
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim
var myString = ' bunch of <br> string data with<p>trailing</p> and leading space ';
myString = myString.trim();
// or myString = String.trim(myString);
Edit
As noted in other comments, it is possible to use the regex approach. The trim
method is effectively just an alias for a regex:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.
ECMAScript 6 introduces String.prototype.includes
, previously named contains
.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
What I did was first I installed python 3.7
brew install python3
brew unlink python
then I installed python 3.6.5 using above link
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb --ignore-dependencies
After that I ran brew link --overwrite python
. Now I have all pythons in the system to create the virtual environments.
mian@tdowrick2~ $ python --version
Python 2.7.10
mian@tdowrick2~ $ python3.7 --version
Python 3.7.1
mian@tdowrick2~ $ python3.6 --version
Python 3.6.5
To create Python 3.7 virtual environment.
mian@tdowrick2~ $ virtualenv -p python3.7 env
Already using interpreter /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7'
New python executable in /Users/mian/env/bin/python3.7
Also creating executable in /Users/mian/env/bin/python
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.7.1
(env) mian@tdowrick2~ $ deactivate
To create Python 3.6 virtual environment
mian@tdowrick2~ $ virtualenv -p python3.6 env
Running virtualenv with interpreter /usr/local/bin/python3.6
Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/mian/env/bin/python3.6
Not overwriting existing python script /Users/mian/env/bin/python (you must use /Users/mian/env/bin/python3.6)
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.6.5
(env) mian@tdowrick2~ $
I like Pointy's between
function so I wrote a similar one that worked well for my scenario.
/**
* Checks if an integer is within ±x another integer.
* @param {int} op - The integer in question
* @param {int} target - The integer to compare to
* @param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
so if you wanted to see if x
was within ±10 of y
:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
I'm using it for detecting a long-press on mobile:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
For testing only two values, I'd personally do this:
if x ~= 0 and x ~= 1 then
print( "X must be equal to 1 or 0" )
return
end
If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:
choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}
if not choices[x] then
print("x must be in the first six prime numbers")
return
end
Focus doesn't work on divs by default. But, according to this, you can make it work:
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (
<input>
,<select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
According to Django documentation, inline formsets are for this purpose: "Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".
See https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
If you use DisplayFor
, then you have to either define the format via the DisplayFormat
attribute or use a custom display template. (A full list of preset DisplayFormatString
's can be found here.)
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }
Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml
:
@model DateTime?
@if (Model.HasValue)
{
@Model.Value.ToString("MM/dd/yyyy")
}
That will apply to all DateTime
s, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml
and the DataType
attribute on your property:
[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }
The final option is to not use DisplayFor
and instead render the property directly:
@if (Model.AuditDate.HasValue)
{
@Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
You could write your own GridWithMargin
class, inherited from Grid
, and override the ArrangeOverride
method to apply the margins
From the man page:
Sending mail
To send a message to one or more people, mailx can be invoked with arguments which are the names of people to whom the mail will be sent. The user is then expected to type in his message, followed by an ‘control-D’ at the beginning of a line.
In other words, mailx reads the content to send from standard input and can be redirected to like normal. E.g.:
ls -l $HOME | mailx -s "The content of my home directory" [email protected]
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
thanks to Greenchiu
netsh http show urlacl
The command is mentioned in a previous comment but I'd like to bring it up as an answer. It will get you all reserved URLs in the system. If you look through all records with "80" in URL, you shall have your answer.
For example, in my case, I got:
Reserved URL: http://+:80/Temporary_Listen_Addresses/
User: \Everyone
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;WD)
Reserved URL: http://+:80/0131501b-d67f-491b-9a40-c4bf27bcb4d4/
User: NT AUTHORITY\NETWORK SERVICE
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;NS)
After a quick Google search, I learnt that "NT AUTHORITY\NETWORK SERVICE" belongs to SQL Server. So I went to Services and stopped SQL Server Reporting Service, port 80 is free again as I check netstat -a -b
#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */
orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));
..
The following steps solved the problem for me. I was having the issue where it was not compiling for the device or archiving, working fine for simulator.
Clean and build after doing the above steps and everything works fine now.
I come from a stripped down KDE background and do not have access to xclip
, xsel
or the other fancy stuff. I have a TCSH Konsole to make matters worse.
Requisites: qdbus
klipper
xargs
bash
Create a bash executable foo.sh
.
#!/bin/bash
qdbus org.kde.klipper /klipper setClipboardContents "$1" > /dev/null
Note: This needs to be bash as TCSH does not support multi-line arguments.
Followed by a TCSH alias in the.cshrc
.
alias clipboard xargs -0 /path/to/foo
Explanation:
xargs -0
pipes stdin into a single argument. This argument is passed to the bash executable which sends a "copy to clipboard" request to klipper
using qdbus
. The pipe to /dev/null
is to not print the newline character returned by qdbus
to the console.
Example Usage:
ls | clipboard
This copies the contents of the current folder into the clipboard.
Note: Only works as a pipe. Use the bash executable directly if you need to copy an argument.
The Win32_Process
class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.
If this is not an option for you, you can try using the taskkill
command:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000
' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
@fooMonster article worked for me
# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe script.sh
As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:
# git update-index --chmod=+x script.sh
commit the changes
# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh
map
creates a new list by applying a function to every element of the source:
xs = [1, 2, 3]
# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
ys.append(x * 2)
n-ary map
is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:
xs = [1, 2, 3]
ys = [2, 4, 6]
def f(x, y):
return (x * 2, y // 2)
# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
zs.append(f(x, y))
I've used zip
here, but map
behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None
.
This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException
, and the fix is not found anywhere else so I thought I'd add an answer here.
java.net.UnknownHostException: google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
...
No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.
Not calling trim()
for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":")
by semicolons for the HOST
header. This left whitespace, and causes the UnknownHostException
as a host with whitespace is not a valid host. Doing a host = host.trim()
on the String host
solved the ambiguous issue.
Update Answer I added android:windowIsTranslucent
in case you have white screen in start of activity
just create new Style in values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- to hide white screen in start of window -->
<item name="android:windowIsTranslucent">true</item>
</style>
</resources>
from your AndroidManifest.xml add style to your activity
android:theme="@style/AppTheme"
to be like this
<activity android:name=".Splash"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You need to specify the domain:
$('.button1').click(function() {
window.location = 'www.example.com/index.php?id=' + this.id;
});
The recommended way in Python 3.5 and above is to use subprocess.run()
:
from subprocess import run
output = run("pwd", capture_output=True).stdout
I realize I'm a little late to the conversation, but I encountered the exact same issue In my git config I had two entries credentials…
In my .gitconfig file
[credential]
helper = cached
[credentials]
helper = wincred
The Fix: Changed my .gitconfig file to the settings below
[credential]
helper = wincred
[credentials]
helper = wincred
The ones I can think of are
def foo(l: List[Option[_]]) = ...
case class A[K[_],T](a: K[T])
val _ = 5
List(1, 2, 3) foreach { _ => println("Hi") }
trait MySeq { _: Seq[_] => }
Some(5) match { case Some(_) => println("Yes") }
"abc" match { case s"a$_c" => }
C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }
import java.util._
import java.util.{ArrayList => _, _}
def bang_!(x: Int) = 5
def foo_=(x: Int) { ... }
List(1, 2, 3) map (_ + 2)
List(1, 2, 3) foreach println _
def toFunction(callByName: => Int): () => Int = callByName _
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_)
and foo _
are different:
This example comes from 0__:
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _
represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A
that will give the type (_ => Unit) => ?
(Existential _
is not a type).
In the second case, process(_)
is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach
expects, and _ => Unit
is a type (whereas just plain _
isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
This worked better for me:
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
Assume time column is in timestamp integer msec format
1 day = 86400000 ms
Here you go:
day_divider = 86400000
df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
Actions
ADD_PRODUCT : (context,product) => {
return Axios.post(uri, product).then((response) => {
if (response.status === 'success') {
context.commit('SET_PRODUCT',response.data.data)
}
return response.data
});
});
Component
this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
if (res.status === 'success') {
// write your success actions here....
} else {
// write your error actions here...
}
})
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
To expand on the above answers, the following can be used to remove multiple elements from an array, without partial matching:
ARRAY=(one two onetwo three four threefour "one six")
TO_REMOVE=(one four)
TEMP_ARRAY=()
for pkg in "${ARRAY[@]}"; do
for remove in "${TO_REMOVE[@]}"; do
KEEP=true
if [[ ${pkg} == ${remove} ]]; then
KEEP=false
break
fi
done
if ${KEEP}; then
TEMP_ARRAY+=(${pkg})
fi
done
ARRAY=("${TEMP_ARRAY[@]}")
unset TEMP_ARRAY
This will result in an array containing: (two onetwo three threefour "one six")
System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.
It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
I ran into this issue by being a bit silly. I use nvm to manage my different versions of node, and installed react-native into a version of node that was not my default. Upon opening a new shell, I lost my command. :) Switching back of course fixed things.
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
I had this problem when trying to delete a certain group of records (using MS Access 2007 with an ODBC connection to MySQL on a web server). Typically I would delete certain records from MySQL then replace with updated records (cascade delete several related records, this streamlines deleting all related records for a single record deletion).
I tried to run through the operations available in phpMyAdmin for the table (optimize,flush, etc), but I was getting a need permission to RELOAD error when I tried to flush. Since my database is on a web server, I couldn't restart the database. Restoring from a backup was not an option.
I tried running delete query for this group of records on the cPanel mySQL access on the web. Got same error message.
My solution: I used Sun's (Oracle's) free MySQL Query Browser (that I previously installed on my computer) and ran the delete query there. It worked right away, Problem solved. I was then able to once again perform the function using the Access script using the ODBC Access to MySQL connection.
Assign your image to a string. Eg image Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));
In my case, the solution was to remove "" (quotation mark) from commit message. Weird
Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.
Yes you can which is Peer-To-Peer Mode
Peer-To-Peer Mode
Bidirectional P2P connection to exchange data between devices
–Proximity triggered interactions
–Nexus S: Devices have to be placed back-to-back
Example of Applications
–Exchange of vCards
–Hand-over of Tickets & P2P Payment
–Web-page sharing, Youtube-video-sharing
–Application sharing
data = pd.read_csv('your_dataset.tsv', delimiter = '\t', quoting = 3)
You can use a delimiter to separate data, quoting = 3 helps to clear quotes in datasst
Specify negative value to spread value. This works for me:
box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);
This seems to work for me:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
You can do it using type:
type"C:\<Directory containing files>\*.txt"> merged.txt
all the files in the directory will be appendeded to the file merged.txt
.
I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.
It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR
warning and problem at starting Firefox using Xfvb.
After adding +extension RANDR
it worked again.
$ vim /etc/init/xvfb.conf
#!upstart
description "Xvfb Server as a daemon"
start on filesystem and started networking
stop on shutdown
respawn
env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid
exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1
I very like the way of Micah Henning in his article (see Setting Up Git Identities) on this subject. The fact that he apply and force the identity to each repository created/cloned is a good way not to forget to set this up each time.
Unset current user config in git:
$ git config --global --unset user.name
$ git config --global --unset user.email
$ git config --global --unset user.signingkey
Force identity configuration on each new local repository:
$ git config --global user.useConfigOnly true
Create Git alias for identity
command, we will use later:
$ git config --global alias.identity '! git config user.name "$(git config user.$1.name)"; git config user.email "$(git config user.$1.email)"; git config user.signingkey "$(git config user.$1.signingkey)"; :'
Create an identity with GPG (use gpg
or gpg2
depending on what you got on your system). Repeat next steps for each identities you want to use.
Note:
[keyid]
here is the identifier of created secret key. Example here:sec rsa4096/8A5C011E4CE081A5 2020-06-09 [SC] [expires: 2021-06-09] CCC470AE787C057557F421488C4C951E4CE081A5 uid [ultimate] Your Name <youremail@domain> ssb rsa4096/1EA965889861C1C0 2020-06-09 [E] [expires: 2021-06-09]
The
8A5C011E4CE081A5
part aftersec rsa4096/
is the identifier of key.
$ gpg --full-gen-key
$ gpg --list-secret-keys --keyid-format LONG <youremail@domain>
$ gpg --armor --export [keyid]
Copy the public key block and add it to your GitHub/GitProviderOfChoice settings as a GPG key.
Add identity to Git config. Also repeat this for each identity you want to add:
Note: here I use
gitlab
to name my identity, but from your question it can be anything, ex:gitolite
orgithub
,work
, etc.
$ git config --global user.gitlab.name "Your Name"
$ git config --global user.gitlab.email "youremail@domain"
$ git config --global user.gitlab.signingkey [keyid]
If a new repo has no identity associated, an error will appear on commit, reminding you to set it.
*** Please tell me who you are.
## parts of message skipped ##
fatal: no email was given and auto-detection is disabled
Specify the identity you want on a new repository:
$ git identity gitlab
You're now ready to commit with the gitlab identity.
Not exactly an answer to the quoting/escaping problem of the original question but probably something that would actually have been more useful for the op:
unset FILES
for f in 2011-*.jpg; do FILES+=("$f"); done
echo "${FILES[@]}"
Where of course the expression would have to be adopted to the specific requirement (e.g. *.jpg
for all or 2001-09-11*.jpg
for only the pictures of a certain day).
print df.to_string(index=False)
print(df.to_string(index=False))
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
ADD:
LIMIT n,1
That will limit the results to one result starting at result n.
I have some code for this online. It's much nicer than the other suggestions; definitely check it out.
Sample usage:
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
// You could use "() =>" in place of "delegate"; it's a style choice.
this.Invoke(delegate
{
// Do the dirty work of my method here.
});
}
The issue is that you branched off a branch off of.... where you are trying to rebase to. You can't rebase to a branch that does not contain the commit your current branch was originally created on.
I got this when I first rebased a local branch X to a pushed one Y, then tried to rebase a branch (first created on X) to the pushed one Y.
Solved for me by rebasing to X.
I have no problem rebasing to remote branches (potentially not even checked out), provided my current branch stems from an ancestor of that branch.
Every class or interface can be used as a type in TypeScript.
const date = new Date();
will already know about the date
type definition as Date
is an internal TypeScript object referenced by the DateConstructor interface.
And for the constructor you used, it is defined as:
interface DateConstructor {
new(): Date;
...
}
To make it more explicit, you can use:
const date: Date = new Date();
You might be missing the type definitions though, the Date
is coming for my example from the ES6 lib, and in my tsconfig.json
I have defined:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"dom"
],
You might adapt these settings to target your wanted version of JavaScript.
The Date is by the way an Interface from lib.es6.d.ts
:
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;
/** Gets the month of a Date object using Universal Coordinated Time (UTC). */
getUTCMonth(): number;
/** Gets the day-of-the-month, using local time. */
getDate(): number;
/** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
getUTCDate(): number;
/** Gets the day of the week, using local time. */
getDay(): number;
/** Gets the day of the week using Universal Coordinated Time (UTC). */
getUTCDay(): number;
/** Gets the hours in a date, using local time. */
getHours(): number;
/** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
getUTCHours(): number;
/** Gets the minutes of a Date object, using local time. */
getMinutes(): number;
/** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
getUTCMinutes(): number;
/** Gets the seconds of a Date object, using local time. */
getSeconds(): number;
/** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
getUTCSeconds(): number;
/** Gets the milliseconds of a Date, using local time. */
getMilliseconds(): number;
/** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
getUTCMilliseconds(): number;
/** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
getTimezoneOffset(): number;
/**
* Sets the date and time value in the Date object.
* @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
*/
setTime(time: number): number;
/**
* Sets the milliseconds value in the Date object using local time.
* @param ms A numeric value equal to the millisecond value.
*/
setMilliseconds(ms: number): number;
/**
* Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
* @param ms A numeric value equal to the millisecond value.
*/
setUTCMilliseconds(ms: number): number;
/**
* Sets the seconds value in the Date object using local time.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setSeconds(sec: number, ms?: number): number;
/**
* Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCSeconds(sec: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using local time.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the hour value in the Date object using local time.
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the hours value in the Date object using Universal Coordinated Time (UTC).
* @param hours A numeric value equal to the hours value.
* @param min A numeric value equal to the minutes value.
* @param sec A numeric value equal to the seconds value.
* @param ms A numeric value equal to the milliseconds value.
*/
setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the numeric day-of-the-month value of the Date object using local time.
* @param date A numeric value equal to the day of the month.
*/
setDate(date: number): number;
/**
* Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
* @param date A numeric value equal to the day of the month.
*/
setUTCDate(date: number): number;
/**
* Sets the month value in the Date object using local time.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
*/
setMonth(month: number, date?: number): number;
/**
* Sets the month value in the Date object using Universal Coordinated Time (UTC).
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
*/
setUTCMonth(month: number, date?: number): number;
/**
* Sets the year of the Date object using local time.
* @param year A numeric value for the year.
* @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
* @param date A numeric value equal for the day of the month.
*/
setFullYear(year: number, month?: number, date?: number): number;
/**
* Sets the year value in the Date object using Universal Coordinated Time (UTC).
* @param year A numeric value equal to the year.
* @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
* @param date A numeric value equal to the day of the month.
*/
setUTCFullYear(year: number, month?: number, date?: number): number;
/** Returns a date converted to a string using Universal Coordinated Time (UTC). */
toUTCString(): string;
/** Returns a date as a string value in ISO format. */
toISOString(): string;
/** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
toJSON(key?: any): string;
}
I just want to share the fact that my apk file was saved to my app "Data" directory and that I needed to change the permissions on the apk file to be world readable in order to allow it to be installed that way, otherwise the system was throwing "Parse error: There is a Problem Parsing the Package"; so using solution from @Horaceman that makes:
File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
If you want to rename multiple files in a single command - let's say you want to convert all *.txt
files - here is the command:
find . -name "*.txt" -exec iconv -f WINDOWS-1252 -t UTF-8 {} -o {}.ren \; -a -exec mv {}.ren {} \;
Adding the JsonProperty also ensures safety in case someone decides they want to change one of the property names not realizing the class in question will be serialized to a Json object. If they change the property name the JsonProperty ensures it will be used in the Json object, and not the property name.
I've just installed the latest idea verion 2108.1 and found this issue, after installed lombok plugin and restart the Idea resolve it.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.
When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.
Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.
We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.
I don't know if my example is clear enough? This is a real life example.
This works for me:
psql -h localhost -U postgres
there is a chrome extension 200ok its a web server for chrome just add that and select your folder