the only thing you can do is to change your signature to
public static <E> E[] appendToArray(E[] array, E item)
Important details:
Generic expressions preceding the return value always introduce (declare) a new generic type variable.
Additionally, type variables between types (ArrayUtils
) and static methods (appendToArray
) never interfere with each other.
So, what does this mean:
In my answer <E>
would hide the E
from ArrayUtils<E>
if the method wouldn't be static
. AND <E>
has nothing to do with the E
from ArrayUtils<E>
.
To reflect this fact better, a more correct answer would be:
public static <I> I[] appendToArray(I[] array, I item)
mongod --dbpath [path_to_data_directory]
if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")
Browser should report request timeout error.
You may do 2 things:
Based on CGI/Server side engine increase timeout there
PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds
In php.ini:
max_execution_time 60
Increase apache timeout - default is 300 (in version 2.4 it is 60).
In your httpd.conf (in server config or vhost config)
TimeOut 600
Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.
Second setting modify maximum amount of time the server will wait for certain events before failing a request
Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.
I had a similar problem with IndentationError in PyCharm.
I could not find any tabs in my code, but once I deleted code AFTER the line with the IndentationError, all was well.
I suspect that you had a tab in the following line:
sex = sex if not sex == 2 else random.randint(0,1)
Using the PHPExcel library to read an Excel file and transfer the data into a database
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
$inputFileName = './sampleData/example1.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Anything more becomes very dependent on your database, and how you want the data structured in it
One easy solution is to use overflow
values other than visible
to make the text flex basis width reset as expected.
Here with value auto
the text wraps as expected and the article content does not overflow main container.
Also, the article flex
value must either have a auto
basis AND be able to shrink, OR, only grow AND explicit 0
basis
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
/* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
xcopy.exe
is the solution here. It's built into Windows.
xcopy /s c:\Folder1 d:\Folder2
You can find more options at http://www.computerhope.com/xcopyhlp.htm
If you can't just limit the query itself with a where
clause, you can use the fact that the count
aggregate only counts the non-null values:
select count(case Position when 'Manager' then 1 else null end)
from ...
You can also use the sum
aggregate in a similar way:
select sum(case Position when 'Manager' then 1 else 0 end)
from ...
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
In your case the appropriate method to use is pop, because it takes the index to be removed:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
It ignores the cached content when refreshing...
https://support.google.com/a/answer/3001912?hl=en
F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content
Try setting core.autocrlf value like this :
git config --global core.autocrlf true
git rev-parse --short HEAD
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
Maybe more clear:
Note that precision is the total number of digits, scale included
NUMBER(Precision,Scale)
Precision 8, scale 3 : 87654.321
Precision 5, scale 3 : 54.321
Precision 5, scale 1 : 5432.1
Precision 5, scale 0 : 54321
Precision 5, scale -1: 54320
Precision 5, scale -3: 54000
The error is try to fix a Youtube error.
The solution to avoid your Javascript-Console-Error complex is to accept that Youtube (and also other webpages) can have Javascript errors that you can't fix.
That is all.
A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.
+------------------+----------------------+
| Name Begins With | Variable Scope |
+------------------+----------------------+
| $ | A global variable |
| @ | An instance variable |
| [a-z] or _ | A local variable |
| [A-Z] | A constant |
| @@ | A class variable |
+------------------+----------------------+
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
It is also possible, that the referenced projects targets .NET 4.0, while the Console App Project targets .NET 4.0 Client Library.
While it might not have been related to this particular case, I think someone else can find this information useful.
<script type="text/javascript">
$("ol li:nth-child(1)").addClass('olli1');
$("ol li:nth-child(2)").addClass("olli2");
$("ol li:nth-child(3)").addClass("olli3");
$("ol li:nth-child(4)").addClass("olli4");
$("ol li:nth-child(5)").addClass("olli5");
$("ol li:nth-child(6)").addClass("olli6");
$("ol li:nth-child(7)").addClass("olli7");
$("ol li:nth-child(8)").addClass("olli8");
$("ol li:nth-child(9)").addClass("olli9");
$("ol li:nth-child(10)").addClass("olli10");
$("ol li:nth-child(11)").addClass("olli11");
$("ol li:nth-child(12)").addClass("olli12");
$("ol li:nth-child(13)").addClass("olli13");
$("ol li:nth-child(14)").addClass("olli14");
$("ol li:nth-child(15)").addClass("olli15");
$("ol li:nth-child(16)").addClass("olli16");
$("ol li:nth-child(17)").addClass("olli17");
$("ol li:nth-child(18)").addClass("olli18");
$("ol li:nth-child(19)").addClass("olli19");
$("ol li:nth-child(20)").addClass("olli20");
</script>
change this to
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("ol li:nth-child(1)").addClass('olli1');
$("ol li:nth-child(2)").addClass("olli2");
$("ol li:nth-child(3)").addClass("olli3");
$("ol li:nth-child(4)").addClass("olli4");
$("ol li:nth-child(5)").addClass("olli5");
$("ol li:nth-child(6)").addClass("olli6");
$("ol li:nth-child(7)").addClass("olli7");
$("ol li:nth-child(8)").addClass("olli8");
$("ol li:nth-child(9)").addClass("olli9");
$("ol li:nth-child(10)").addClass("olli10");
$("ol li:nth-child(11)").addClass("olli11");
$("ol li:nth-child(12)").addClass("olli12");
$("ol li:nth-child(13)").addClass("olli13");
$("ol li:nth-child(14)").addClass("olli14");
$("ol li:nth-child(15)").addClass("olli15");
$("ol li:nth-child(16)").addClass("olli16");
$("ol li:nth-child(17)").addClass("olli17");
$("ol li:nth-child(18)").addClass("olli18");
$("ol li:nth-child(19)").addClass("olli19");
$("ol li:nth-child(20)").addClass("olli20");
});
</script>
try this code [updated]:
Scanner scan = null;
int range, smallest = 0, input;
for(;;){
boolean error=false;
scan = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
continue;
}
range = scan.nextInt();
if(range < 1) {
System.out.println("Invalid input!");
error=true;
}
if(error)
{
//do nothing
}
else
{
break;
}
}
for(int ii = 1; ii <= range; ii++) {
scan = new Scanner(System.in);
System.out.print("Enter value " + ii + ": ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
ii--;
continue;
}
}
Problem is that you are doing something wrong in XML layout file
android:text=" <- Go Back" // this creates error
android:text="Go Back" // correct way
Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select>
would do):
http://www.bootply.com/VxVlaebtnL
HTML:
<div class="container">
<div class="col-sm-7 pull-right well">
<form class="form-inline" action="#" method="get">
<div class="input-group col-sm-8">
<input class="form-control" type="text" value="" placeholder="Search" name="q">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
<ul class="dropdown-menu" id="mydropdownmenu">
<li><a href="#">Choice 1</a></li>
<li><a href="#">Choice 2</a></li>
<li><a href="#">Choice 3</a></li>
</ul>
<input type="hidden" id="mydropwodninput" name="category">
</div><!-- /btn-group -->
</div>
<button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
</form>
</div>
</div>
Jquery:
$('#mydropdownmenu > li').click(function(e){
e.preventDefault();
var selected = $(this).text();
$('#mydropwodninput').val(selected);
$('#mydropdowndisplay').text(selected);
});
Replace this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">
with
<button value=" Send" class="btn btn-success" type="submit" id="submit">
I had this issue recently and I resolved it by simply rolling IE8 back to IE7.
My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.
Your submodule history is safely preserved in the submodule git anyway.
So, why not just delete the submodule and add it again?
Otherwise, did you try manually editing the HEAD
or the refs/master/head
within the submodule .git
for alamofire 4 use this ..
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(fileUrl, withName: "video")
//fileUrl is your file path in iOS device and withName is parameter name
}, to:"http://to_your_url_path")
{ (result) in
switch result {
case .success(let upload, _ , _):
upload.uploadProgress(closure: { (progress) in
print("uploding")
})
upload.responseJSON { response in
print("done")
}
case .failure(let encodingError):
print("failed")
print(encodingError)
}
}
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
After looking on Super User I found this question which explains how to do this with the shortcut on the start screen. Similarly you can do the same when Visual Studio is pinned to the task bar. In either location:
Properties
Shortcut tab
select Advanced
Run as administrator
Unlike in Windows 7 this only works if you launch the application from the shortcut you changed. After updating both Visual Studio shortcuts it seems to also work when you open a solution file from Explorer.
Update Warning:
It looks like one of the major flaws in running Visual Studio with elevated permissions is since Explorer isn't running with them as well you can't drag and drop files into Visual Studio for editing. You need to open them through the file open dialog. Nor can you double click any file associated to Visual Studio and have it open in Visual Studio (aside from solutions it seems) because you'll get an error message saying There was a problem sending the command to the program.
Once I uncheck to always start with elevated permissions (using VSCommands) then I'm able to open files directly and drop them into an open instance of Visual Studio.
Update For The Daring: Despite there being no UI to turn off UAC like in the past, that I saw at least, you can still do so through the registry. The key to edit is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
EnableLUA - DWORD 1-Enabled, 0-Disabled
After changing this Windows will prompt you to restart. Once restarted you'll be back to everything running with admin permissions if you're an admin. The issues I reported above are now gone as well.
Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc
, it is also possible to check them using sysctl
(Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):
sysctl net.ipv4.tcp_rmem
sysctl net.ipv4.tcp_wmem
However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss
command (part of the iproute
package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t
option) sockets and associated memory (m
) information:
ss -tm
Here's some example output:
State Recv-Q Send-Q Local Address:Port Peer Address:Port
ESTAB 0 0 192.168.56.102:ssh 192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)
Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):
r:sk_rmem_alloc rb:sk_rcvbuf # current receive buffer size t:sk_wmem_alloc tb:sk_sndbuf # current transmit buffer size f:sk_forward_alloc w:sk_wmem_queued # persistent transmit queue size o:sk_omem_alloc bl:sk_backlog d:sk_drops
I believe you also have to use .detach()
. I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. I did it like the following:
# this is just my embedding matrix which is a Torch tensor object
embedding = learn.model.u_weight
embedding_list = list(range(0, 64382))
input = torch.cuda.LongTensor(embedding_list)
tensor_array = embedding(input)
# the output of the line below is a numpy array
tensor_array.cpu().detach().numpy()
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.
1) Put =Left(E1,5)
in F1
2) Copy F1
, then select entire F
column and paste.
this is variation of Dennis method, looks more elegant in the scripts.
function definition:
define(){ IFS='\n' read -r -d '' ${1} || true; }
usage:
define VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
echo "$VAR"
enjoy
p.s. made a 'read loop' version for shells that do not support read -d
. should work with set -eu
and unpaired backticks, but not tested very well:
define(){ o=; while IFS="\n" read -r a; do o="$o$a"'
'; done; eval "$1=\$o"; }
For Access 2010 - multiple steps required; I followed the same pattern as posted above, but thought I could help someone in Access. Worked great for me, I didn't have to keep a seeded table of dates.
Create a table called DUAL (similar to how the Oracle DUAL table works)
Create a query named "ZeroThru9Q"; manually enter the following syntax:
SELECT 0 AS a
FROM dual
UNION ALL
SELECT 1
FROM dual
UNION ALL
SELECT 2
FROM dual
UNION ALL
SELECT 3
FROM dual
UNION ALL
SELECT 4
FROM dual
UNION ALL
SELECT 5
FROM dual
UNION ALL
SELECT 6
FROM dual
UNION ALL
SELECT 7
FROM dual
UNION ALL
SELECT 8
FROM dual
UNION ALL
SELECT 9
FROM dual;
Create a query named "TodayMinus1KQ" (for dates before today); manually enter the following syntax:
SELECT date() - (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
FROM
(SELECT *
FROM ZeroThru9Q) AS a,
(SELECT *
FROM ZeroThru9Q) AS b,
(SELECT *
FROM ZeroThru9Q) AS c
Create a query named "TodayPlus1KQ" (for dates after today); manually enter the following syntax:
SELECT date() + (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
FROM
(SELECT *
FROM ZeroThru9Q) AS a,
(SELECT *
FROM ZeroThru9Q) AS b,
(SELECT *
FROM ZeroThru9Q) AS c;
Create a union query named "TodayPlusMinus1KQ" (for dates +/- 1000 days):
SELECT MyDate
FROM TodayMinus1KQ
UNION
SELECT MyDate
FROM TodayPlus1KQ;
Now you can use the query:
SELECT MyDate
FROM TodayPlusMinus1KQ
WHERE MyDate BETWEEN #05/01/2014# and #05/30/2014#
You can also put the files or links into the root of the solution explorer and then set the files properties:
Build action = Content
and
Copy to Output Directory = Copy if newer
(for example)
For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.
Check your code for errors in my case i had an error in Kernel.php. First solve errors if any Than run composer require ....(package you wish)
android studio 4.1.1
applicationVariants.all { variant ->
variant.outputs.all { output ->
def reversion = "118"
def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
def versionName = defaultConfig.versionName
outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
}
}
Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch()
elsewhere. More like repeatedly creating the stubs of the same method.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.
Consider the below Test Class for example:
@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
@Mock
Service1 svc1Mock1;
@Mock
Service2 svc2Mock2;
@InjectMock
TestClass class;
//Assume you have many dependencies and you want to set up all the stubs
//in one place assuming that all your tests need these stubs.
//I know that any initialization code for the test can/should be in a
//@Before method. Lets assume there is another method just to create
//your stubs.
public void setUpRequiredStubs() {
when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
}
@Test
public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
// You forget that you defined the stub for svcMock1.someMethod or
//thought you could redefine it. Well you cannot. That's going to be
//a problem and would throw your UnnecessaryStubbingException.
when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
setUpRequiredStubs();
}
}
I would rather considering refactoring your tests to stub where necessary.
If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:
#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN
TL;DR: use one PNG icon at 180 x 180 px @ 150 ppi and then link to it like this:
<link rel="apple-touch-icon" href="path/to/apple-touch-icon.png">
As of 2020-04, the canonical response from Apple is reflected in their documentation on iOS.
Officially, the spec says:
In reality, these sizing differences are tiny, so the performance savings will really only matter on very high traffic sites.
For lower traffic sites, I typically use one PNG icon at 180 x 180 px @ 150 ppi and get very good results on all devices, even the plus sized ones.
Try this:
text-overflow: ellipsis;
overflow: hidden;
white-space:nowrap;
Had peno's version optimised a bit. The increase in performance is perceptible.
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
if you use pg_dump with -Fp to backup in plain text format, use following command:
cat db.txt | psql dbname
to copy all data to your database with name dbname
Firstly a quick recap on RSA key generation.
The public key consists of the modulus and the public exponent.
A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.
However:
So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.
Both join()
and concat()
way could solve the problem. However, there is one warning I have to mention: Reset the index before you join()
or concat()
if you trying to deal with some data frame by selecting some rows from another DataFrame.
One example below shows some interesting behavior of join and concat:
dat1 = pd.DataFrame({'dat1': range(4)})
dat2 = pd.DataFrame({'dat2': range(4,8)})
dat1.index = [1,3,5,7]
dat2.index = [2,4,6,8]
# way1 join 2 DataFrames
print(dat1.join(dat2))
# output
dat1 dat2
1 0 NaN
3 1 NaN
5 2 NaN
7 3 NaN
# way2 concat 2 DataFrames
print(pd.concat([dat1,dat2],axis=1))
#output
dat1 dat2
1 0.0 NaN
2 NaN 4.0
3 1.0 NaN
4 NaN 5.0
5 2.0 NaN
6 NaN 6.0
7 3.0 NaN
8 NaN 7.0
#reset index
dat1 = dat1.reset_index(drop=True)
dat2 = dat2.reset_index(drop=True)
#both 2 ways to get the same result
print(dat1.join(dat2))
dat1 dat2
0 0 4
1 1 5
2 2 6
3 3 7
print(pd.concat([dat1,dat2],axis=1))
dat1 dat2
0 0 4
1 1 5
2 2 6
3 3 7
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
What you're looking for is
[ConditionalAttribute("DEBUG")]
attribute.
If you for instance write a method like :
[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
Console.WriteLine("This message was brought to you by your debugger : ");
Console.WriteLine(message);
}
any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.
Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
A better solution is to use the array_filter
function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
Simple Solution: Rather then cloning via https, clone it via ssh.
For example:
git clone https://github.com/vaibhavjain2/xxx.git - Avoid
git clone [email protected]:vaibhavjain2/xxx.git - Correct
From Overview of Numeric Types;
BIT[(M)]
A bit-field type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted.
This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, BDB, and NDBCLUSTER. Before 5.0.3, BIT is a synonym for TINYINT(1).
TINYINT[(M)] [UNSIGNED] [ZEROFILL]
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
Additionally consider this;
BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
Set libraries search path first:
LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)
And then just do
TARGET_LINK_LIBRARIES(GLBall mylib)
you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.
Another answer that I'm using on 2.7 where I'm just printing out a "." every time a loop runs (to indicate to the user that things are still running) is this:
print "\b.",
It prints the "." characters without spaces between each. It looks a little better and works pretty well. The \b is a backspace character for those wondering.
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
//decode base64 string to image
imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
//setImageBitmap is imp
$order = new WC_Order(get_query_var('order-received'));
If all you want is to request the URL and if it needs to be done from batch file, without anything outside of the OS, this can help you:
@if (@This==@IsBatch) @then
@echo off
rem **** batch zone *********************************************************
setlocal enableextensions disabledelayedexpansion
rem The batch file will delegate all the work to the script engine
if not "%~1"=="" (
wscript //E:JScript "%~dpnx0" %1
)
rem End of batch file area. Ensure the batch file ends execution
rem before reaching the JavaScript zone
exit /b
@end
// **** JavaScript zone *****************************************************
// Instantiate the needed component to make URL queries
var http = WScript.CreateObject('Msxml2.XMLHTTP.6.0');
// Retrieve the URL parameter
var url = WScript.Arguments.Item(0)
// Make the request
http.open("GET", url, false);
http.send();
// All done. Exit
WScript.Quit(0);
It is just a hybrid batch/JavaScript file and is saved as callurl.cmd
and called as callurl "http://www.google.es"
. It will do what you ask for. No error check, no post, just a skeleton.
If it is possible to use something outside of the OS, wget
or curl
are available as Windows executables and are the best options available.
If you are limited by some kind of security policy, you can get the Internet Information Services (IIS) 6.0 Resource Kit Tools. It includes tinyget
and wfetch
tools that can do what you need.
I could get this error working with UnsafeMutablePointer
let ptr = rawptr.assumingMemoryBound(to: A.self) //<-- wrong A.self Change it to B.Self
ptr.pointee = B()
In your operation in your initial question, you are performing the following operation:
item1.attr - item2.attr
So, assuming those are numbers (i.e. item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. The following should work:
return parseInt(item1.attr) - parseInt(item2.attr);
If they are alphaNumeric, then do use localCompare().
Here is benchmark of several methods converting arguments into array.
As for me, the best solution for small amount of arguments is:
function sortArgs (){
var q = [];
for (var k = 0, l = arguments.length; k < l; k++){
q[k] = arguments[k];
}
return q.sort();
}
For other cases:
function sortArgs (){ return Array.apply(null, arguments).sort(); }
only css, quite simple I find it:
.checkmark {_x000D_
display: inline-block;_x000D_
transform: rotate(45deg);_x000D_
height: 25px;_x000D_
width: 12px;_x000D_
margin-left: 60%; _x000D_
border-bottom: 7px solid #78b13f;_x000D_
border-right: 7px solid #78b13f;_x000D_
}
_x000D_
<div class="checkmark"></div>
_x000D_
Here is my solution:
public static String encode(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
public static void main(String [] args) throws Exception {
System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}
Or you can return the hash encoded in Base64:
Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
The output in hex is as expected:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.
<VirtualHost *:80>
DocumentRoot /var/www/html
</VirtualHost>
Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost
PUT => Set all new attributes for an existing resource.
PATCH => Partially update an existing resource (not all attributes required).
You can try
$("your_div_id").remove();
or
$("your_div_id").html("");
try to use following query
select *
from xxx
where convert(date,dates) >= '2012-10-26' and convert(date,dates) <= '2012-10-27'
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
You can use the date.timetuple()
method and unpack operator *
.
args = d.timetuple()[:6]
datetime.datetime(*args)
function image()
{
//dynamically add an image and set its attribute
var img=document.createElement("img");
img.src="p1.jpg"
img.id="picture"
var foo = document.getElementById("fooBar");
foo.appendChild(img);
}
<span id="fooBar"> </span>
I got the OP's link error about rc.exe
when trying to execute pip install
inside a bash
task within an Azure DevOps pipeline that I was using to build a Python package from source with C++ extensions. I was able to resolve it by adding the path to rc.exe
inside the bash
task just before calling pip install
, like so:
PATH="/c/Program Files (x86)/Windows Kits/10/bin/10.0.18362.0/x64":$PATH
That was inside an Azure job
that was using vmImage: 'windows-2019'
for its agent; i.e., Windows Server 2019 with Visual Studio 2019.
In my case, the correct menu path was:
File > Default settings > Project Interpreter
Add Content-Type: application/json
and Accept: application/json
in REST Client header section
You don't need these two assigments:
cString1 = strToLower(cString1);
cString2 = strToLower(cString2);
you are modifying the strings in place.
Warnings are because you are returning a char, and assigning to a char[] (which is equivalent to char*)
Another method is to place a png behind the UILabel. I have views with several labels that overlay a single background png that has all the artwork for the individual labels.
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:
Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String
numSheets = 0
For Each ws In Application.ActiveWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
Sheets.Add.Name = "Sheet1"
End If
Next
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show = -1 Then 'Any file is selected
MyString = .SelectedItems.Item(1)
Else ' else dialog is cancelled
MsgBox "You have cancelled the dialogue"
[filePath] = "" ' when cancelled set blank as file path.
End If
End With
LString = Range("A1").Value
dashpos = InStr(1, LString, "\") + 1
LArray = Split(LString, "\")
'MsgBox LArray(dashpos - 1)
FileName = LArray(dashpos)
strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & FileName
Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count
For x = 1 To numSheets
closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
x = x + 1
If x = numSheets Then
GoTo 1000
End If
Next
1000
closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True
End Sub
The following solution worked for me:
brew install python2
It also upgraded pip
to version 1.10.1
The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.
Some examples in Clojure.
(.scale 0.00123M) ; 5
(.precision 0.00123M) ; 3
(In Clojure, The M
designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)
You can easily increase the scale:
(.setScale 0.00123M 7) ; 0.0012300M
But you can't decrease the scale in the exact same way:
(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary
You'll need to pass a rounding mode too:
(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.
So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!
It is easy to decrease the precision:
(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M
But it is not obvious how to increase the precision:
(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)
For the skeptical, this is not just a matter of trailing zeros not being displayed:
(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6
; (same as above, still unexpected)
FWIW, Clojure is careful with trailing zeros and will show them:
4.0000M ; 4.0000M
(.precision 4.0000M) ; 5
Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:
(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M
So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?
So, best I can tell, if you want to change precision, you'll need to do these steps:
These steps, as Clojure code:
(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M
I know, this is a lot of steps just to change the precision!
Why doesn't BigDecimal already provide this? Did I overlook something?
import os
import sys
Assuming test.sh is the shell script that you would want to execute
os.system("sh test.sh")
It is to my understanding that you want to embed a video on your site that:
This Demo Here does just that. You have to place another embed class outside of the object/embed/iframe tag as per the the instructions here - but you're also able to use a video tag instead of the object tag even though it's not specified.
<div align="center" class="embed-responsive embed-responsive-16by9">
<video autoplay loop class="embed-responsive-item">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
</div>
That is not possible without intercepting addEventListener
calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.
The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.
Note: This will also remove listeners on element's children.
var el = document.getElementById('el-id'),
elClone = el.cloneNode(true);
el.parentNode.replaceChild(elClone, el);
There is a simple answer to this question which uses a dictionary of types to look up a lambda function. Here is how it might be used:
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
There is also a generalized solution to this problem in terms of pattern matching (both types and run-time checked conditions):
var getRentPrice = new PatternMatcher<int>()
.Case<MotorCycle>(bike => 100 + bike.Cylinders * 10)
.Case<Bicycle>(30)
.Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
.Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
.Default(0);
var vehicles = new object[] {
new Car { EngineType = EngineType.Diesel, Doors = 2 },
new Car { EngineType = EngineType.Diesel, Doors = 4 },
new Car { EngineType = EngineType.Gasoline, Doors = 3 },
new Car { EngineType = EngineType.Gasoline, Doors = 5 },
new Bicycle(),
new MotorCycle { Cylinders = 2 },
new MotorCycle { Cylinders = 3 },
};
foreach (var v in vehicles)
{
Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v));
}
I would write something like this:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
My way of doing things is the following
#Backup branch
git checkout -b master_backup
git push origin master_backup
git checkout master
#Hard Reset master branch to the last common commit
git reset --hard e8c8597
#Merge
git merge develop
SHOW CREATE PROCEDURE proc_name;
returns the definition of proc_name
I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html
<div class="form-group">
<label for="options">Options :</label>
<div *ngFor="let option of xyzlist">
<label>
<input type="checkbox"
name="options"
value="{{option.Id}}"
(change)="onClicked(option, $event)"/>
{{option.Id}}-- {{option.checked}}
</label>
</div>
<button type="submit">Submit</button>
</div>
** XYZ.Component.ts**.
create a list -- xyzlist.
Now to get value in Componenet.ts.
xyzlist;//Just created a list
onClicked(option, event) {
console.log("event " + this.xyzlist.length);
console.log("event checked" + event.target.checked);
console.log("event checked" + event.target.value);
for (var i = 0; i < this.xyzlist.length; i++) {
console.log("test --- " + this.xyzlist[i].Id;
if (this.xyzlist[i].Id == event.target.value) {
this.xyzlist[i].checked = event.target.checked;
}
console.log("after update of checkbox" + this.xyzlist[i].checked);
}
I'd have done it like this:
perl -e 'while (<>) {chop; $h{$_}++;} for $k (keys %h) {print "$k $h{$k}\n";}' ip_addresses
but uniq might work for you.
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Dave Webb's answer did work for me. Thanks! Here my code, hope this helps someone!
<RelativeLayout
android:background="#FFFFFF"
android:layout_width="match_parent"
android:minHeight="30dp"
android:layout_height="wrap_content">
<TextView
android:height="25dp"
android:layout_width="wrap_content"
android:layout_marginLeft="20dp"
android:text="ABA Type"
android:padding="3dip"
android:layout_gravity="center_vertical"
android:gravity="left|center_vertical"
android:layout_height="match_parent" />
<TextView
android:background="@color/blue"
android:minWidth="30px"
android:minHeight="30px"
android:layout_column="1"
android:id="@+id/txtABAType"
android:singleLine="false"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_width="wrap_content" />
</RelativeLayout>
Image: Image
this is the best way and it also gives you a clear picture of total number of commits by all the user
git shortlog -s -n
$.fn.extend({
hasClasses: function (selectors) {
var self = this;
for (var i in selectors) {
if ($(self).hasClass(selectors[i]))
return true;
}
return false;
}
});
$('#element').hasClasses(['class1', 'class2', 'class3']);
This should do it, simple and easy.
We store our URLs in a database and load them at runtime.
public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
public TChannel Create(string url)
{
this.Endpoint.Address = new EndpointAddress(new Uri(url));
return this.Channel;
}
}
Implementation
var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);
Double check if you are not able to use keys.
Otherwise use expect:
#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact
The accepted answer for this question is wrong, but I have low rep so can't add a comment to it.
The correct answer to this question is given by Mat:
shopt -s nullglob
logfiles=(*.log)
echo ${#logfiles[@]}
The problem with the accepted answer is that wc -l counts the number of newline characters, and counts them even if they print to the terminal as '?' in the output of 'ls -l'. This means that the accepted answer FAILS when a filename contains a newline character. I have tested the suggested command:
ls -l log* | wc -l
and it erroneously reports a value of 2 even if there is only 1 file matching the pattern whose name happens to contain a newline character. For example:
touch log$'\n'def
ls log* -l | wc -l
If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.
If you are looking for NA
counts for each column in a dataframe then:
na_count <-sapply(x, function(y) sum(length(which(is.na(y)))))
should give you a list with the counts for each column.
na_count <- data.frame(na_count)
Should output the data nicely in a dataframe like:
----------------------
| row.names | na_count
------------------------
| column_1 | count
Create with Resource Method
php artisan make:controller --resource ControllerName --model=ModelName
Use It With a path
php artisan make:controller --resource path/ControllerName --model=ModelName
If you are looking for a Ruby class/method I used this, and I have also included the tests:
class Binary
def self.binary_to_decimal(binary)
binary_array = binary.to_s.chars.map(&:to_i)
total = 0
binary_array.each_with_index do |n, i|
total += 2 ** (binary_array.length-i-1) * n
end
total
end
end
class BinaryTest < Test::Unit::TestCase
def test_1
test1 = Binary.binary_to_decimal(0001)
assert_equal 1, test1
end
def test_8
test8 = Binary.binary_to_decimal(1000)
assert_equal 8, test8
end
def test_15
test15 = Binary.binary_to_decimal(1111)
assert_equal 15, test15
end
def test_12341
test12341 = Binary.binary_to_decimal(11000000110101)
assert_equal 12341, test12341
end
end
WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?
Have you tried this?
ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);
This will change the col_name's type to VARCHAR(65353)
After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.
This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:
assets > testjs.js
function test(){
alert('TestingFunction')
}
include testjs.js in your index.html
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Project1</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="./assets/testjs.js"></script>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:
app.component.ts
import { Component } from '@angular/core';
declare var test: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
f(){
new test();
}
}
Finally in your app.component.html test the function
app.component.html
<h1>
<button (click)='f()'>Test</button>
</h1>
In addition to the accepted answer. You can use a lambda
instead of regex
:
from bs4 import BeautifulSoup
html = """<p>test python</p>"""
soup = BeautifulSoup(html, "html.parser")
print(soup(text="python"))
print(soup(text=lambda t: "python" in t))
Output:
[]
['test python']
If you already have git installed via homebrew, you can just do upgrade:
$ type -a git
/usr/bin/git
$ brew upgrade git
$ type -a git
/usr/local/bin/git
The one at local/bin will have gitk
With the Material Components library you can use the CircularProgressIndicator
:
Something like:
<com.google.android.material.progressindicator.CircularProgressIndicator
android:indeterminate="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:indicatorColor="@array/progress_colors"
app:indicatorSize="xxdp"
app:showAnimationBehavior="inward"/>
where array/progress_colors
is an array with the colors:
<integer-array name="progress_colors">
<item>@color/yellow_500</item>
<item>@color/blue_700</item>
<item>@color/red_500</item>
</integer-array>
Note: it requires at least the version 1.3.0
Here is an example from the matplotlib tutorial found here. This is one of the more simpler examples but I added transparency to the legend and added plt.show() so you can paste this into the interactive shell and get a result:
import matplotlib.pyplot as plt
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
p3, = plt.plot([2, 3, 1])
plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5)
plt.show()
awk '{$1=$2="";$0=$0;$1=$1}1'
Input
a b c d
Output
c d
Try this:
$('#select_all').click(function() {
$('#countries option').prop('selected', true);
});
And here's a live demo.
it will work if you put it as below:
AA='first line
\nsecond line
\nthird line'
echo $AA
output:
first line
second line
third line
I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.
I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.
Use the pdfpages
package.
\usepackage{pdfpages}
To include all the pages in the PDF file:
\includepdf[pages=-]{myfile.pdf}
To include just the first page of a PDF:
\includepdf[pages={1}]{myfile.pdf}
Run texdoc pdfpages
in a shell to see the complete manual for pdfpages
.
It's an very important improvement for npm: guarantee exact same version of every package.
How to make sure your project built with same packages in different environments in a different time? Let's say, you may use ^1.2.3
in your package.json
, or some of your dependencies are using that way, but how can u ensure each time npm install
will pick up same version in your dev machine and in the build server? package-lock.json will ensure that.
npm install
will re-generate the lock file, when on build server or deployment server, do npm ci
(which will read from the lock file, and install the whole package tree)
Storing JSON in database violates the first normal form.
The best thing you can do is to normalize and store features in another table. Then you will be able to use a much better looking and performing query with joins. Your JSON even resembles the table.
Mysql 5.7 has builtin JSON functionality:
http://mysqlserverteam.com/mysql-5-7-lab-release-json-functions-part-2-querying-json-data/
Correct pattern is:
WHERE `attribs_json` REGEXP '"1":{"value":[^}]*"3"[^}]*}'
[^}]
will match any character except }
Check this out: http://qrdroid.com/web-masters.php
You can create a link in your web form, something like:
http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}
When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
Hi I think the SimpleXml is very useful . And with it I am using xpath;
$xml = simplexml_load_file("som_xml.xml");
$blocks = $xml->xpath('//block'); //gets all <block/> tags
$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are <layout/> tags
I use many xml configs and this helps me to parse them really fast.
SimpleXml
is written on C
so it's very fast.
Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl
You can use a function to generate the template string:
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
The principles behind this in computer science is called
? extends MyClass
,? super MyClass
andMyClass
The picture below should explain the concept. Picture courtesy: Andrey Tyukin
The empty string is false as a rule.
Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.
it don't needed port and brew! because you have android sdk package.
.1 edit your .bash_profile
export ANT_HOME="[your android_sdk_path/eclipse/plugins/org.apache.ant_1.8.3.v201301120609]"
// its only my org.apache.ant version, check your org.apache.ant version
export PATH=$PATH:$ANT_HOME/bin
.2 make ant command that can executed
chmod 770 [your ANT_HOME/bin/ant]
.3 test if you see below message. that's success!
command line execute: ant
Buildfile: build.xml does not exist!
Build failed
Setting that is not that hard as mentioned in the question. Actually it's pretty simple. Try this on storyboard.
string.find("substring")
will help you. This function returns -1
when there is no substring.
strip()
is a method for strings, you are calling it on a list
, hence the error.
>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False
To do what you want, just do
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
Since, you want the elements to be in a single list (and not a list of lists), you have two options.
To do the first, follow the code:
>>> l1 = []
>>> for elem in l:
l1.extend(elem.strip().split(';'))
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
To do the second, use itertools.chain
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
However, starting in Java SE 8, a local class can access local variables and parameters of the >enclosing block that are final or effectively final.
This didn't start on Java 8, I use this since long time. This code used (before java 8) to be legal:
String str = ""; //<-- not accesible from anonymous classes implementation
final String strFin = ""; //<-- accesible
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ann = str; // <---- error, must be final (IDE's gives the hint);
String ann = strFin; // <---- legal;
String str = "legal statement on java 7,"
+"Java 8 doesn't allow this, it thinks that I'm trying to use the str declared before the anonymous impl.";
//we are forced to use another name than str
}
);
Loose Coupling is the process of giving the dependency your class needs indirectly without providing all the information of the dependency(i.e in the from of interface) in case tight coupling you directly give in the dependency which is not good way of coding.
One way is this:
select id, name, priority from table a
order by case when name='core' then -1 else priority end asc, priority asc
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.
I think in this context it means it is static in the sense that the size is fixed. Use std::vector. It has a resize() function.
I put the year and the number series of my app example 2014-01
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
Use the css "rotate()" method:
div {
width: 100px;
height: 100px;
background-color: yellow;
border: 1px solid black;
}
div#rotate{
transform: rotate(90deg);
}
_x000D_
<div>
normal div
</div>
<br>
<div id="rotate">
This div is rotated 90 degrees
</div>
_x000D_
Instead of isset()
you can use something shorter getting errors muted, it is @$_POST['field']
. Then, if the field is not set, you'll get no error printed on a page.
jQuery does only make some regexp checking before calling the native browser method window.JSON.parse()
. If that is not available, it uses eval()
or more exactly new Function()
to create a Javascript object.
The opposite of JSON.parse()
is JSON.stringify()
which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js
from http://www.json.org
JSON.stringify()
is available in all major browsers, but to be compatible with older browsers you still need that fallback.
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
There are multiple ways to create an array in shell.
ARR[0]="ABC"
ARR[1]="BCD"
echo ${ARR[*]}
${ARR[*]}
prints all elements in the array.
Second way is:
ARR=("A" "B" "C" "D" 5 7 "J")
echo ${#ARR[@]}
echo ${ARR[0]}
${#ARR[@]}
is used to count length of the array.
You have some errors in your code:
myArray[i].push( 0 );
to add a new column. Your code (myArray[i][j].push(0);
) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j]
.One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3
var rows = 8;
var cols = 7;
// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
myArray.push( [] );
}
// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
for (var j = myArray[i].length; j < cols; j++)
{
myArray[i].push(0);
}
}
Replication is not very hard to create.
Here's some good tutorials:
http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication
Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):
This way, you will avoid errors.
For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.
You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.
NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).
I would recommend to monitor your servers to make sure everything is fine.
Let me know if you need additional help
If you are not trying to reorder the array you can just do:
$array = array_reverse( $array );
$array = array_reverse( $array );
The array_reverse is very fast and it reorders as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
This is way more simpler with Maven dependency feature:
Hope this will help!
you need to call the function like this
$this->assign()
instead of just assign()
If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…
For example in one <VirtualHost>
that uses SSL add the two following directives:
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
Make sure the following apache modules are loaded (load them using a2enmod):
Obviously you'll have to change your AJAX requests url in order to use the apache proxy…
var x = '<option value="' + col + '"'
if (col == 'screwdriver') x += ' selected';
x += '>Very roomy</option>';
A bit late to the party, but be sure that you are trying to build a proper build variant. It sometimes happens to me that when I update AS, the build variants are totally messed up, so instead of building the "debug" variant I am actually building the "release" variant, which outputs apk to a different location (not to app/build directory, but to app directly) and I get the following error:
The APK file /path/to/file/app.apk does not exist on disk.
Error while Installing APK
To fix this just open the menu in left bottom corner, click on "Build Variants" and select the debug variant (it might have a different name, depending on how many modules/flavors or custom gradle build types you have).
I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.
I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).
It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.
Sometimes you get broken code, when using dex2jar
/apktool
, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar
/.class
file first as dex2jar
does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!
This will remove empty lines or lines with only whitespace characters (tabs/spaces).
[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"
we can use Model.last(5)
or Model.limit(5).order(id: :desc)
in rails 5.2
For timing operation you should use Handler.
If you need to run a background service the AlarmManager is the way to go.
In Swift 4 I tried all of this previously, but runs only:
@IBAction func myButton(sender: AnyObject) {
sender.setTitle("This is example text one", for:[])
sender.setTitle("This is example text two", for: .normal)
}
This may help you, I have tried this when i got the same issue.
SELECT *
FROM tab
ORDER BY IIF(TRY_CAST(val AS INT) IS NULL, 1, 0),TRY_CAST(val AS INT);
Multiple box shadows did it for me.
box-shadow:
inset 0 -8px 4px 4px rgb(255,255,255),
inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
In swift4,
var Msg_Date_ = "2019-03-30T05:30:00+0000"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd yyyy h:mm a" //"MMM d, h:mm a" for Sep 12, 2:11 PM
let datee = dateFormatterGet.date(from: Msg_Date_)
Msg_Date_ = dateFormatterPrint.string(from: datee ?? Date())
print(Msg_Date_)
//output :- Mar 30 2019 05:30 PM
Did you try format?
@font-face {
font-family: 'The name of the Font Family Here';
src: URL('font.ttf') format('truetype');
}
Read this article: http://css-tricks.com/snippets/css/using-font-face/
Also, might depend on browser as well.
In simple class declare context and get data from file from res folder
public class FileData
{
private Context context;
public FileData(Context current){
this.context = current;
}
void getData()
{
InputStream in = context.getResources().openRawResource(R.raw.file11);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//write stuff to get Data
}
}
In the activity class declare like this
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileData fileData=new FileData(this);
}
}
There is a property in <Button>
that is android:textAllCaps="false" that make characters in which you want in your own Small and caps. By Default its became True so write this code and make textAllCaps=false then you can write text on button in small and Caps letter as per your requirement.
Complete code for a Button which allow use to write letters as per our requirement.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnLogin"
android:text="Login for Chat"
android:textAllCaps="false"/>
You can use your favourite telnet (not recommended) or ssh (recommended) application to connect to your Synology box and use it as a terminal.
If you need more detailed instruction read https://www.synology.com/en-global/knowledgebase/DSM/help/DSM/AdminCenter/system_terminal
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
Let's say you're an airline. You build an airplane. You install seats in it. Then, you fill the plane up with passengers and send it somewhere. The passengers (or rather, some spatio-temporally altered version thereof) disembark. Next day, you re-use the same plane, and same seats, but with different passengers this time.
The plane is your function.
The parameters are the seats.
The arguments are the passengers that go in those seats.
Use git config --global core.editor mate -w
or git config --global core.editor open
as @dmckee suggests in the comments.
Reference: http://git-scm.com/docs/git-config
Alternatively to information_schema
it is possible to use pg_tables
:
select * from pg_tables where schemaname='public';
You might take a look at this:
https://github.com/michaelmoussa/ng-boolean-radio/
This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.
The CSS solutions don't appear to be widely available as of mid-2013. Instead...
Nicholas Zakas explains that Modernizr applies a no-touch
CSS class when the browser doesn’t support touch.
Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:
<script>
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
</script>
Then you can write your CSS as:
.no-touch .myClass {
...
}
.touch .myClass {
...
}
The string in quotes after "[submodule" doesn't matter. You can change it to "foobar" if you want. It's used to find the matching entry in ".git/config".
Therefore, if you make the change before you run "git submodule init", it'll work fine. If you make the change (or pick up the change through a merge), you'll need to either manually edit .git/config or run "git submodule init" again. If you do the latter, you'll be left with a harmless "stranded" entry with the old name in .git/config.
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
labelName.font = labelName.font.withSize(15)
2020 Update
One of my reasons for preferring a typeof
check (namely, that undefined
can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use typeof
to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations:
myVariable === undefined
Original answer from 2010
Using typeof
is my preference. It will work when the variable has never been declared, unlike any comparison with the ==
or ===
operators or type coercion using if
. (undefined
, unlike null
, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above).
if (typeof someUndeclaredVariable == "undefined") {
// Works
}
if (someUndeclaredVariable === undefined) {
// Throws an error
}
For Android 7, Galaxy S6 Edge:
If Developer Options is not available then
Now perform step 1. Now it should work, if its still not working then perform these steps. It worked for me.
If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:
throw new java.lang.UnsupportedOperationException("Not supported yet.");
Therefore, I recommend to use the UnsupportedOperationException.
This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically
select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'
exec (@sql)
of course #tables is a dynamic table in the stored procedure
Most of the time we login to remote server using ssh. If you start a shell script and you logout then the process is killed. Nohup helps to continue running the script in background even after you log out from shell.
Nohup command name &
eg: nohup sh script.sh &
Nohup catches the HUP signals. Nohup doesn't put the job automatically in the background. We need to tell that explicitly using &
Another programatically way to do that:
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;
@BeforeClass
public static void setupTest() {
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "test");
}
It works great.
Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.
while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.
There are 2 jQuery functions that you'll want to use here.
1) click
. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.
2) html
. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.
So, in your case, you'll want to do the following:
$('#content-container a').click(function(e){
$(this).parent().html('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you only want to add content to your div, rather than replacing everything in it, you should use append
:
$('#content-container a').click(function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you want the new added links to also add new content when clicked, you should use event delegation:
$('#content-container').on('click', 'a', function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
This will also give you the project directory by navigating two levels up from the current executing directory (this won't return the project directory for every build, but this is the most common).
System.IO.Path.GetFullPath(@"..\..\")
Of course you would want to contain this inside some sort of validation/error handling logic.
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
How about typing document.cookie into the console? It just shows the values, but it's something.
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.setLayoutParams(labelLayoutParams);
// If you want to add some controls in this Relative Layout
labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView mImage = new ImageView(this);
mImage.setBackgroundResource(R.drawable.popupnew_bg);
layout.addView(mImage,labelLayoutParams);
setContentView(layout);
I'd do it like this:
sudo chown -R $USER:www-data laravel-project/
find laravel-project/ -type f -exec chmod 664 {} \;
find laravel-project/ -type d -exec chmod 775 {} \;
then finally, you need to give webserver permission to modify the storage
and bootstrap/cache
directories:
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.
In my case I wanted to load the same form each time I click, I didn't want the changes I've made on the file stays. It may not relevant to this post exactly, but this could be a potential solution on the client side without setting config for require. Instead of sending the contents directly, you can make a copy of the required file and keep the actual file intact.
LoadFile(filePath){
const file = require(filePath);
const result = angular.copy(file);
return result;
}
You can install multiple versions of Python one machine, and during setup, you can choose to have one of them associate itself with Python file extensions. If you install modules, there will be different setup packages for different versions, or you can choose which version you want to target. Since they generally install themselves into the site-packages directory of the interpreter version, there shouldn't be any conflicts (but I haven't tested this). To choose which version of python, you would have to manually specify the path to the interpreter if it is not the default one. As far as I know, they would share the same PATH and PYTHONPATH variables, which may be a problem.
Note: I run Windows XP. I have no idea if any of this changes for other versions, but I don't see any reason that it would.
Inspired by the work of Josien, I wondered about a simplification.
Would this also work? Much shorter:
SELECT SUBSTRING(col, CHARINDEX ('/', col) + 1, CHARINDEX ('.', col) - CHARINDEX ('/', col) - 1);
(I can't test right now because of right issues at my company SQL server, which is a problem in its own right)
I know this has been answered to death but I'd like to show an actual example of speed differences.
Function directly on object:
function ExampleFn() {
this.print = function() {
console.log("Calling print! ");
}
}
var objects = [];
console.time('x');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('x');
//x: 1151.960693359375ms
_x000D_
Function on prototype:
function ExampleFn() {
}
ExampleFn.prototype.print = function() {
console.log("Calling print!");
}
var objects = [];
console.time('y');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('y');
//x: 617.866943359375ms
_x000D_
Here we're creating 2,000,000 new objects with a print
method in Chrome. We're storing every object in an array. Putting print
on the prototype takes about 1/2 as long.