<table border="1" style="width: 100%;">
<colgroup>
<col width="100%" />
<col width="0%" />
</colgroup>
<tr>
<td style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.</td>
<td style="white-space: nowrap;">Less content here.</td>
</tr>
</table>
I used this solution: in TableRow
, I created for every cell LinearLayout
with vertical line and actual cell in it, and after every TableRow
, I added a horizontal line.
Look at the code below:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:shrinkColumns="1">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_height="match_parent"
android:layout_width="1dp"
android:background="#BDCAD2"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
</TableRow>
<View
android:layout_height="1dip"
android:background="#BDCAD2" />
<!-- More TableRows -->
</TableLayout>
Hope it will help.
I do not like the solution that forces the number of lines in the text view. I rather suggest you solve it via the solution proposed here. As I see the OP is also struggling with making text view look like proper in table and shrinkColumns
is the correct directive to pass in to achieve what is wanted.
table {
border: 1px solid transparent;
}
I have IE 7.0, Firefox 3.0 and Chrome 1.0
The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.
Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.
This does NOT work when the table-layout CSS property is set to fixed.
Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic. Hope this helps.
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
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();
}
);
}
);
The "table-column" display type means it acts like the <col>
tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
Let's assume this is your class:
class Test
{
private $baz = 1;
public function foo() { ... }
public function bar()
{
printf("baz = %d\n", $this->baz);
}
public static function staticMethod() { echo "static method\n"; }
}
From within the foo()
method, let's look at the different options:
$this->staticMethod();
So that calls staticMethod()
as an instance method, right? It does not. This is because the method is declared as public static
the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.
$this::staticMethod();
Since PHP 5.3 you can use $var::method()
to mean <class-of-$var>::
; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:
self::staticMethod();
Now, before you start thinking that the ::
is the static call operator, let me give you another example:
self::bar();
This will print baz = 1
, which means that $this->bar()
and self::bar()
do exactly the same thing; that's because ::
is just a scope resolution operator. It's there to make parent::
, self::
and static::
work and give you access to static variables; how a method is called depends on its signature and how the caller was called.
To see all of this in action, see this 3v4l.org output.
You should verify that new File(".")
is really pointing to where you think it is pointing - .classpath
suggests the root of some Eclipse project....
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
A string needs no encoding. It is simply a sequence of Unicode characters.
You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.
Encoding of a String is carried out by:
String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into
You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).
Decoding:
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
I took couple of ideas from your answers and I don't know how to make it shorter :)
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris['feature_names'])
df['target'] = iris['target']
This gives a Pandas DataFrame with feature_names plus target as columns and RangeIndex(start=0, stop=len(df), step=1). I would like to have a shorter code where I can have 'target' added directly.
Here's another one:
PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate
Name LockedOut LastLogonDate
---- --------- -------------
Yxxxxxxx True 14/11/2014 10:19:20
Bxxxxxxx True 18/11/2014 08:38:34
Administrator True 03/11/2014 20:32:05
Other parameters worth mentioning:
Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive
Get-Help Search-ADAccount -ShowWindow
Check if data is a empty string (and ignore any white space) with jQuery:
function isBlank( data ) {
return ( $.trim(data).length == 0 );
}
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
If you're using WPF and the previous answers don't help, you can retrieve the result using:
var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Do something
}
For simple animations you can use an animated gif. I'm using one in this README file for instance.
I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.
So without further ado,
import math
def count_number(number):
counter = 0
counter_number = number
while counter_number > 0:
counter_number //= 10
counter += 1
return counter
def digit_selector(number, selected_digit, total):
total_counter = total
calculated_select = total_counter - selected_digit
number_selected = int(number / math.pow(10, calculated_select))
while number_selected > 10:
number_selected -= 10
return number_selected
def main():
x = 1548731588
total_digits = count_number(x)
digit_2 = digit_selector(x, 2, total_digits)
return print(digit_2)
if __name__ == '__main__':
main()
which will print:
5
Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!
This should find any digit in a integer.
Flaws:
Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)
Usage:
You need every line from 1-21. Then you can call first count_number to make it count your integer.
x = 1548731588
total_digits = count_number(x)
Then read/use the digit_selector function as follows:
digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')
If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.
We know how many digits there are due to using total_digits. So that's pretty easy.
Hope that explains everything!
Han
PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):
public static int GetNativeThreadId(Thread thread)
{
var f = typeof(Thread).GetField("DONT_USE_InternalThread",
BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var pInternalThread = (IntPtr)f.GetValue(thread);
var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
return nativeId;
}
When adding a column you need to make that column an integer and if possible stick with rails conventions. So for your case I am assuming you already have a Tester and User models, and testers and users tables.
To add the foreign key you need to create an integer column with the name user_id (convention):
add_column :tester, :user_id, :integer
Then add a belongs_to to the tester model:
class Tester < ActiveRecord::Base
belongs_to :user
end
And you might also want to add an index for the foreign key (this is something the references already does for you):
add_index :tester, :user_id
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
If you have a slow page or network connection, chances are that none of the above will work. I have tried them all and the only thing that worked for me is to wait for the last visible element on that page. Take for example the Bing webpage. They have placed a CAMERA icon (search by image button) next to the main search button that is visible only after the complete page has loaded. If everyone did that, then all we have to do is use an explicit wait like in the examples above.
As Service is already a Context itself
you can even get it through:
Context mContext = this;
OR
Context mContext = [class name].this; //[] only specify the class name
// mContext = JobServiceSchedule.this;
My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......
function CheckLength()
{
var keyCode = event.keyCode
if (keyCode == 13)
{
document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
}
}
When running in debug mode you can use the little arrow button in the debug area (Shift+Cmd+Y) in Xcode to specify a location. There are some presets or you can also add a GPX file.
You can generate GPX files here manually: http://www.bikehike.co.uk/mapview.php (from answer: https://stackoverflow.com/a/17478860/881197)
Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->
var array = [ [id,name,value], [id,name,value] ]
Hopefully that helps!
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
You can change the labels' text by adorning the property with the DisplayName
attribute.
[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }
Or, you could write the raw HTML explicitly:
<label for="SomekingStatus" class="control-label">Someking Status</label>
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
Insert bulk more than 7000000 record in 1 minutes in database(superfast query with calculation)
mysqli_query($cons, '
LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE tablename
FIELDS TERMINATED by \',\'
LINES TERMINATED BY \'\n\'
IGNORE 1 LINES
(isbn10,isbn13,price,discount,free_stock,report,report_date)
SET RRP = IF(discount = 0.00,price-price * 45/100,IF(discount = 0.01,price,IF(discount != 0.00,price-price * discount/100,@RRP))),
RRP_nl = RRP * 1.44 + 8,
RRP_bl = RRP * 1.44 + 8,
ID = NULL
');
$affected = (int) (mysqli_affected_rows($cons))-1;
$log->lwrite('Inventory.CSV to database:'. $affected.' record inserted successfully.');
RRP and RRP_nl and RRP_bl is not in csv but we are calculated that and after insert that.
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
if($('#leftmenu').val() == "") {
// statement
}
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
Something like this?
And the code I used:
.box{
position: relative;
overflow: hidden;
}
.box:hover .hidden{
left: 0px;
}
.box .hidden {
background: yellow;
height: 300px;
position: absolute;
top: 0;
left: -500px;
width: 500px;
opacity: 1;
-webkit-transition: all 0.7s ease-out;
-moz-transition: all 0.7s ease-out;
-ms-transition: all 0.7s ease-out;
-o-transition: all 0.7s ease-out;
transition: all 0.7s ease-out;
}
I may also add that it's possible to move an elment using transform: translate();
, which in this case could work something like this - DEMO nr2
This can be done for free using GIMP.
It uses the ability of GIMP to have each layer a different size.
I created the following layers sized correctly.
Notes
The below code will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
/*
* Properties from the Souce1 object will be copied to Source2 Object.
* Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
* */
var mergedJSON = Object.create(source2);// Copying Source2 to a new Object
for (var attrname in source1) {
if(mergedJSON.hasOwnProperty(attrname)) {
if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
/*
* Recursive call if the property is an object,
* Iterate the object and set all properties of the inner object.
*/
mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
}
} else {//else copy the property from source1
mergedJSON[attrname] = source1[attrname];
}
}
return mergedJSON;
}
If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join()
available as a method on any old string object, and you will instead need to use the string module. Example:
a = ['a', 'b', 'c', 'd']
try:
b = ''.join(a)
except AttributeError:
import string
b = string.join(a, '')
The string b
will be 'abcd'
.
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
if you don't want add the attr disabled can do it programmatically
can disable the edition into the <select class="yourClass">
element with this code:
//bloqueo selects
//block all selects
jQuery(document).on("focusin", 'select.yourClass', function (event) {
var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
});
if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/
if any(word in 'some one long two phrase three' for word in list_):
Martin Encountered the same issue with a Minecraft Mod project when I changed the Main folder location. Normally I would open the project like this
This is how my path looked when I started the project
I got the same "The project description file (.project) for my project is missing." Error.
I later found the .project file in the main folder like this.
This is the location where I found the .project file
I found that going eclipse to "File->Open Project from File System or Archive" and navigate to your main project folder with the .project file solved the problem.
My project is already included
This is my first post in here hoping it can help you out, Martin.
There are a few options:
Deal exclusively with unicode objects as much as possible by decoding things to unicode objects when you first get them and encoding them as necessary on the way out.
If your string is actually a unicode object, you'll need to convert it to a unicode-encoded string object before writing it to a file:
foo = u'?, ?, ?, ? ?, ?, ?, ?, ?, and ?.'
f = open('test', 'w')
f.write(foo.encode('utf8'))
f.close()
When you read that file again, you'll get a unicode-encoded string that you can decode to a unicode object:
f = file('test', 'r')
print f.read().decode('utf8')
If you are using AJAX
jQuery
Request this is a must to apply. If not it will throw you 415
Error.
dataType: "json",
contentType:'application/json'
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
in most cases the List<String>
should be enough. No need to create an ArrayList
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
...
String[] words={"ace","boom","crew","dog","eon"};
List<String> l = Arrays.<String>asList(words);
// if List<String> isnt specific enough:
ArrayList<String> al = new ArrayList<String>(l);
One way to check it is to loop through the string and return true (or false depending on what you want) when you hit a number.
function checkStringForNumbers(input){
let str = String(input);
for( let i = 0; i < str.length; i++){
console.log(str.charAt(i));
if(!isNaN(str.charAt(i))){ //if the string is a number, do the following
return true;
}
}
}
@Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
I'm using AWS Elasticbeanstalk + Docker + Supervisord.
Just add some code in Dockerfile
.
CMD echo 123.123.123.123 this_is_my.host >> /etc/hosts; supervisord -n;
If its a 32 bit COM/Active X, use version 32 bit of cscript.exe/wscript.exe located in C:\Windows\SysWOW64\
Use the value child element instead of the value attribute and specify the Enum class name:
<property name="residence">
<value type="SocialSecurity$Residence">ALIEN</value>
</property>
The advantage of this approach over just writing value="ALIEN"
is that it also works if Spring can't infer the actual type of the enum from the property (e.g. the property's declared type is an interface).Adapted from araqnid's comment.
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
if you have an array like this:
(users is the name of the array)
Array=>
[0] => (array)
'user' => 'john'
'age' => '23'
[1] => (array)
'user' => 'jane'
'age' => '20'
[2]=> (array)
'user' => 'john'
'age' => '23'
and you want to delete duplicates...then:
$serialized = array();
for ($i=0; $i < sizeof($users); $i++) {
$test = in_array($users['user'], $serialized);
if ($test == false) {
$serialized[] = $users['user'];
}
}
can be a solution :P
Check your my.cnf
file in your MySQL program directory, look for
[mysqld]
datadir=
The datadir
is the location where your MySQL database is stored.
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
Please check this. https://code.google.com/p/android/issues/detail?id=82850
I faced the same issue. Could notice that the "adb integration" was disabled. Please enable it at your IDE (Tools | Android)
This exception is typically thrown when the app is being sent to the background.
So I've decided to use the data Fragment method to completely circumvent the onSavedInstanceStae
lifecycle. My solution also handles complex instance states and frees memory ASAP.
First I've created a simple Fargment to store the data:
package info.peakapps.peaksdk.logic;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
/**
* A neat trick to avoid TransactionTooLargeException while saving our instance state
*/
public class SavedInstanceFragment extends Fragment {
private static final String TAG = "SavedInstanceFragment";
private Bundle mInstanceBundle = null;
public SavedInstanceFragment() { // This will only be called once be cause of setRetainInstance()
super();
setRetainInstance( true );
}
public SavedInstanceFragment pushData( Bundle instanceState )
{
if ( this.mInstanceBundle == null ) {
this.mInstanceBundle = instanceState;
}
else
{
this.mInstanceBundle.putAll( instanceState );
}
return this;
}
public Bundle popData()
{
Bundle out = this.mInstanceBundle;
this.mInstanceBundle = null;
return out;
}
public static final SavedInstanceFragment getInstance(FragmentManager fragmentManager )
{
SavedInstanceFragment out = (SavedInstanceFragment) fragmentManager.findFragmentByTag( TAG );
if ( out == null )
{
out = new SavedInstanceFragment();
fragmentManager.beginTransaction().add( out, TAG ).commit();
}
return out;
}
}
Then on my main Activity I circumvent the saved instance cycle completely, and defer the respoinsibilty to my data Fragment. No need to use this on the Fragments themselves, sice their state is added to the Activity's state automatically):
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
SavedInstanceFragment.getInstance( getFragmentManager() ).pushData( (Bundle) outState.clone() );
outState.clear(); // We don't want a TransactionTooLargeException, so we handle things via the SavedInstanceFragment
}
What's left is simply to pop the saved instance:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(SavedInstanceFragment.getInstance(getFragmentManager()).popData());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState( SavedInstanceFragment.getInstance( getFragmentManager() ).popData() );
}
Full details: http://www.devsbedevin.net/avoiding-transactiontoolargeexception-on-android-nougat-and-up/
This can also happen if CMAKE_FIND_ROOT_PATH
is set as different from BOOST_ROOT
.
I faced the same issue that in spite of setting BOOST_ROOT
, I was getting the error.
But for cross compiling for ARM I was using Toolchain-android.cmake in which I had (for some reason):
set(BOOST_ROOT "/home/.../boost")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${SYSROOT}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --sysroot=${SYSROOT} -I${SYSROOT}/include/libcxx")
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
set(CMAKE_FIND_ROOT_PATH "${SYSROOT}")
CMAKE_FIND_ROOT_PATH
seems to be overriding BOOST_ROOT
which was causing the issue.
An <iframe>
background can be changed like this:
<iframe allowtransparency="true" style="background: #FFFFFF;"
src="http://zingaya.com/widget/9d043c064dc241068881f045f9d8c151"
frameborder="0" height="184" width="100%">
</iframe>
I don't think it's possible to change the background of the page that you have loaded in the iframe.
From this article: How to copy arrays and objects in Javascript by Brian Huisman:
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (var i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
};
Select top 2 [id] from table Order by [id] desc
should give you want you the latest two rows added.
However, you will have to pay particular attention to the order by
clause as that will determine the 1st and 2nd row returned.
If the query was to be changed like this:
Select top 2 [id] from table Order by ModifiedDate desc
You could get two different rows. You will have to decide which column to use in your order by statement.
Right click on table name
-->choose open table
--> Go to Info Tab
and the scroll down to see create table script
You can also use an interceptor to set the values
Create an interface called TimeStamped which your entities implement
public interface TimeStamped {
public Date getCreatedDate();
public void setCreatedDate(Date createdDate);
public Date getLastUpdated();
public void setLastUpdated(Date lastUpdatedDate);
}
Define the interceptor
public class TimeStampInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
Object[] previousState, String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "lastUpdated");
currentState[indexOf] = new Date();
return true;
}
return false;
}
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "createdDate");
state[indexOf] = new Date();
return true;
}
return false;
}
}
And register it with the session factory
The sqlite3 .import command won't work for ordinary csv data because it treats any comma as a delimiter even in a quoted string.
This includes trying to re-import a csv file that was created by the shell:
Create table T (F1 integer, F2 varchar);
Insert into T values (1, 'Hey!');
Insert into T values (2, 'Hey, You!');
.mode csv
.output test.csv
select * from T;
Contents of test.csv:
1,Hey!
2,"Hey, You!"
delete from T;
.import test.csv T
Error: test.csv line 2: expected 2 columns of data but found 3
It seems we must transform the csv into a list of Insert statements, or perhaps a different delimiter will work.
Over at SuperUser I saw a suggestion to use LogParser to deal with csv files, I'm going to look into that.
When you want two React components to communicate, which are not bound by a relationship (parent-child), it is advisable to use Flux or similar architectures.
What you want to do is to listen for changes of the observable component store, which holds the model and its interface, and saving the data that causes the render to change as state
in MyComponent
. When the store pushes the new data, you change the state of your component, which automatically triggers the render.
Normally you should try to avoid using forceUpdate()
. From the documentation:
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your application much simpler and more efficient
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
.Select(t => t.Result)
.Where(i => i != null)
.ToList();
But this seems very weird to me, first of all the use of async and await in the select. According to this answer by Stephen Cleary I should be able to drop those.
The call to Select
is valid. These two lines are essentially identical:
events.Select(async ev => await ProcessEventAsync(ev))
events.Select(ev => ProcessEventAsync(ev))
(There's a minor difference regarding how a synchronous exception would be thrown from ProcessEventAsync
, but in the context of this code it doesn't matter at all.)
Then the second Select which selects the result. Doesn't this mean the task isn't async at all and is performed synchronously (so much effort for nothing), or will the task be performed asynchronously and when it's done the rest of the query is executed?
It means that the query is blocking. So it is not really asynchronous.
Breaking it down:
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
will first start an asynchronous operation for each event. Then this line:
.Select(t => t.Result)
will wait for those operations to complete one at a time (first it waits for the first event's operation, then the next, then the next, etc).
This is the part I don't care for, because it blocks and also would wrap any exceptions in AggregateException
.
and is it completely the same like this?
var tasks = await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev)));
var inputs = tasks.Where(result => result != null).ToList();
var inputs = (await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev))))
.Where(result => result != null).ToList();
Yes, those two examples are equivalent. They both start all asynchronous operations (events.Select(...)
), then asynchronously wait for all the operations to complete in any order (await Task.WhenAll(...)
), then proceed with the rest of the work (Where...
).
Both of these examples are different from the original code. The original code is blocking and will wrap exceptions in AggregateException
.
No it is not safe. You could later do var IsLoggedIn = "Foo";
and JavaScript will not throw an error.
It is possible to do
var IsLoggedIn = new Boolean(false);
var IsLoggedIn = new Boolean(true);
You can also pass the non boolean variable into the new Boolean()
and it will make IsLoggedIn boolean.
var IsLoggedIn = new Boolean(0); // false
var IsLoggedIn = new Boolean(NaN); // false
var IsLoggedIn = new Boolean("Foo"); // true
var IsLoggedIn = new Boolean(1); // true
This could be related to one of the bugs in JDK 6 Update 14, as indicated in the release notes for JDK 6 update 15.
If this indeed turns out to be the issue, you should move to a higher version of the JDK (that's no guarantee though, since fixes have been released against 6u16, 6u18 and 7b1). The best bet is to use -XX:+UseParallelGC flag. Increasing the size of the minimum and maximum heap size, to delay the first GC, bring temporary relief.
By the way, use this bug report in Eclipse to track how others have been faring.
While this is not a direct answer to Devang's question I believe that the below macro can be very helpful to people looking to log BOOLs. This will log out the value of the bool as well as automatically labeling it with the name of the variable.
#define LogBool(BOOLVARIABLE) NSLog(@"%s: %@",#BOOLVARIABLE, BOOLVARIABLE ? @"YES" : @"NO" )
BOOL success = NO;
LogBool(success); // Prints out 'success: NO' to the console
success = YES;
LogBool(success); // Prints out 'success: YES' to the console
No need to add any plugin, CSS can do this job !!!
The idea is to make the position of all the first cells in each column absolute, and make width fixed. Ex:
max-width: 125px;
min-width: 125px;
position: absolute;
This hides some parts of some columns under the first column, so add an empty second column (add second empty td) with width same as the first column.
I tested and this works in Chrome and Firefox.
You can register a route change listener on your main component and scroll to top on route changes.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
Not need to change all config in file /opt/lampp/etc/extra/httpd-xampp.conf.
The only thing you need to change is the Require local
It's kinda obvious what Require local means so just change to Require all granted
Require all granted
Solution
from Require local
to Require all granted
Often, you don't need any auto*
tools and the simplest solution is to simply run touch aclocal.m4 configure
in the relevant folder (and also run touch
on Makefile.am
and Makefile.in
if they exist). This will update the timestamp of aclocal.m4
and remind the system that aclocal.m4
is up-to-date and doesn't need to be rebuilt. After this, it's probably best to empty your build
directory and rerun configure
from scratch after doing this. I run into this problem regularly. For me, the root cause is that I copy a library (e.g. mpfr
code for gcc
) from another folder and the timestamps change.
Of course, this trick isn't valid if you really do need to regenerate those files, perhaps because you have manually changed them. But hopefully the developers of the package distribute up-to-date files.
And of course, if you do want to install automake
and friends, then use the appropriate package-manager for your distribution.
Install aclocal which comes with automake:
brew install automake # for Mac
apt-get install automake # for Ubuntu
Try again:
./configure && make
There is a way of displaying 3 Y axis see here.
Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
Simple, create multiple accordian div each representating one anchor tag like:
<div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
</div>
It adds up some markup. But works like a pro...
To copy remote-to-remote files you can use the synchronize module with 'delegate_to: source-server
' keyword:
- hosts: serverB
tasks:
- name: Copy Remote-To-Remote (from serverA to serverB)
synchronize: src=/copy/from_serverA dest=/copy/to_serverB
delegate_to: serverA
This playbook can run from your machineC.
Unless you need to identify the columns automatically, I found this to be the simplest solution:
df$name <- as.factor(df$name)
This makes column name
in dataframe df
a factor.
As of C# 7 you could also use this:
if (clientsParsed["objects"] is JArray clients)
{
foreach (JObject item in clients.Children())
{
if (item["thisParameter"] as JToken itemToken)
{
command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
}
}
}
The is Operator checks the Type and if its corrects the Value is inside the clients variable.
In you keyup/down handler you just need to set the scrollTop
property of the div you want to scroll to make it scroll down (or up).
For example:
JSX:
<div ref="foo">{content}</div>
keyup/down handler:
this.refs.foo.getDOMNode().scrollTop += 10
If you do something similar to above, your div will scroll down 10 pixels (assuming the div is set to overflow auto
or scroll
in css, and your content is overflowing of course).
You will need to expand on this to find the offset of the element inside your scrolling div that you want to scroll the div down to, and then modify the scrollTop
to scroll far enough to show the element based on it's height.
Have a look at MDN's definitions of scrollTop, and offsetTop here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop
This works for me (just an extract from my whole script)
choice /C 1234567H /M "Select an option or ctrl+C to cancel"
set _dpi=%ERRORLEVEL%
if "%_dpi%" == "8" call :helpme && goto menu
for /F "tokens=%_dpi%,*" %%1 in ("032 060 064 096 0C8 0FA 12C") do set _dpi=%%1
echo _dpi:%_dpi%:
It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.
I am using this and got I worked
"query": { "query_string" : { "query" : "*test*", "fields" : ["field1","field2"], "analyze_wildcard" : true, "allow_leading_wildcard": true } }
Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:
fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');
The second param is an optional replacer function which you don't need in this case so null
works.
The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.
I have SingleChildScrollView
as a parent, and one Column
Widget and then List View Widget as last child.
Adding these properties in List View Worked for me.
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
scrollDirection: Axis.vertical,
Hi above solutions didn't work for me. The other way of running a single test is
mocha test/cartcheckout/checkout.js -g 'Test Name Goes here'
This helps to run a test case from a single file and with specific name.
If you are using the modules system on the server side, you do not need to use Babel at all. To use modules in Node.js ensure that:
That's it.
However and this is a big however, while your shinny pure ES6 code will run in an environment like Node.js (e.g., 9.5.0) you will still have the craziness of transpilling just to test. Also bear in mind that Ecma has stated that release cycles for JavaScript are going to be faster, with newer features delivered on a more regular basis. Whilst this will be no problems for single environments like Node.js, it's a slightly different proposition for browser environments. What is clear is that testing frameworks have a lot to do in catching up. You will still need to probably transpile for testing frameworks. I'd suggest using Jest.
Also be aware of bundling frameworks. You will be running into problems there.
In our case, nothing was added in the Windows Event Logs except logs that the problematic service has been started and then stopped.
It turns out that the service's CONFIG file was invalid. Correcting the invalid CONFIG file fixed the issue.
In lisp
(defun pick-random (set)
(nth (random (length set)) set))
Try something like this (should work for Apache and IIS):
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
The result of a subtraction generating a negative number in an unsigned type is well-defined:
- [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)
As you can see, (unsigned)0 - (unsigned)1
equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.
Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.
Extension method should be inside a static class. So please add your extension method inside a static class.
so for example it should be like this
public static class myclass
{
public static Byte[] ToByteArray(this Stream stream)
{
Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
Byte[] buffer = new Byte[length];
stream.Read(buffer, 0, length);
return buffer;
}
}
Hint: break up the 32-bit integer to 4 8-bit integers, and print them out.
Something along the lines of this (not compiled, YMMV):
int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
(i >> 24) & 0xFF,
(i >> 16) & 0xFF,
(i >> 8) & 0xFF,
i & 0xFF);
You could reference the variable in an assertion and then build with -fsanitize=address
:
void foo (int32_t& i) {
// Assertion will trigger address sanitizer if not initialized:
assert(static_cast<int64_t>(i) != INT64_MAX);
}
This will cause the program to reliably crash with a stack trace (as opposed to undefined behavior).
You can go to IE Tools -> Internet options -> Advanced Tab
. Under Advanced, check for security and put a check on the 1st 2 options which says,"Allow active content from CDs to run on My Computer* and Allow active content to run in files on My Computer*"
Restart your browser and the ActiveX scripts will not be shown.
Modified the above answer a little bit. We don't really have to call the 'map' method explicitly, because it is already built-in into the 'Array.from' as a second argument. As of MDN.
Array.from(arrayLike[, mapFn[, thisArg]])
let num = 1234;
let arr = Array.from(String(num), Number);
console.log(arr); // [1, 2, 3, 4]
There are two problems with your code
In the same statement in which you execute finish(), execute your animation there too. Then, in the new activity, run another animation. See this code:
fadein.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<alpha android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="500"/> //Time in milliseconds
</set>
In your finish-class
private void finishTask() {
if("blabbla".equals("blablabla"){
finish();
runFadeInAnimation();
}
}
private void runFadeInAnimation() {
Animation a = AnimationUtils.loadAnimation(this, R.anim.fadein);
a.reset();
LinearLayout ll = (LinearLayout) findViewById(R.id.yourviewhere);
ll.clearAnimation();
ll.startAnimation(a);
}
fadeout.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="500"/>
</set>
In your new Activity-class you create a similiar method like the runFadeAnimation I wrote and then you run it in onCreate and don't forget to change the resources id to fadeout.
If I understand correctly, what you want to do, in pseudo-code is the following:
for (Tweet tweet : tweets) {
if (!db.containsTweet(tweet.getId())) {
db.insertTweet(tweet.getText(), tweet.getId());
}
}
I assume your db class actually uses an sqlite database as a backend? What you could do is implement containsTweet
directly and just query the database each time, but that seems less than perfect. The easiest solution if we go by your base code is to just keep a Set
around that indexes the tweets. Since I can't be sure what the equals()
method of Tweet
looks like, I'll just store the identifiers in there. Then you get:
Set<Integer> tweetIds = new HashSet<Integer>(); // or long, whatever
for (Tweet tweet : tweets) {
if (!tweetIds.contains(tweet.getId())) {
db.insertTweet(tweet.getText(), tweet.getId());
tweetIds.add(tweet.getId());
}
}
It would probably be better to save a tiny bit of this work, by sorting the list of tweets
to begin with and then just filtering out duplicate tweets. You could use:
// if tweets is a List
Collections.sort(tweets, new Comparator() {
public int compare (Object t1, Object t2) {
// might be the wrong way around
return ((Tweet)t1).getId() - ((Tweet)t2).getId();
}
}
Then process it
Integer oldId;
for (Tweet tweet : tweets) {
if (oldId == null || oldId != tweet.getId()) {
db.insertTweet(tweet.getText(), tweet.getId());
}
oldId = tweet.getId();
}
Yes, you could do this using a second for-loop, but you'll run into performance problems much more quickly than with this approach (although what we're doing here is trading time for memory performance, of course).
with help of other answers I wrote this function.
public static int convertToPixels(Context context, int nDP)
{
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f) ;
}
There is no good way to store an array into a single field.
You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.
If you must save the array into a single field then the serialize()
and unserialize()
functions will do the trick. But you cannot perform queries on the actual content.
As an alternative to the serialization function there is also json_encode()
and json_decode()
.
Consider the following array
$a = array(
1 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
2 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
);
To save it in the database you need to create a table like this
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
'DROP TABLE IF EXISTS test');
$r = mysql_query(
'CREATE TABLE test (
id INTEGER UNSIGNED NOT NULL,
a INTEGER UNSIGNED NOT NULL,
b INTEGER UNSIGNED NOT NULL,
c INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (id)
)');
To work with the records you can perform queries such as these (and yes this is an example, beware!)
function getTest() {
$ret = array();
$c = connect();
$query = 'SELECT * FROM test';
$r = mysql_query($query,$c);
while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
$ret[array_shift($o)] = $o;
}
mysql_close($c);
return $ret;
}
function putTest($t) {
$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (id,".
implode(',',array_keys($v)).
") VALUES ($k,".
implode(',',$v).
")";
$r = mysql_query($query,$c);
}
mysql_close($c);
}
putTest($a);
$b = getTest();
The connect()
function returns a mysql connection resource
function connect() {
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
return $c;
}
Python includes two functions in the math
package; radians
converts degrees to radians, and degrees
converts radians to degrees.
To match the output of your calculator you need:
>>> math.cos(math.radians(1))
0.9998476951563913
Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.
Can be done using xp_DirTree, then looping through to generate a full file path if required.
Here is an extract of a script I use to restore databases to a test server automatically. It scans a folder and all subfolders for any backup files, then returns the full path.
DECLARE @BackupDirectory SYSNAME = @BackupFolder
IF OBJECT_ID('tempdb..#DirTree') IS NOT NULL
DROP TABLE #DirTree
CREATE TABLE #DirTree (
Id int identity(1,1),
SubDirectory nvarchar(255),
Depth smallint,
FileFlag bit,
ParentDirectoryID int
)
INSERT INTO #DirTree (SubDirectory, Depth, FileFlag)
EXEC master..xp_dirtree @BackupDirectory, 10, 1
UPDATE #DirTree
SET ParentDirectoryID = (
SELECT MAX(Id) FROM #DirTree d2
WHERE Depth = d.Depth - 1 AND d2.Id < d.Id
)
FROM #DirTree d
DECLARE
@ID INT,
@BackupFile VARCHAR(MAX),
@Depth TINYINT,
@FileFlag BIT,
@ParentDirectoryID INT,
@wkSubParentDirectoryID INT,
@wkSubDirectory VARCHAR(MAX)
DECLARE @BackupFiles TABLE
(
FileNamePath VARCHAR(MAX),
TransLogFlag BIT,
BackupFile VARCHAR(MAX),
DatabaseName VARCHAR(MAX)
)
DECLARE FileCursor CURSOR LOCAL FORWARD_ONLY FOR
SELECT * FROM #DirTree WHERE FileFlag = 1
OPEN FileCursor
FETCH NEXT FROM FileCursor INTO
@ID,
@BackupFile,
@Depth,
@FileFlag,
@ParentDirectoryID
SET @wkSubParentDirectoryID = @ParentDirectoryID
WHILE @@FETCH_STATUS = 0
BEGIN
--loop to generate path in reverse, starting with backup file then prefixing subfolders in a loop
WHILE @wkSubParentDirectoryID IS NOT NULL
BEGIN
SELECT @wkSubDirectory = SubDirectory, @wkSubParentDirectoryID = ParentDirectoryID
FROM #DirTree
WHERE ID = @wkSubParentDirectoryID
SELECT @BackupFile = @wkSubDirectory + '\' + @BackupFile
END
--no more subfolders in loop so now prefix the root backup folder
SELECT @BackupFile = @BackupDirectory + @BackupFile
--put backupfile into a table and then later work out which ones are log and full backups
INSERT INTO @BackupFiles (FileNamePath) VALUES(@BackupFile)
FETCH NEXT FROM FileCursor INTO
@ID,
@BackupFile,
@Depth,
@FileFlag,
@ParentDirectoryID
SET @wkSubParentDirectoryID = @ParentDirectoryID
END
CLOSE FileCursor
DEALLOCATE FileCursor
When you want a relative path from your home directory (on any UNIX) you use this strange syntax:
ssh://[user@]host.xz[:port]/~[user]/path/to/repo
For Example, if the repo is in /home/jack/projects/jillweb
on the server jill.com
and you are logging in as jack
with sshd
listening on port 4242:
ssh://[email protected]:4242/~/projects/jillweb
And when logging in as jill
(presuming you have file permissions):
ssh://[email protected]:4242/~jack/projects/jillweb
class TableViewCell: UITableViewCell {
@IBOutlet weak var oneButton: UIButton!
@IBOutlet weak var twoButton: UIButton!
}
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)
return cell
}
func oneTapped(_ sender: Any?) {
print("Tapped")
}
func twoTapped(_ sender: Any?) {
print("Tapped")
}
}
if path.exists(Score_file):
try :
with open(Score_file , "rb") as prev_Scr:
return Unpickler(prev_Scr).load()
except EOFError :
return dict()
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
Yes Jython does this, but it may or may not be what you want
try this:
select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '[email protected]' )),3,32)
I tried the program below and saw different string each time
package main
import (
"fmt"
"math/rand"
"time"
)
func RandomString(count int){
rand.Seed(time.Now().UTC().UnixNano())
for(count > 0 ){
x := Random(65,91)
fmt.Printf("%c",x)
count--;
}
}
func Random(min, max int) (int){
return min+rand.Intn(max-min)
}
func main() {
RandomString(12)
}
And the output on my console is
D:\james\work\gox>go run rand.go
JFBYKAPEBCRC
D:\james\work\gox>go run rand.go
VDUEBIIDFQIB
D:\james\work\gox>go run rand.go
VJYDQPVGRPXM
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
Per Microsoft in powershell:
Get-ChildItem "hklm:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | % { $_ -ge 394802 }
See the table at this link to get the DWORD value to search for specific versions:
by far the best C++ GUI library out there is Qt, it's comprehensive, easy to learn, really fast, and multiplattform.
ah, it recently got a LGPL license, so now you can download it for free and include on commercial programs
Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:
breaker = False #our mighty loop exiter!
while True:
while True:
if conditionMet:
#insert code here...
breaker = True
break
if breaker: # the interesting part!
break # <--- !
If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!
Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.
Note.query.filter(Note.message.match("%somestr%")).all()
It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.
For more info go Common Filter Operators
Stop docker service
sudo systemctl stop docker
Move existing docker directory to new location
sudo mv /var/lib/docker/ /path/to/new/docker/
Create symbolic link
sudo ln -s /path/to/new/docker/ /var/lib/docker
Start docker service
sudo systemctl start docker
Using Desandro's imagesloaded plugin
1 - hide images in css:
#content img {
display:none;
}
2 - fade in images on load with javascript:
var imgLoad = imagesLoaded("#content");
imgLoad.on( 'progress', function( instance, image ) {
$(image.img).fadeIn();
});
Can add muted
tag.
<video autoplay muted>
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
reference https://developers.google.com/web/updates/2016/07/autoplay
When it comes to compilation speed, composed interfaces perform better than type intersections:
[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.
Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections
This is not the best practice in .NET framework (4 & +) to check equality
String.Compare(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase) == 0
Use the following instead
String.Equals(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase)
- Use an overload of the String.Equals method to test whether two strings are equal.
- Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
A better, more modern, answer to this question is to use the %pip
magic, like:
%pip install scipy
That will automatically use the correct Python version. Using !pip
might be tied to a different version of Python, and then you might not find the package after installing it.
And in colab, the magic gives a nice message and button if it detects that you need to restart the runtime if pip updated a packaging you have already imported.
BTW, there is also a %conda
magic for doing the same with conda.
I use to work on UNIX-like machines, but recently I have had to do some work with Java on a Windows 7 machine. I have had that problem and this is the I've solved it. It has worked right for me so I hope it can be used for whoever who may have this problem in the future.
These steps are exposed considering a default Java installation on drive C. You should change what it is necessary in case your installation is not a default one.
Suppose we have installed Java 8 but for whatever reason we want to keep with Java 7.
1- Start a cmd as administrator
2- Go to C:\ProgramData\Oracle\Java
3- Rename the current directory javapath to javapath_<version_it_refers_to>. E.g.: rename javapath javapath_1.8
4- Create a javapath_<version_you_want_by_default> directory. E.g.: mkdir javapath_1.7
5- cd into it and create the following links:
cd javapath_1.7
mklink java.exe "C:\Program Files\Java\jre7\bin\java.exe"
mklink javaw.exe "C:\Program Files\Java\jre7\bin\javaw.exe"
mklink javaws.exe "C:\Program Files\Java\jre7\bin\javaws.exe"
6- cd out and create a directory link javapath pointing to the desired javapath. E.g.: mklink /D javapath javapath_1.7
7- Open the register and change the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion to have the value 1.7
At this point if you execute java -version
you should see that you are using java version 1.7:
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)
8- Finally it is a good idea to create the environment variable JAVA_HOME. To do that I create a directory link named CurrentVersion in C:\Program Files\Java pointing to the Java version I'm interested in. E.g.:
cd C:\Program Files\Java\
mklink /D CurrentVersion .\jdk1.7.0_71
9- And once this is done:
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Root directory:
DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)
Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps
pipeline {
agent none
stages {
stage ('Hello') {
agent any
steps {
echo 'Hello, '
sh '''#!/bin/bash
echo "Hello from bash"
echo "Who I'm $SHELL"
'''
}
}
}
}
The result of the above execution is
I tried all of these solutions before I realized that I had enabled opcache in PHP on my live environment. Wordpress was not reading a cached version of wp-config.
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
brew help
will show you the list of commands that are available.
brew list
will show you the list of installed packages. You can also append formulae, for example brew list postgres
will tell you of files installed by postgres (providing it is indeed installed).
brew search <search term>
will list the possible packages that you can install. brew search post
will return multiple packages that are available to install that have post in their name.
brew info <package name>
will display some basic information about the package in question.
You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)
From a new Ubuntu 16.04 Installation
1) Terminal => Edit => Profile Preferences
2) Command Tab => Check Run command as a login shell
3) Close, and reopen terminal
rvm --default use 2.2.4
Sometimes it's just the version which you are missing, and you are scratching your head unnecessarily.
If you are using a specific version of PostgreSQL, for example, PostgreSQL 10, then simply do
brew services start postgresql@10
brew services stop postgresql@10
The normal brew services start postgresql
won't work without a version if you have installed it for a specific version from Homebrew.
In case if you are using node js, then this could be the possible solution
const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;
In the light of the evolving thread, I have updated the below:
_:-ms-fullscreen, :root .foo { property:value; }
_:-ms-lang(x), .foo { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.foo{property:value;}
}
_:-ms-lang(x), .foo { property:value\9; }
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
//.foo CSS
.foo{property:value;}
}
@media screen and (min-width:0\0) {
.foo /* backslash-9 removes.foo & old Safari 4 */
}
@media screen and (min-width:0\0) and (min-resolution: .001dpcm) {
//.foo CSS
.foo{property:value;}
}
@media screen\0 {
.foo {property:value;}
}
.foo { property /*\**/: value\9 }
html>/**/body .foo {property:value;}
or
@media \0screen {
.foo {property:value;}
}
*+html .foo {property:value;}
or
*:first-child+html .foo {property:value;}
@media \0screen\,screen\9 {
.foo {property:value;}
}
@media screen\9 {
.foo {property:value;}
}
or
.foo { *property:value;}
or
.foo { #property:value;}
@media \0screen\,screen\9 {
.foo {property:value;}
}
* html .foo {property:value;}
or
.foo { _property:value;}
Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element
Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to html
element:
data-useragent='Mozilla/5.0 (compatible; M.foo 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
If possible, identify and fix any issue(s) without hacks. Support progressive enhancement and graceful degradation. However, this is an 'ideal world' scenario not always obtainable, as such- the above should help provide some good options.
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).
More info on default primitive values here.
I researched this just recently and have yet to find a decent date picker that also includes a decent time picker. What I ended up using was eyecon's awesome DatePicker, with two simple dropdowns for time. I was tempted to use Timepickr.js though, looks like a really nice approach.
In case of a multi-value return function you can't refer to fields or methods of a specific value of the result when calling the function.
And if one of them is an error
, it's there for a reason (which is the function might fail) and you should not bypass it because if you do, your subsequent code might also fail miserably (e.g. resulting in runtime panic).
However there might be situations where you know the code will not fail in any circumstances. In these cases you can provide a helper function (or method) which will discard the error
(or raise a runtime panic if it still occurs).
This can be the case if you provide the input values for a function from code, and you know they work.
Great examples of this are the template
and regexp
packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason the template
package provides the Must(t *Template, err error) *Template
function and the regexp
package provides the MustCompile(str string) *Regexp
function: they don't return error
s because their intended use is where the input is guaranteed to be valid.
Examples:
// "text" is a valid template, parsing it will not fail
var t = template.Must(template.New("name").Parse("text"))
// `^[a-z]+\[[0-9]+\]$` is a valid regexp, always compiles
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
IF you can be certain Get()
will not produce error
for certain input values, you can create a helper Must()
function which would not return the error
but raise a runtime panic if it still occurs:
func Must(i Item, err error) Item {
if err != nil {
panic(err)
}
return i
}
But you should not use this in all cases, just when you're sure it succeeds. Usage:
val := Must(Get(1)).Value
Alternative / Simplification
You can even simplify it further if you incorporate the Get()
call into your helper function, let's call it MustGet
:
func MustGet(value int) Item {
i, err := Get(value)
if err != nil {
panic(err)
}
return i
}
Usage:
val := MustGet(1).Value
See some interesting / related questions:
Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.
There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...
You'll want to enter a message before you leave Vim:
...will start a new line for you to type in.
To exit (g)Vim type:
It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor
, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).
Here is a solution using Streams with Java 8
// lets assume the original list is filled with {1,1,2,3,6,3,8,7}
List<String> original = new ArrayList<>();
List<String> result = new ArrayList<>();
You just look if the frequency of this object is more than once in your list. Then call .distinct() to only have unique elements in your result
result = original.stream()
.filter(e -> Collections.frequency(original, e) > 1)
.distinct()
.collect(Collectors.toList());
// returns {1,3}
// returns only numbers which occur more than once
result = original.stream()
.filter(e -> Collections.frequency(original, e) == 1)
.collect(Collectors.toList());
// returns {2,6,8,7}
// returns numbers which occur only once
result = original.stream()
.distinct()
.collect(Collectors.toList());
// returns {1,2,3,6,8,7}
// returns the list without duplicates
EDIT: As pointed out in recent comments, this solution may BREAK your system.
You most likely don't want to remove python3.
Please refer to the other answers for possible solutions.
Outdated answer (not recommended)
sudo apt-get remove 'python3.*'
You are expecting an id
parameter in your URL but you aren't supplying one. Such as:
http://yoursite.com/controller/edit/12
^^ missing
You can do this:
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>'); _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
You should add an optional hyphen at the beginning by adding -?
(?
is a quantifier meaning one or zero occurrences):
^-?[0-9]\d*(\.\d+)?$
I verified it in Rubular with these values:
10.00
-10.00
and both matched as expected.
The best solution for this is to write a custom assignment_tag
. This solution is more clean than using a with
tag because it achieves a very clear separation between logic and styling.
Start by creating a template tag file (eg. appname/templatetags/hello_world.py
):
from django import template
register = template.Library()
@register.assignment_tag
def get_addressee():
return "World"
Now you may use the get_addressee
template tag in your templates:
{% load hello_world %}
{% get_addressee as addressee %}
<html>
<body>
<h1>hello {{addressee}}</h1>
</body>
</html>
env.OrderByDescending(x => x.ReportDate)
You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire <body>
to load. It goes something like this:
<html>
<head>
<style media="screen" type="text/css">
.layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
.layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
</style>
<script>
function downLoad(){
if (document.all){
document.all["layer1"].style.visibility="hidden";
document.all["layer2"].style.visibility="visible";
} else if (document.getElementById){
node = document.getElementById("layer1").style.visibility='hidden';
node = document.getElementById("layer2").style.visibility='visible';
}
}
</script>
</head>
<body onload="downLoad()">
<div id="layer1" class="layer1_class">
<table width="100%">
<tr>
<td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
</tr>
</table>
</div>
<div id="layer2" class="layer2_class">
<script type="text/javascript">
alert('Just holding things up here. While you are reading this, the body of the page is not loading and the onload event is being delayed');
</script>
Final content.
</div>
</body>
</html>
The onload event won't fire until all of the page has loaded. So the layer2 <DIV>
won't be displayed until the page has finished loading, after which onload will fire.
Here's a technical consideration: will the image be generated dynamically? It tends to be a lot easier to generate the <img>
tag in HTML than to try to dynamically edit a CSS property.
A possible workaround that allows to enable database session timeout without an external scheduled task is to use the extension pg_timeout that I have developped.
You need both a value and a field to assign it to. The value is TableField + 1
, so the assignment is:
SET TableField = TableField + 1
The accepted answer should be the following which was unmultimedio's comment to one of the answers above:
Cmd+K will work, you just need to set again in the Keyboard Shortcuts the workbench.action.terminal.clear to Cmd+K, so it shows as Source: User instead of Source: Default – unmultimedio Mar 12 '19 at 1:13
Importing .cer
certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security
worked for me, as opposed to attemps to generate and use my own keystore.
java_home\jre\lib\security
cmd
and CTRL+SHIFT+ENTERyourAliasName
and path\to\certificate.cer
respectively) ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.
An important example of the use of LSP is in software testing.
If I have a class A that is an LSP-compliant subclass of B, then I can reuse the test suite of B to test A.
To fully test subclass A, I probably need to add a few more test cases, but at the minimum I can reuse all of superclass B's test cases.
A way to realize is this by building what McGregor calls a "Parallel hierarchy for testing": My ATest
class will inherit from BTest
. Some form of injection is then needed to ensure the test case works with objects of type A rather than of type B (a simple template method pattern will do).
Note that reusing the super-test suite for all subclass implementations is in fact a way to test that these subclass implementations are LSP-compliant. Thus, one can also argue that one should run the superclass test suite in the context of any subclass.
See also the answer to the Stackoverflow question "Can I implement a series of reusable tests to test an interface's implementation?"
#collect
is actually an alias for #map
. That means the two methods can be used interchangeably, and effect the same behavior.
git pull
and git rebase
are not interchangeable, but they are closely connected.
git pull
fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull
is similar to git fetch & git merge
.
Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.
You can pull using rebase instead of merge (git pull --rebase
). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.
Atlassian has some excellent documentation on merging vs. rebasing.
If you can't affect your parents elements (like in a nested components situation) you can use height: 100vh
which will make it a full window (=view) height;
You need to enclose your class in {
and }
. A few extra pointers: According to the Java coding conventions, you should
{
on the same line as the method declaration:Here's how I would write it:
public class ModMyMod extends BaseMod {
public String version() {
return "1.2_02";
}
public void addRecipes(CraftingManager recipes) {
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt
});
}
}
I was getting the same problem when running my project. On checking the files structure, I realised that Spring's xml file was inside the project's package and thus couldn't be found. I put it outside the package and it worked just fine.
Looking at the code below, I tried it and found:
Instead of writing DBCon = DBConnection.Instance();
you should put DBConnection DBCon - new DBConnection();
(That worked for me)
and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection());
you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection());
(it's missing the d)
This is a sample spark code which can read the files present on s3
val hadoopConf = sparkContext.hadoopConfiguration
hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
hadoopConf.set("fs.s3.awsAccessKeyId", s3Key)
hadoopConf.set("fs.s3.awsSecretAccessKey", s3Secret)
var jobInput = sparkContext.textFile("s3://" + s3_location)
This was what I was looking for:
# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev
I had the same challenge. This is the solution I found to add users to roles.
internal class Security
{
ApplicationDbContext context = new ApplicationDbContext();
internal void AddUserToRole(string userName, string roleName)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
var user = UserManager.FindByName(userName);
UserManager.AddToRole(user.Id, roleName);
context.SaveChanges();
}
catch
{
throw;
}
}
}
hcpl's methods work perfectly pre-KitKat, but not working with the DocumentsProvider API. For that just simply follow the official Android tutorial for documentproviders: https://developer.android.com/guide/topics/providers/document-provider.html -> open a document, Bitmap section.
Simply I used hcpl's code and extended it: if the file with the retrieved path to the image throws exception I call this function:
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
Tested on Nexus 5.
The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.
Instead of writing
l = []
for n in range(1, 11):
l.append(n)
or
l = [n for n in range(1, 11)]
you should write only
l = range(1, 11)
In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.
To get a new dictionary with all keys set to the same value based on another dict, do this:
old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}
You're receiving a SyntaxError because when you write
d = {}
d[i for i in range(1, 11)] = True
you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like
d[[i for i in range(1, 11)]] = True
and not
d[i for i in range(1, 11)] = True
but lists are not hashable, so you can't use them as dict keys.
In Python 3.2.2, I found \Python32\Lib\idlelib\idle.bat
which was useful because it would let me open python files supplied as args in IDLE.
October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -
(first, install pre-requisites using sudo apt-get install build-essential curl file git)
finally create a ~/.zprofile
with the following contents:
emulate sh -c '. ~/.profile'
There is a button Download ZIP
. If you want to do a sparse checkout there are many solutions on the site. For example here.
You can create a push segue from the source viewcontroller to the destination viewcontroller and give an identifier name like below.
You have to perform a segue from didselectRowAt like this.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue", sender: self)
}
And you can pass the array of the selected item from the below function.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = CategorytableView.indexPathForSelectedRow
let indexNumber = index?.row
print(indexNumber!)
let VC = segue.destination as! AddTransactionVC
VC.val = CategoryData[indexNumber!] . // Here you can pass the entire array instead of an array element.
}
And you have to check the value in viewdidload of destination viewcontroller and then store it into the database.
override func viewDidLoad{
if val != ""{
btnSelectCategory.setTitle(val, for: .normal)
}
}
Per Mikaël Mayer's answer, this is no longer a problem, and my answer is obsolete (go()
now returns 30
after mucking with the console). This was fixed in July 2013, according to the bug report linked above in gabrielmaldi's comment. It alarms me that I'm still getting upvotes - makes me think the upvoter doesn't understand either the question or my answer.
I'll leave my original answer here for historical reasons, but go upvote Mikaël's answer instead.
The trick is that you can't change a local variable directly, but you can modify the properties of an object. You can also modify the value of a global variable:
var g_n = 0;
function go()
{
var n = 0;
var o = { n: 0 };
return g_n + n + o.n; // breakpoint here
}
console:
> g_n = 10
10
> g_n
10
> n = 10
10
> n
0
> o.n = 10
10
> o.n
10
Check the result of go()
after setting the breakpoint and running those calls in the console, and you'll find that the result is 20, rather than 0 (but sadly, not 30).
The key attribute is align-self: center
:
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<p>Without align-self:</p>_x000D_
<img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
<p>With align-self:</p>_x000D_
<img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
Download and extract .zip file having all .dll plugin files under the path
C:\ProgramData\Notepad++\plugins\
Make sure to create a separated folder for each plugin
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
From oldest to newer solutions:
The most portable solution, even older sh
(works with spaces and glob characters) (no loop, faster):
eval printf "'%s\n'" "\"\${$#}\""
Since version 2.01 of bash
$ set -- The quick brown fox jumps over the lazy dog
$ printf '%s\n' "${!#} ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog dog dog dog dog
For ksh, zsh and bash:
$ printf '%s\n' "${@: -1} ${@:~0}" # the space beetwen `:`
# and `-1` is a must.
dog dog
And for "next to last":
$ printf '%s\n' "${@:~1:1}"
lazy
Using printf to workaround any issues with arguments that start with a dash (like -n
).
For all shells and for older sh
(works with spaces and glob characters) is:
$ set -- The quick brown fox jumps over the lazy dog "the * last argument"
$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument
Or, if you want to set a last
var:
$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument
And for "next to last":
$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog
Adding to Andrew's answer, you can even introduce a maxResults
property and use it this way:
$("#auto").autocomplete({
maxResults: 10,
source: function(request, response) {
var results = $.ui.autocomplete.filter(src, request.term);
response(results.slice(0, this.options.maxResults));
}
});
jsFiddle: http://jsfiddle.net/vqwBP/877/
This should help code readability and maintainability!
Remove dist folder and this solve my problem!!
When your XHR request returns a Redirect response (HTTP Status 301, 302, 303, 307), the XMLHttpRequest
automatically follows the redirected URL and returns the status code of that URL.
You can get the non-redirecting status codes (200, 400, 500 etc) via the status
property of the xhr object.
So you cannot get the redirected location from the response header of a 301
, 302
, 303
or 307
request.
You might have to change your server logic to respond in a way that you can handle the redirect, rather than letting the browser do it. An example implementation.
Use git checkout -
You will see Switched to branch <branch_name>
. Confirm it's the branch you want.
Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.
Mnemonic: this approach is a lot like using cd -
to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).
The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.
Use git branch -v
You see a list of existing local branches. Grab the branch name that suits your needs.
Use git checkout <branch_name>
You will see Switched to branch <branch_name>
. Success!
With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>
.
Note that both git checkout -
and git checkout <branch_name>
will give additional instructions if you have committed changes while HEAD was detached.
Update
BlobBuilder has been obsoleted see how you go using it, if you're using it for testing purposes.
Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.
As an alternative there is a Blob that you can use in place of File as it is what File interface derives from as per W3C spec:
interface File : Blob {
readonly attribute DOMString name;
readonly attribute Date lastModifiedDate;
};
The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Using the BlobBuilder like this on an existing JavaScript method that takes a File to upload via XMLHttpRequest
and supplying a Blob to it works fine like this:
var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);
xhr.responseType = 'arraybuffer';
bb.append(this.response); // Note: not xhr.responseText
//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');
/* more setup code */
xhr.send(blob);
The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.
Well, if you are not satisfied with the default setting, you can use ANSI escape code to help you set the color, and if you want to modify some text, you can write bash to help you. see as below:
# .gitconfig
[alias]
st-color = "!f() { \
echo -n -e '\\033[38;2;255;0;01m\\033[4m' ;\
git status -s | grep ' D' | \
sed -e 's/^ ./DELETE:/' ; \
echo -n -e '\\033[m' ;\
\
echo -n -e '\\033[48;2;128;128;128m' ;\
echo -n -e '\\033[38;2;0;255;01m' ;\
git status -s | grep ' [AM]' | \
sed -e 's/^ ./NEW OR MODIFY:/' ; \
echo -n -e '\\033[m' ;\
\
echo -n -e '\\033[38;2;255;0;255m' ;\
echo Rename ;\
git status -s | grep 'R ' | \
sed -e 's/^..//' ; \
echo -n -e '\\033[m' ;\
}; f"
you can write the long script on .gitconfig
use the syntax as below:
[alias]
your-cmd = !f() { \
\
}; f"
echo -n -e
(see more echo)
\\033[38;2;255;0;0m\\033[4m
(see more SGR parameters)
\\033[38;2;255;0;0m
: 38 mean fore color. 255;0;0 = Red | r;g;b\\033[4m
: underlinegrep
: The grep command is used to search text.
sed -e 's/be_replace_string/new_string/'
replace string to new string.
I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:
while (i.hasNext()) {
// code goes here
}
I did one iteration at the start, and then checked for condition using:
do {
// code goes here
} while (i.hasNext());
I hope this will help some people at some stage.
If your constructor is similar to this one:
public Example(String example) {
if (example == null) {
throw new NullPointerException();
}
//do fun things with valid example here
}
Then, when you run this JUnit test you will get a green bar:
@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
Example example = new Example(null);
}
This should do the work:
sed -e 's/[ \t]+/\n/g'
[ \t]
means a space OR an tab. If you want any kind of space, you could also use \s
.
[ \t]+
means as many spaces OR tabs as you want (but at least one)
s/x/y/
means replace the pattern x by y (here \n
is a new line)
The g
at the end means that you have to repeat as many times it occurs in every line.
If Multiset
extends from the Array
class
x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]
x.union(y) # => [1, 2, 4, 7] (ONLY IN RUBY 2.6)
x.union(y, z) # => [1, 2, 4, 7, 3] (ONLY IN RUBY 2.6)
x | y # => [1, 2, 4, 7]
x.difference(y) # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z) # => [4] (ONLY IN RUBY 2.6)
x - y # => [4, 7]
x & y # => [1, 2]
For more info about the new methods in Ruby 2.6, you can check this blog post about its new features
Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.
I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION
) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.
You can use a code like this (adapted from TML response):
$cookies = Array();
$ch = curl_init('http://www.google.com/');
// Ask for the callback.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$result = curl_exec($ch);
var_dump($cookies);
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine); // Needed by curl
}
This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.
The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.
Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:
=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5
the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.
ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.
You can however change the log model to the database to simple so this log does not grow too fast.
Check this for example.
Check here for reference.
I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...
CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"
two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...
start \\filer\repo\lab\"software"\"myapp"\setup.exe
the start code here, can be set up like that, but the correct syntax is
start "\\filter\repo\lab\software\myapp\" setup.exe
This will run: setup.exe, located in: \filter\repo\lab...etc.\
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
Or use directly the InputStream
of the resource using the absolute CLASSPATH path (starting with the /
slash character):
getClass().getResourceAsStream("/com/path/to/file.txt");
Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to
):
getClass().getResourceAsStream("file.txt");
The basic answer is "It depends".
What is your objective in versioning? Many people use version.revision.build and only advertise version.revision to the world as that's a release version rather than a dev version. If you use the check-in 'version' then you'll quickly find that your version numbers become large.
If you are planning your project then I'd increment revision for releases with minor changes and increment version for releases with major changes, bug fixes or functionality/features. If you are offering beta or nightly build type releases then extend the versioning to include the build and increment that with every release.
Still, at the end of the day, it's up to you and it has to make sense to you.
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
I would try the itemStateChanged()
method of the ItemListener
interface if jodonnell's solution fails.
you can give aviation to the view by adding z axis to it and can have default shadow to it. this feature was provided in L preview and will be available after it release. For now you can simply add a image the gives this look for button background
You could also recursively walk through a folder and lists all it's contents using pathlib.Path()
from pathlib import Path
def check_out_path(target_path, level=0):
""""
This function recursively prints all contents of a pathlib.Path object
"""
def print_indented(folder, level):
print('\t' * level + folder)
print_indented(target_path.name, level)
for file in target_path.iterdir():
if file.is_dir():
check_out_path(file, level+1)
else:
print_indented(file.name, level+1)
my_path = Path(r'C:\example folder')
check_out_path(my_path)
Output:
example folder
folder
textfile3.txt
textfile1.txt
textfile2.txt
Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways
Sharing host network --net=host:
docker run -it --net=host myimage
Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface
user@ubuntu:~$ ifconfig
docker0 Link encap:Ethernet HWaddr 02:42:a4:a2:b2:f1
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.
docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage
NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:
Edit postgresql.conf to listen on all addresses. By default it will point to localhost.
listen_addresses = '*'
Edit pg_hba.conf to allow connections from all addresses. Add on the last line:
host all all 0.0.0.0/0 md5
IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.