$variable[0] != "_"
In PHP you can get particular character of a string with array index notation. $variable[0]
is the first character of a string (if $variable is a string).
use try-catch to see real error occurred on you
try
{
//Your insert code here
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
Try figsize
param in df.plot(figsize=(width,height))
:
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));
The size in figsize=(5,3)
is given in inches
per (width, height)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html
It is impossible for both (?=foo)
and (?=baz)
to match at the same time. It would require the next character to be both f
and b
simultaneously which is impossible.
Perhaps you want this instead:
(?=.*foo)(?=.*baz)
This says that foo
must appear anywhere and baz
must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).
No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.
If you are using fish as your shell, the best solution is to create a function. As an example, given the original question, you could copy the 4 lines below and paste them into your fish command line:
function proj
cd /home/tree/projects/java
end
funcsave proj
This will create the function and save it for use later. If your project changes, just repeat the process using the new path.
If you prefer, you can manually add the function file by doing the following:
nano ~/.config/fish/functions/proj.fish
and enter the text:
function proj
cd /home/tree/projects/java
end
and finally press ctrl+x to exit and y followed by return to save your changes.
(NOTE: the first method of using funcsave creates the proj.fish file for you).
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
From Javarevisited blog post:
Here are a few important differences between static and dynamic binding:
- Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
private
,final
andstatic
methods and variables use static binding and are bonded by compiler while virtual methods are bonded during runtime based upon runtime object.- Static binding uses
Type
(class
in Java) information for binding while dynamic binding uses object to resolve binding.- Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest { public static void main(String args[]) { Collection c = new HashSet(); StaticBindingTest et = new StaticBindingTest(); et.sort(c); } //overloaded method takes Collection argument public Collection sort(Collection c) { System.out.println("Inside Collection sort method"); return c; } //another overloaded method which takes HashSet argument which is sub class public Collection sort(HashSet hs) { System.out.println("Inside HashSet sort method"); return hs; } }
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car vehicle.start(); //Car's start called because start() is overridden method } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { @Override public void start() { System.out.println("Inside start method of Car"); } }
Output: Inside start method of Car
Why don't u use:
<script>
$('input').keyup(function(){
if(($('#eng').val().length > 0) && ($('#spa').val().length > 0))
$("#submit").prop('disabled', false);
else
$("#submit").prop('disabled', true);
});
</script>
Then delete the onkeyup function on the input.
It seems that
Unfortunately, webkit browsers do not support styling of option tags yet.
you may find similar question here
The most widely used cross browser solution is to use ul li
Hope it helps!
This means that you should filter the properties of evtListeners with the hasOwnProperty method.
public List<Object> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new {pro.ProjectName,pro.ProjectId};
return query.ToList<Object>();
}
}
window.history.length == 1
This works on Chrome, Firefox, and Edge. You can use the following piece of JQuery code that worked for me on the latest versions of all of the above 3 browsers if you want to hide or remove a back button on your developed web page when there is no window history.
$(window).load(function() {
if (window.history.length == 1) {
$("#back-button").remove();
}
})
Updated answer.
_shutdown
API has been removed in elasticsearch 2.x.
Some options:
In your terminal (dev mode basically), just type "Ctrl-C"
If you started it as a daemon (-d
) find the PID and kill the process: SIGTERM
will shut Elasticsearch down cleanly (kill -15 PID
)
If running as a service, run something like service elasticsearch stop
:
Previous answer. It's now deprecated from 1.6.
Yeah. See admin cluster nodes shutdown documentation
Basically:
# Shutdown local node
$ curl -XPOST 'http://localhost:9200/_cluster/nodes/_local/_shutdown'
# Shutdown all nodes in the cluster
$ curl -XPOST 'http://localhost:9200/_shutdown'
but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
I had to add port via Configuration Manager and add the port number in my sql connection [host]\[db instance name],1433
Note the , (comma) between instancename and port
Another option:
=MID(A1,2,LEN(A1)-2)
Or this (for fun):
=RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)
Considering everyone is posting older ways of hiding the ActionBar here is the proper way of implementing it within styles for AppCompat support library. Which I highly suggest moving toward if you haven't already.
Simply removing the ActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
If you are using the appcompat support libraries, this is the easiest and recommended way of hiding the ActionBar to make full screen or start implementing to toolbar within your layouts.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Your Toolbar Color-->
<item name="colorPrimary">@color/primary</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/primary_dark</item>
<!-- colorAccent is used as the default value for colorControlActivated,
which is used to tint widgets -->
<item name="colorAccent">@color/accent</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight, and colorSwitchThumbNormal. -->
</style>
Then to change your toolbar color
<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:minHeight=”?attr/actionBarSize”
android:background=”?attr/primary” />
Last note: Your Activity class should extend AppCompatActivity
public class MainActivity extends AppCompatActivity {
<!--Activity Items -->
}
Just run this in a console.
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell
It installs the latest version using a Chocolatey repository.
Originally I was using command cinst powershell 3.0.20121027
, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell
refers to version 3.0 of PowerShell, and that may change in future.
See the Chocolatey PowerShell package page for details on what version will be installed.
Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.
If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.
The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.
The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.
I came from PHP, where you can increment char (A to B, Z to AA, AA to AB etc.) using ++ operator. I made a simple function which does the same in Python. You can also change list of chars to whatever (lowercase, uppercase, etc.) is your need.
# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
# Unique and sort
chlist = ''.join(sorted(set(str(chlist))))
chlen = len(chlist)
if not chlen:
return ''
text = str(text)
# Replace all chars but chlist
text = re.sub('[^' + chlist + ']', '', text)
if not len(text):
return chlist[0]
# Increment
inc = ''
over = False
for i in range(1, len(text)+1):
lchar = text[-i]
pos = chlist.find(lchar) + 1
if pos < chlen:
inc = chlist[pos] + inc
over = False
break
else:
inc = chlist[0] + inc
over = True
if over:
inc += chlist[0]
result = text[0:-len(inc)] + inc
return result
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
"The use of the checkbox is to determine what Item in the Listview that I selected"
Just add the tag to checkbox using setTag() method in the Adapter class. and other side using getTag() method.
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ServiceHelper helper=userServices.get(position);
holder.tvServiceName.setText(helper.getServiceName());
if(!helper.isServiceStatus()){
holder.btnAdd.setVisibility(View.VISIBLE);
holder.btnAdd.setTag(helper.getServiceName());
holder.checkBoxServiceStatus.setVisibility(View.INVISIBLE);
}else{
holder.checkBoxServiceStatus.setVisibility(View.VISIBLE);
//This Line
holder.checkBoxServiceStatus.setTag(helper.getServiceName());
holder.btnAdd.setVisibility(View.INVISIBLE);
}
}
In xml code of the checkbox just put the "android:onClick="your method""attribute.
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="checkboxClicked"
android:id="@+id/checkBox_Service_row"
android:layout_marginRight="5dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
In your class Implement that method "your method".
protected void checkboxClicked(View view)
{
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
}
}
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
Here is another example on how you can loop through a document or an element:
function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
//This loop will loop thru the child element list//
for(var z=0;z<l[r].childNodes.length;z++){
//Push the element to the return array.
ret.push(l[r].childNodes[z]);
if(l[r].childNodes[z].childNodes[0]){
l.push(l[r].childNodes[z]);c++;
}//IF
}//FOR
}//FOR
return ret;
}
Patch builtins.open
and use mock_open
, which is part of the mock
framework. patch
used as a context manager returns the object used to replace the patched one:
from unittest.mock import patch, mock_open
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
If you want to use patch
as a decorator, using mock_open()
's result as the new=
argument to patch
can be a little bit weird. Instead, use patch
's new_callable=
argument and remember that every extra argument that patch
doesn't use will be passed to the new_callable
function, as described in the patch
documentation:
patch()
takes arbitrary keyword arguments. These will be passed to theMock
(or new_callable) on construction.
@patch("builtins.open", new_callable=mock_open, read_data="data")
def test_patch(mock_file):
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
Remember that in this case patch
will pass the mocked object as an argument to your test function.
You need to patch __builtin__.open
instead of builtins.open
and mock
is not part of unittest
, you need to pip install
and import it separately:
from mock import patch, mock_open
with patch("__builtin__.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
try
{
..
..
..
}
catch(Exception ex)
{
..
..
..
}
the Exception ex means all the exceptions.
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
This won't win a code golf competition, and borrows from the previous answers - but clearly shows how the key is added, and how the join works. This creates 2 new data frames from lists, then adds the key to do the cartesian product on.
My use case was that I needed a list of all store IDs on for each week in my list. So, I created a list of all the weeks I wanted to have, then a list of all the store IDs I wanted to map them against.
The merge I chose left, but would be semantically the same as inner in this setup. You can see this in the documentation on merging, which states it does a Cartesian product if key combination appears more than once in both tables - which is what we set up.
days = pd.DataFrame({'date':list_of_days})
stores = pd.DataFrame({'store_id':list_of_stores})
stores['key'] = 0
days['key'] = 0
days_and_stores = days.merge(stores, how='left', on = 'key')
days_and_stores.drop('key',1, inplace=True)
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
Use this to remove iframe from parent within iframe itself
frameElement.parentNode.removeChild(frameElement)
It works with same origin only(not allowed with cross origin)
your 8080 port is already used by another application 1/ you can try to find out which app is using it, using "netstat -aon" and stop the process; 2/ you can go to server.xml and change from port 8080 to another one (ex: 8081)
"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.
You can check that with:
$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
Are you using qmake
projects? If so, you can add an external library using the LIBS
variable. E.g:
win32:LIBS += path/to/Psapi.lib
You could use a cross-over ethernet cable - http://en.wikipedia.org/wiki/Ethernet_crossover_cable
Assuming your RPi is a DCHP Client, then best to run a simple DHCP server on your notebook to assign the RPi an IP address.
i solved with a max-width
in my main css-file.
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
It's a simple solution with little "code"
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementYes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
The Answer i was looking for was:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
I've also learned that you can do it this way:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString(myCountryDateFormat);
where myCountryDateFormat can be changed to meet change depending on requirement.
Please note that the tagged "This question may already have an answer here:" has not actually answered the question because as you can see it used a ".Date" instead of omitting it. It's quite confusing for new programmers of .NET
For the AngularJS from meanjs.org, I place the custom filters in modules/core/client/app/init.js
I needed a custom filter to capitalize each word in a sentence, here is how I do so:
angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : ''}).join(" ");
}
});
The credit of the map function goes to @Naveen raj
Sometimes in situations like this I miss my youth, when Access was my poison of choice, and I could give each radio button in a group its own value.
My hack in C# is to use the tag to set the value, and when I make a selection from the group, I read the value of the tag of the selected radiobutton. In this example, directionGroup is the group in which I have four five radio buttons with "None" and "NE", "SE", "NW" and "SW" as the tags on the other four radiobuttons.
I proactively used a button to capture the value of the checked button, because because assigning one event handler to all of the buttons' CHeckCHanged event causes EACH button to fire, because changing one changes them all. So the value of sender is always the first RadioButton in the group. Instead, I use this method when I need to find out which one is selected, with the values I want to retrieve in the Tag property of each RadioButton.
private void ShowSelectedRadioButton()
{
List<RadioButton> buttons = new List<RadioButton>();
string selectedTag = "No selection";
foreach (Control c in directionGroup.Controls)
{
if (c.GetType() == typeof(RadioButton))
{
buttons.Add((RadioButton)c);
}
}
var selectedRb = (from rb in buttons where rb.Checked == true select rb).FirstOrDefault();
if (selectedRb!=null)
{
selectedTag = selectedRb.Tag.ToString();
}
FormattableString result = $"Selected Radio button tag ={selectedTag}";
MessageBox.Show(result.ToString());
}
FYI, I have tested and used this in my work.
Joey
You need to install tkinter for python3.
On Fedora pip3 install tkinter --user
returns Could not find a version that satisfies the requirement
... so I have to command: dnf install python3-tkinter
. This have solved my problem
A tad more generic copy/paste function for your project.
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
I try to explain it more understandably than the referred PostgreSQL documentation.
Neither TIMESTAMP
variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:
TIMESTAMP WITHOUT TIME ZONE
stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30'
, then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00'
and '2011-07-01 06:30:30+05'
are the same as just '2011-07-01 06:30:30'
.
For Java developers: it's analogous to java.time.LocalDateTime
.
TIMESTAMP WITH TIME ZONE
stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The
input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30'
) it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'
). The output is displayed converted to the current time zone of the PostgreSQL session.
For Java developers: It's analogous to java.time.Instant
(with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime
(or to java.util.Date
or java.sql.Timestamp
of course).
Some say that both TIMESTAMP
variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE
is stored like a TIMESTAMP WITH TIME ZONE
, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)
try this
[yourTableView setBounces:NO];
# Set the HEAD to the old commit that we want to tag
git checkout 9fceb02
# temporarily set the date to the date of the HEAD commit, and add the tag
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" \
git tag -a v1.2 -m"v1.2"
# set HEAD back to whatever you want it to be
git checkout master
The answer by @dkinzer creates tags whose date is the current date (when you ran the git tag
command), not the date of the commit. The Git help for tag
has a section "On Backdating Tags" which says:
If you have imported some changes from another VCS and would like to add tags for major releases of your work, it is useful to be able to specify the date to embed inside of the tag object; such data in the tag object affects, for example, the ordering of tags in the gitweb interface.
To set the date used in future tag objects, set the environment variable
GIT_COMMITTER_DATE
(see the later discussion of possible values; the most common form is "YYYY-MM-DD HH:MM").For example:
$ GIT_COMMITTER_DATE="2006-10-02 10:31" git tag -s v1.0.1
The page "How to Tag in Git" shows us that we can extract the time of the HEAD commit via:
git show --format=%aD | head -1
#=> Wed, 12 Feb 2014 12:36:47 -0700
We could extract the date of a specific commit via:
GIT_COMMITTER_DATE="$(git show 9fceb02 --format=%aD | head -1)" \
git tag -a v1.2 9fceb02 -m "v1.2"
However, instead of repeating the commit twice, it seems easier to just change the HEAD to that commit and use it implicitly in both commands:
git checkout 9fceb02
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" git tag -a v1.2 -m "v1.2"
Since the range of numbers is constrained, I'd say the best thing to do is generate the array, fill it with numbers zero through 39 (in order), then shuffle it.
You can use too
style="overflow-y: scroll; height:150px; width: auto;"
It's works for me
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.
Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios
I'm using next approach:
ProductID OrderID,...
ProductID Title Name LanguageID
LanguageID Name Culture,....
This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.
string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");
string marRes = string.Join(Environment.NewLine, lines.ToArray());
Hopefully may help Someone!!!!
Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:
var result = {};
for ( let { first_field, ...fields } of your_data )
{
result[first_field] = result[first_field] || [];
result[first_field].push({ ...fields });
}
I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.
So, I had to generate the SSL certificate again and it started working...
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt
var first_value = '2';
// convert this string value into int
parseInt(first_value);
The pythonic way would be:
mystring = 'Hello World, this should work!'
find_all = lambda c,s: [x for x in range(c.find(s), len(c)) if c[x] == s]
# s represents the search string
# c represents the character string
find_all(mystring,'o') # will return all positions of 'o'
[4, 7, 20, 26]
>>>
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now
"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
I think it's better to change your csv file like:
"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov
It's also possible to define your table like
CREATE TABLE people (
age varchar(20),
first_name varchar(20),
last_name varchar(20)
);
and after copy, you can convert empty strings:
select nullif(age, '')::int as age, first_name, last_name
from people
Contrary to all the other posts I suggest NOT using sudo
when installing gems.
Instead I recommend you install RVM and start a happy life with portable gem homes and different version of Ruby all living under one roof.
For the uninitiated, from the documentation:
RVM is a command line tool which allows us to easily install, manage and work with multiple ruby environments and sets of gems.
The reason why installing gems with sudo
is worse than just gem install
is because it installs the gems for ALL USERS as root
. This might be fine if you're the only person using the machine, but if you're not it can cause weirdness.
If you decide you want to blow away all your gems and start again it's much easier, and safer, to do so as a non-root user.
If you decide you want to use RVM
then using sudo
will cause all kinds of weirdness because each Ruby version you install through RVM
has its own GEM_HOME.
Also, it's nice if you can make your development environment as close to your production environment as possible, and in production you'll most likely install gems as a non-root user.
Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.
class Point2D {
double X, Y;
public Point2D(double x, double y) {
init(x, y);
}
public Point2D(Point2D point) {
if (point == null)
throw new ArgumentNullException("point");
init(point.X, point.Y);
}
void init(double x, double y) {
// ... Contracts ...
X = x;
Y = y;
}
}
[0-9]{4,6}
can be shortened to \d{4,6}
If you want to create a simple hyperlink instead of the pin it button,
Change this:
http://pinterest.com/pin/create/button/?url=
To this:
http://pinterest.com/pin/create/link/?url=
So, a complete URL might simply look like this:
<a href="//pinterest.com/pin/create/link/?url=http%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&description=Next%20stop%3A%20Pinterest">Pin it</a>
Try this my friend
// Confirmation Message On Delete Button._x000D_
_x000D_
$('.close').click(function() {_x000D_
return confirm('Are You Sure ?')_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<td class='close'></td>
_x000D_
You should check it against null
.
If you want to check if object x is null or not, you can do:
if(x != null)
But if it is not null, it can have properties which are null or empty. You will check those explicitly:
if(x.getProperty() != null)
For "empty" check, it depends on what type is involved. For a Java String
, you usually do:
if(str != null && !str.isEmpty())
As you haven't mentioned about any specific problem with this, difficult to tell.
None of this answers was working for me (Nuget 2.8.6) because of missing some tips, will try to add them here as it might be useful for others.
After reading the following sources:
https://docs.nuget.org/consume/NuGet-Config-Settings
https://github.com/NuGet/Home/issues/1346
It appears that
E.g.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<config>
<add key="repositorypath" value="$/../../../Common/packages" />
</config>
</configuration>
You can also use NuGet command to ensure that syntax will be correct like this:
NuGet.exe config -Set repositoryPath=$/../../../Common/packages -ConfigFile NuGet.Config
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
I can't assign a null to a String?
No. std::string
is not a pointer type; it cannot be made "null." It cannot represent the absence of a value, which is what a null pointer is used to represent.
It can be made empty, by assigning an empty string to it (s = ""
or s = std::string()
) or by clearing it (s.clear()
).
The DoEvents does allow the user to click around or type and trigger other events, and background threads are a better approach.
However, there are still cases where you may run into issues that require flushing event messages. I ran into a problem where the RichTextBox control was ignoring the ScrollToCaret() method when the control had messages in queue to process.
The following code blocks all user input while executing DoEvents:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Integrative.Desktop.Common
{
static class NativeMethods
{
#region Block input
[DllImport("user32.dll", EntryPoint = "BlockInput")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt);
public static void HoldUser()
{
BlockInput(true);
}
public static void ReleaseUser()
{
BlockInput(false);
}
public static void DoEventsBlockingInput()
{
HoldUser();
Application.DoEvents();
ReleaseUser();
}
#endregion
}
}
A "connection reset" error message generally means that the other side has aborted the connection during the attempt to create a connection (the handshake). This has a lot of possible causes. A bug in the JDBC driver, a timeout at the DB side, a restart of the database, the DB being run out of available connections, poor network quality, bad virusscanner/firewall/proxy, etc.
As it happens intermittely, a bug in the JDBC driver can be less or more excluded. Left behind the remaining possible causes. I suggest to start with looking in the logs of the DB server.
You should store your images, css and JS files in a public
directory. To create a link to any of them, use asset()
helper:
{{ asset('img/myimage.png') }}
https://laravel.com/docs/5.1/helpers#method-asset
As alternative, you could use amazing Laravel Collective package for building forms and HTML elements, so your code will look like this:
{{ HTML::image('img/myimage.png', 'a picture') }}
Remove padding between cells inside the table. Just use cellpadding=0
and cellspacing=0
attributes in table tag.
You can use css modules as an alternative, and additionally react-css-modules for class name mapping.
That way you can import your styles as follows and use normal css scoped locally to your components:
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';
class Table extends React.Component {
render () {
return <div styleName='table'>
<div styleName='row'>
<div styleName='cell'>A0</div>
<div styleName='cell'>B0</div>
</div>
</div>;
}
}
export default CSSModules(Table, styles);
Here is a webpack css modules example
Is very simple to clone the last row with jquery pressing a button:
Your Table HTML:
<table id="tableExample">
<thead>
<tr>
<th>ID</th>
<th>Header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Line 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"><button type="button" id="addRowButton">Add row</button></td>
</tr>
</tfoot>
</table>
JS:
$(document).on('click', '#addRowButton', function() {
var table = $('#tableExample'),
lastRow = table.find('tbody tr:last'),
rowClone = lastRow.clone();
table.find('tbody').append(rowClone);
});
Regards!
Also add this bit of code to your form to allow it to be draggable still.
Just add it right before the constructor (the method that calls InitializeComponent()
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
///
/// Handling the window messages
///
protected override void WndProc(ref Message message)
{
base.WndProc(ref message);
if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
message.Result = (IntPtr)HTCAPTION;
}
That code is from: https://jachman.wordpress.com/2006/06/08/enhanced-drag-and-move-winforms-without-having-a-titlebar/
Now to get rid of the title bar but still have a border combine the code from the other response:
this.ControlBox = false;
this.Text = String.Empty;
with this line:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Put those 3 lines of code into the form's OnLoad event and you should have a nice 'floating' form that is draggable with a thin border (use FormBorderStyle.None if you want no border).
You can't access non-static members from a static method. (Note that Main()
is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:
static private long volteado(long a)
Try this sample SQL scripts for easy understanding,
CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))
--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2
INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'
INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'
SELECT * FROM TABLE1
SELECT * FROM TABLE2
DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO
Your case is:
DELETE pgc
FROM guide_category pgc
LEFT JOIN guide g
ON g.id_guide = gc.id_guide
WHERE g.id_guide IS NULL
list1 = [10,-4,5,2,33,4,7,8,2,3,5,8,99,-34]
print(list1)
max_v=list1[0]
min_v=list1[0]
for x in list1:
if x>max_v:
max_v=x
print('X is {0} and max is {1}'.format(x,max_v))
for x in list1:
if x<min_v:
min_v=x
print('X is {0} and min is {1}'.format(x,min_v))
print('Max values is ' + str(max_v))
print('Min values is ' + str(min_v))
For a comprehensive and continually growing collection of links check AngularJS-Learning, a github repo that collects resources, links and interesting blog posts.
I've found very helpful the tutorials and videos on the AngularJS youtube channel. They go from the mostly basic stuff to some advanced topics, a good way to start.
The official twitter and google+ accounts are a good way to follow news and get some nice links. Also check the AngularJS Mailing list.
A nice aggregator of news/link is angularjsdaily.com.
Also there're some new books out there, so you can keep an eye on your favourite online library.
The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).
import numpy as np
import matplotlib.pyplot as plt
N = 3
ind = np.arange(N) # the x locations for the groups
width = 0.27 # the width of the bars
fig = plt.figure()
ax = fig.add_subplot(111)
yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')
ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
No need for an onchange function. You can grab the value in one line:
document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;
Or, split it up for better readability:
var select_id = document.getElementById("select_id");
select_id.options[select_id.selectedIndex].value;
it could be done when the RowDataBound
event fires
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Hide the edit button when some condition is true
// for example, the row contains a certain property
if (someCondition)
{
Button btnEdit = (Button)e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
}
Here's a demo page
markup
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView OnRowDataBound Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="name" />
<asp:BoundField HeaderText="Age" DataField="age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace GridViewDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
protected override void OnInit(EventArgs e)
{
GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
base.OnInit(e);
}
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
int age;
if (int.TryParse(e.Row.Cells[1].Text, out age))
if (age == 30)
{
Button btnEdit = (Button) e.Row.FindControl("btnEdit");
btnEdit.Visible = false;
}
}
private static List<Customer> GetCustomers()
{
List<Customer> results = new List<Customer>();
results.Add(new Customer("Steve", 30));
results.Add(new Customer("Brian", 40));
results.Add(new Customer("Dave", 50));
results.Add(new Customer("Bill", 25));
results.Add(new Customer("Rich", 22));
results.Add(new Customer("Bert", 30));
return results;
}
}
public class Customer
{
public string Name {get;set;}
public int Age { get; set; }
public Customer(string name, int age)
{
Name = name;
Age = age;
}
}
}
In the demo, the Edit Button is not Visible (the HTML markup is not sent to the client) in those rows where the Customer's age is 30.
You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.
$('#myTextbox').on('input', function() {
// do something
});
If you use the change
handler, this will only fire after the user deselects the input box, which may not be what you want.
There is an example of both here: http://jsfiddle.net/6bSX6/
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
function rgb(...values){
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0'+val : val);
}, '').toUpperCase();
}
this.setState creates an infinite loop when used in ComponentDidUpdate when there is no break condition in the loop. You can use redux to set a variable true in the if statement and then in the condition set the variable false then it will work.
Something like this.
if(this.props.route.params.resetFields){
this.props.route.params.resetFields = false;
this.setState({broadcastMembersCount: 0,isLinkAttached: false,attachedAffiliatedLink:false,affilatedText: 'add your affiliate link'});
this.resetSelectedContactAndGroups();
this.hideNext = false;
this.initialValue_1 = 140;
this.initialValue_2 = 140;
this.height = 20
}
git config --global core.editor "atom --wait"
Atom needs to be configured to run from the command line for the above to work:
OS X: install shell commands from Atom: menu bar > Atom > Install Shell Commands
Windows: no action required - atom is configured to run from the command line by default
There are several C sorting functions available in stdlib.h
. You can do man 3 qsort
on a unix machine to get a listing of them but they include:
$($("li").get().reverse()).each(function() { /* ... */ });
User order by with that field, and then do distinct.
ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()
You can use timespan
TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString()); // Displays "02:14:18".
[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.
I wrote this program to do the math for you. Just enter in the summary statistics. No need to provide an array:
One-Sample Z-Test for a Population Proportion:
To do this for mean rather than proportion, change the formula for z accordingly
EDIT:
Here is the content from the link:
import scipy.stats as stats
import math
def one_sample_ztest_pop_proportion(tail, p, pbar, n, alpha):
#Calculate test stat
sigma = math.sqrt((p*(1-p))/(n))
z = round((pbar - p) / sigma, 2)
if tail == 'lower':
pval = round(stats.norm(p, sigma).cdf(pbar),4)
print("Results for a lower tailed z-test: ")
elif tail == 'upper':
pval = round(1 - stats.norm(p, sigma).cdf(pbar),4)
print("Results for an upper tailed z-test: ")
elif tail == 'two':
pval = round(stats.norm(p, sigma).cdf(pbar)*2,4)
print("Results for a two tailed z-test: ")
#Print test results
print("Test statistic = {}".format(z))
print("P-value = {}".format(pval))
print("Confidence = {}".format(alpha))
#Compare p-value to confidence level
if pval <= alpha:
print("{} <= {}. Reject the null hypothesis.".format(pval, alpha))
else:
print("{} > {}. Do not reject the null hypothesis.".format(pval, alpha))
#one_sample_ztest_pop_proportion('upper', .20, .25, 400, .05)
#one_sample_ztest_pop_proportion('two', .64, .52, 100, .05)
Think about it as array of array.
If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n
For this your declaration looks like
String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];
etc..
The most straightforward way (in my opinion) would be to simply put together a CSV file. If you want to get into formatting and actually writing to a *.xlsx file, there are more complicated solutions (and APIs) to do that for you.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
Some additional steps may be needed to set both the project and default workspace JRE correctly, as MayoMan mentioned. Here is the complete sequence in Eclipse Luna:
Easy.... not.
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
Just add this namespace,
using System.Linq;
your startDate is first-day-of-month, In this case we can use
var endDate = moment(startDate).add(1, 'months').subtract(1, 'days');
Hope this helps!!
Here is an example on Python 3.x
, much simpler than 2.x
:
import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
from_email='[email protected]'):
# import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ', '.join(to_email)
msg.set_content(message)
print(msg)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.login(from_email, 'password') # user & password
server.send_message(msg)
server.quit()
print('successfully sent the mail.')
call this function:
send_mail(to_email=['[email protected]', '[email protected]'],
subject='hello', message='Your analysis has done!')
If you use 126/163, ????, you need to set"???????", like below:
ref: https://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples
As pointed out by Brani, vector() is a solution, e.g.
newVector <- vector(mode = "numeric", length = 50)
will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.
aVector <- c(aVector, newScalar)
The php.ini file that needs edit is different in this case. In my WAMP installation the php.ini file that is loaded in command line is:
\wamp\bin\php\php5.5.12\php.ini
instead of \wamp\bin\apache\apache2.4.9\bin\php.ini which loads when php is run from browser
Something like this should do:
function cleanLocalStorage() {
for(key in localStorage) {
delete localStorage[key];
}
}
Be careful about using this, though, as the user may have other data stored in localStorage
and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage
or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage
.
Edit: As Lyn pointed out, you'll be good with localStorage.clear()
. My previous points still stand, however.
AFAIK there is no native jquery function that does this. Best option would be to process the conversion on the server. How you do this depends on what language you are using (.net, php etc.). You can pass the content of the div to the function that handles the conversion, which would return a pdf to the user.
After 1.13.0, Docker includes a new command docker system df
to show docker disk usage.
$ docker system df
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 5 1 2.777 GB 2.647 GB (95%)
Containers 1 1 0 B 0B
Local Volumes 4 1 3.207 GB 2.261 (70%)
To show more detailed information on space usage:
$ docker system df --verbose
You can use Github Contents API to get an archive link and tar
to retrieve a specified folder.
curl https://codeload.github.com/[owner]/[repo]/tar.gz/master | \ tar -xz --strip=2 [repo]-master/[folder_path]
For example,
if you want to download examples/with-apollo/ folder from zeit/next.js, you can type this:
curl https://codeload.github.com/zeit/next.js/tar.gz/master | \
tar -xz --strip=2 next.js-master/examples/with-apollo
//Method for Smaller Number Range:
Integer.parseInt("abc",16);
//Method for Bigger Number Range.
Long.parseLong("abc",16);
//Method for Biggest Number Range.
new BigInteger("abc",16);
I fixed this issue by moving my directory from my exFAT drive which does not support symlinking.
My exFat drive is shared between osx and a bootcamp windows partition so when I tried to clone and npm install my project it was failing but never explains that exFAT doesn't support this functionality.
There are drivers out there that you can install to add the ability to symlink but you'll have to do a lot of your setup manually compared to running a simple npm script.
I use android studio in Windows 7 and i have AVG for antivirus. The first time you launch adb, AVG prompts you to add avg.exe in antivirus vault. If you accept, then you android studio dont have access to run adb.exe. So open avg >> options >> Virus Vault >> Restore (select the adb file)
Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.
public static int findIndex(int arr[], int t) {
int index = Arrays.binarySearch(arr, t);
return (index < 0) ? -1 : index;
}
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.
If you really want to use VBA I believe you could select first character
strSpace = left(range("A1").Value,1)
and use replace function in VBA the same way
Range("A1").Value = Replace(Range("A1").Value, strSpace, "")
or
for each cell in selection.cells
cell.value = replace(cell.value, strSpace, "")
next
By using ''.join
list1 = ['1', '2', '3']
str1 = ''.join(list1)
Or if the list is of integers, convert the elements before joining them.
list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)
In your current code, what Dictionary.update()
does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.
If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list
as a list and then append case
to it (instead of update) .
Example -
case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)
Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1
or entry2
, etc and the value being the corresponding dictionary for that entry.
case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.
The problem located on the following line
SELECT @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))
Use this instead
SELECT @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
Full Code:
CREATE PROC [dbo].[getVoucherNo]
AS
BEGIN
DECLARE @Prefix VARCHAR(10)='J'
DECLARE @startFrom INT=1
DECLARE @maxCode VARCHAR(100)
DECLARE @sCode INT
IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(VoucharNo,LEN(@startFrom)+1,LEN(VoucharNo)- LEN(@Prefix)) AS INT))+1 AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
SELECT @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
END
ELSE
BEGIN
SELECT(@Prefix + CAST(@startFrom AS VARCHAR))
END
END
In listView you can use it by Adapter
ArrayAdapter<String> adapterChannels = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice);
Select into creates new table for you at the time and then insert records in it from the source table. The newly created table has the same structure as of the source table.If you try to use select into for a existing table it will produce a error, because it will try to create new table with the same name. Insert into requires the table to be exist in your database before you insert rows in it.
You should use a Set
. A Set
is a Collection that contains no duplicates.
If you have a List
that contains duplicates, you can get the unique entries like this:
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
NOTE: This HashSet
constructor identifies duplicates by invoking the elements' equals() methods.
You could use crypto-js.
I would also recommend using SHA256, rather than MD5.
To install crypto-js via NPM:
npm install crypto-js
Alternatively you can use a CDN and reference the JS file.
Then to display a MD5 and SHA256 hash, you can do the following:
<script type="text/javascript">
var md5Hash = CryptoJS.MD5("Test");
var sha256Hash = CryptoJS.SHA256("Test1");
console.log(md5Hash.toString());
console.log(sha256Hash.toString());
</script>
Working example located here, JSFiddle
There are also other JS functions that will generate an MD5
hash, outlined below.
http://www.myersdaily.org/joseph/javascript/md5-text.html
http://pajhome.org.uk/crypt/md5/md5.html
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}
Then simply use the MD5 function, as shown below:
alert(md5("Test string"));
Another working JS Fiddle here
I used this query and it worked for me:
CREATE EVENT `exec`
ON SCHEDULE EVERY 5 SECOND
STARTS '2013-02-10 00:00:00'
ENDS '2015-02-28 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE
DO
call delete_rows_links();
Here the still lacking lubridate
answer (although Gregor's function is built on this package)
The lubridate timespan documentation is very helpful for understanding the difference between periods and duration. I also like the lubridate cheatsheet and this very useful thread
library(lubridate)
dates <- c(dmy('14.01.2013'), dmy('26.03.2014'))
span <- dates[1] %--% dates[2] #creating an interval object
#creating period objects
as.period(span, unit = 'year')
#> [1] "1y 2m 12d 0H 0M 0S"
as.period(span, unit = 'month')
#> [1] "14m 12d 0H 0M 0S"
as.period(span, unit = 'day')
#> [1] "436d 0H 0M 0S"
Periods do not accept weeks as units. But you can convert durations to weeks:
as.duration(span)/ dweeks(1)
#makes duration object (in seconds) and divides by duration of a week (in seconds)
#> [1] 62.28571
Created on 2019-11-04 by the reprex package (v0.3.0)
NO boost REQUIRED, which would be an overkill.
Use stat() (not cross platform though as mentioned by pavon), like this:
#include <sys/stat.h>
#include <iostream>
// true if file exists
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
int main() {
if(!fileExists("test.txt")) {
std::cerr << "test.txt doesn't exist, exiting...\n";
return -1;
}
return 0;
}
Output:
C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt
ls: test.txt: No such file or directory
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
test.txt doesn't exist, exiting...
Another version (and that) can be found here.
I store my non-Github repo's on Dropbox. One caveat I ran into was syncing after a reinstall. Dropbox will download the smallest files first before moving to the larger ones. Not an issue if you start at night and come back after the weekend :-)
My thread - http://forums.dropbox.com/topic.php?id=29984&replies=6
Mixaz's above answer worked for me. However I had issues installing the package because of PGP check failures. Installing it by skipping the signature worked, you could try this :
yaourt --m-arg "--skipchecksums --skippgpcheck" -Sb <your-package>
You have to make a new instance of OrderedDict
. If your keys are unique:
d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("d",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)
#OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)])
But if not, beware as this behavior may or may not be desired for you:
d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("b",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)
#OrderedDict([('c', 3), ('b', 2), ('a', 1)])
String in C# is immutable. If you concatenate it with any string, you are actually making a new string, that is new string object ! But StringBuilder creates mutable string.
You are using a transaction; autocommit does not disable transactions, it just makes them automatically commit at the end of the statement.
What is happening is, some other thread is holding a record lock on some record (you're updating every record in the table!) for too long, and your thread is being timed out.
You can see more details of the event by issuing a
SHOW ENGINE INNODB STATUS
after the event (in sql
editor). Ideally do this on a quiet test-machine.
As others mentioned using epel
gives a really outdated version, here is a little script I just wrote instead to add to the CI pipeline or pass it to ec2 user-data
to install the latest version of node, simply replace the version
with what you want, and the appropriate distro
of Linux you are using.
The following example is for amazon-Linux-2-AMI
#!/bin/bash
version='v14.13.1'
distro='linux-x64'
package_name="node-$version-$distro"
package_location="/usr/local/lib/"
curl -O https://nodejs.org/download/release/latest/$package_name.tar.gz
tar -xvf $package_name.tar.gz -C $package_location
rm -rfv $package_name.tar.gz
echo "export PATH=$package_location/$package_name/bin:\$PATH" >> ~/.profile
if you want to test it in the same shell simply run
. ~/.profile
And for SBT : excludeDependencies += "log4j" % "log4j"
As well as using lapply
or some other looping construct in R you could merge your CSV files into one file.
In Unix, if the files had no headers, then its as easy as:
cat *.csv > all.csv
or if there are headers, and you can find a string that matches headers and only headers (ie suppose header lines all start with "Age"), you'd do:
cat *.csv | grep -v ^Age > all.csv
I think in Windows you could do this with COPY
and SEARCH
(or FIND
or something) from the DOS command box, but why not install cygwin
and get the power of the Unix command shell?
I have detected something different from the other answers. Reaching this exception in my project was the result of a corrupt compilation. Without making any changes, just forcing rebuild, it was fixed.
run this
// you'll see that it prints Object
console.log(typeof document.location);
you want document.location.toString()
or document.location.href
I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run
from PyQt4.QtCore import SIGNAL
from a python interpreter but only without activating my virtualenv.
The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
This works!
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<http.Response> postRequest () async {
var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map data = {
'apikey': '12345678901234567890'
}
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: {"Content-Type": "application/json"},
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project
QuartzCore.framework
For the bug
Undefined symbols for architecture i386:
Using the Application Class
Depending on what you're doing in your initialization you could consider creating a new class that extends Application
and moving your initialization code into an overridden onCreate
method within that class.
public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
The onCreate
in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.
It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.
NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:
<application
android:name="com.you.yourapp.MyApplicationClass"
Reacting to Configuration Changes [UPDATE: this is deprecated since API 13; see the recommended alternative]
As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.
Start by adding the android:configChanges
node to your Activity's manifest node
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
or for Android 3.2 (API level 13) and newer:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
Then within the Activity override the onConfigurationChanged
method and call setContentView
to force the GUI layout to be re-done in the new orientation.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}
/
starts from the root only, to get the relative path we should use ./
or ../
I've found a solution (on makandracards page), that gives just the newest file name:
ls -1tr * | tail -1
(thanks goes to Arne Hartherz)
I used it for cp
:
cp $(ls -1tr * | tail -1) /tmp/
Expanding on zoul's answer:
If you want to setup Vim to use specific settings when editing a particular filetype, you'll want to use autocommands:
autocmd Filetype css setlocal tabstop=4
This will make it so that tabs are displayed as 4 spaces. Setting expandtab
will cause Vim to actually insert spaces (the number of them being controlled by tabstop
) when you press tab; you might want to use softtabstop
to make backspace work properly (that is, reduce indentation when that's what would happen should tabs be used, rather than always delete one char at a time).
To make a fully educated decision as to how to set things up, you'll need to read Vim docs on tabstop
, shiftwidth
, softtabstop
and expandtab
. The most interesting bit is found under expandtab
(:help 'expandtab
):
There are four main ways to use tabs in Vim:
Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.
Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' is changed.
I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:
$("#id").on('click', function(){ //enables click event
//do your thing here
});
$("#id").off('click'); //disables click event
If you want to disable a div, use the following code:
$("#id").attr('disabled','disabled');
Hope this helps.
edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
A simple example of escaping quotes in the shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's done by finishing an already-opened one ('
), placing the escaped one (\'
), and then opening another one ('
).
Alternatively:
$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc
It's done by finishing already opened one ('
), placing a quote in another quote ("'"
), and then opening another one ('
).
More examples: Escaping single-quotes within single-quoted strings
I had trouble with the other DatabaseHelpers regarding this problem, not sure why.
This is what worked for me:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
private final Context context;
private final String assetPath;
private final String dbPath;
public DatabaseHelper(Context context, String dbName, String assetPath)
throws IOException {
super(context, dbName, null, 1);
this.context = context;
this.assetPath = assetPath;
this.dbPath = "/data/data/"
+ context.getApplicationContext().getPackageName() + "/databases/"
+ dbName;
checkExists();
}
/**
* Checks if the database asset needs to be copied and if so copies it to the
* default location.
*
* @throws IOException
*/
private void checkExists() throws IOException {
Log.i(TAG, "checkExists()");
File dbFile = new File(dbPath);
if (!dbFile.exists()) {
Log.i(TAG, "creating database..");
dbFile.getParentFile().mkdirs();
copyStream(context.getAssets().open(assetPath), new FileOutputStream(
dbFile));
Log.i(TAG, assetPath + " has been copied to " + dbFile.getAbsolutePath());
}
}
private void copyStream(InputStream is, OutputStream os) throws IOException {
byte buf[] = new byte[1024];
int c = 0;
while (true) {
c = is.read(buf);
if (c == -1)
break;
os.write(buf, 0, c);
}
is.close();
os.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Use sort_values
to sort the df by a specific column's values:
In [18]:
df.sort_values('2')
Out[18]:
0 1 2
4 85.6 January 1.0
3 95.5 February 2.0
7 104.8 March 3.0
0 354.7 April 4.0
8 283.5 May 5.0
6 238.7 June 6.0
5 152.0 July 7.0
1 55.4 August 8.0
11 212.7 September 9.0
10 249.6 October 10.0
9 278.8 November 11.0
2 176.5 December 12.0
If you want to sort by two columns, pass a list of column labels to sort_values
with the column labels ordered according to sort priority. If you use df.sort_values(['2', '0'])
, the result would be sorted by column 2
then column 0
. Granted, this does not really make sense for this example because each value in df['2']
is unique.
As mentioned by T.J., There is no assert
in JavaScript.
However, there is a node module named assert, which is used mostly for testing. so, you might see code like:
const assert = require('assert');
assert(5 > 7);
single/double quotes
and backslash
everywhere:
$ python -c 'exec("import sys\nfor i in range(10): print \"bob\"")'
Much better:
$ python -c '
> import sys
> for i in range(10):
> print "bob"
> '
Note: this answer is only valid for git v1.8 and older.
Most of this has been said in the other answers and comments, but here's a concise explanation:
git fetch
fetches all branch heads (or all specified by the remote.fetch config option), all commits necessary for them, and all tags which are reachable from these branches. In most cases, all tags are reachable in this way.git fetch --tags
fetches all tags, all commits necessary for them. It will not update branch heads, even if they are reachable from the tags which were fetched.Summary: If you really want to be totally up to date, using only fetch, you must do both.
It's also not "twice as slow" unless you mean in terms of typing on the command-line, in which case aliases solve your problem. There is essentially no overhead in making the two requests, since they are asking for different information.
You can use the code below:
li:hover { cursor: pointer; }
<script language="JavaScript">
function importXML()
{
if (document.implementation && document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = createTable;
}
else if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.onreadystatechange = function () {
if (xmlDoc.readyState == 4) createTable()
};
}
else
{
alert('Your browser can\'t handle this script');
return;
}
xmlDoc.load("emperors.xml");
}
function createTable()
{
var theData="";
var x = xmlDoc.getElementsByTagName('emperor');
var newEl = document.createElement('TABLE');
newEl.setAttribute('cellPadding',3);
newEl.setAttribute('cellSpacing',0);
newEl.setAttribute('border',1);
var tmp = document.createElement('TBODY');
newEl.appendChild(tmp);
var row = document.createElement('TR');
for (j=0;j<x[0].childNodes.length;j++)
{
if (x[0].childNodes[j].nodeType != 1) continue;
var container = document.createElement('TH');
theData = document.createTextNode(x[0].childNodes[j].nodeName);
container.appendChild(theData);
row.appendChild(container);
}
tmp.appendChild(row);
for (i=0;i<x.length;i++)
{
var row = document.createElement('TR');
for (j=0;j<x[i].childNodes.length;j++)
{
if (x[i].childNodes[j].nodeType != 1) continue;
var container = document.createElement('TD');
var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
container.appendChild(theData);
row.appendChild(container);
}
tmp.appendChild(row);
}
document.getElementById('writeroot').appendChild(newEl);
}
</script>
</HEAD>
<BODY onLoad="javascript:importXML();">
<p id=writeroot> </p>
</BODY>
For more info refer this http://www.easycodingclub.com/xml-parser-in-javascript/javascript-tutorials/
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
td {
overflow: hidden;
max-width: 400px;
word-wrap: break-word;
}
Use single quotation marks ('
):
var val = '@ViewBag.ForSection';
alert(val);
In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.
All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!
The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.
Ex.(each element has 2 sides so border, margin and padding get multiplied x2)
So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32
Then add all of your element's totaled widths together.
Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24
In this example the width for the "outer" div would be 112.
.outer {_x000D_
/* floats + margins + borders = 270 */_x000D_
max-width: 270px;_x000D_
margin: auto;_x000D_
height: 80px;_x000D_
border: 1px;_x000D_
border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
/* 3 floats x 50px = 150px */_x000D_
width: 50px;_x000D_
/* 6 margins x 10px = 60 */_x000D_
margin: 10px;_x000D_
/* 6 borders x 10px = 60 */_x000D_
border: 10px solid #6B6B6B;_x000D_
float: left;_x000D_
text-align: center;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="myFloat">Float 1</div>_x000D_
<div class="myFloat">Float 2</div>_x000D_
<div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
You can learn some tutorials for JSP page direct access database (mysql) here
Notes:
import sql tag library in jsp page
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
then set datasource on page
<sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
Now query what you want on page
<sql:query dataSource="${ds}" var="result"> //ref defined 'ds'
SELECT * from <your-table>;
</sql:query>
Finally you can populate dropdowns on page using c:forEach
tag to iterate result rows in select
element
<c:forEach var="row" items="${result.rows}"> //ref set var 'result'
<option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option>
</c:forEach>
Best function I have found. Credit to text-ellipsis.
function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
if (str.length > maxLength) {
switch (side) {
case "start":
return ellipsis + str.slice(-(maxLength - ellipsis.length));
case "end":
default:
return str.slice(0, maxLength - ellipsis.length) + ellipsis;
}
}
return str;
}
Examples:
var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."
var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"
var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"
Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named self
:
def updateVelocity(self):
public void invokeShare(Activity activity, String quote, String credit) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject));
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text");
shareIntent.putExtra("com.facebook.platform.extra.APPLICATION_ID", activity.getString(R.string.app_id));
activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title)));
}
Additional to this answer, create a function like
CREATE FUNCTION myrandom(
pmin INTEGER,
pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
RETURN floor(pmin+RAND()*(pmax-pmin));
END;
and call like
SELECT myrandom(100,300);
This gives you random number between 100 and 300
Kotlin version with how much percent do you want to match.
Method call with percent optional argument
isMatchingColor(intColor1, intColor2, 95) // should match color if 95% similar
Method body
private fun isMatchingColor(intColor1: Int, intColor2: Int, percent: Int = 90): Boolean {
val threadSold = 255 - (255 / 100f * percent)
val diffAlpha = abs(Color.alpha(intColor1) - Color.alpha(intColor2))
val diffRed = abs(Color.red(intColor1) - Color.red(intColor2))
val diffGreen = abs(Color.green(intColor1) - Color.green(intColor2))
val diffBlue = abs(Color.blue(intColor1) - Color.blue(intColor2))
if (diffAlpha > threadSold) {
return false
}
if (diffRed > threadSold) {
return false
}
if (diffGreen > threadSold) {
return false
}
if (diffBlue > threadSold) {
return false
}
return true
}
I know this is a repeat of other answers, but it has some emotional support to take the extra step for testing update :D
For testing update, hash # is your friend.
If you have an update statement like:
UPDATE
wp_history
SET history_by="admin"
WHERE
history_ip LIKE '123%'
You hash UPDATE and SET out for testing, then hash them back in:
SELECT * FROM
#UPDATE
wp_history
#SET history_by="admin"
WHERE
history_ip LIKE '123%'
It works for simple statements.
An additional practically mandatory solution is, to get a copy (backup duplicate), whenever using update on a production table. Phpmyadmin > operations > copy: table_yearmonthday. It just takes a few seconds for tables <=100M.
That what manual says about setOnClickListener
method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
Use $wpdb->insert()
.
$wpdb->insert('wp_submitted_form', array(
'name' => 'Kumkum',
'email' => '[email protected]',
'phone' => '3456734567', // ... and so on
));
Addition from @mastrianni:
$wpdb->insert
sanitizes your data for you, unlike $wpdb->query
which requires you to sanitize your query with $wpdb->prepare
. The difference between the two is $wpdb->query
allows you to write your own SQL statement, where $wpdb->insert
accepts an array and takes care of sanitizing/sql for you.
1. Generalized Substring
To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:
${string: -7:4}
Where 4 is the length of course (7-3).
2. Alternative using cut
In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:
echo $string | cut -c $((${#string}-2))-
Here, ${#string}
is the length of the string, and the "-" means cut to the end.
3. Alternative using awk
This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length)
going to the end if the length is omitted. length($string)-2)
thus picks up the last three characters.
echo $string | awk '{print substr($1,length($1)-2) }'
If you're looking to do a simple round in Angular you can easily set the filter inside your expression. For example:
{{ val | number:0 }}
See this CodePen example & for other number filter options.
I just wanted to share my experience
For me,
$('#selectorId').val()
returned null.
I had to use
$('#selectorId option:selected').val()
To remove all the constraints from the DB:
SELECT 'ALTER TABLE ' + Table_Name +' DROP CONSTRAINT ' + Constraint_Name
FROM Information_Schema.CONSTRAINT_TABLE_USAGE
You could definitely append data into an existing table. (But it is actually not an append at the HDFS level). It's just that whenever you do a LOAD or INSERT operation on an existing Hive table without OVERWRITE
clause the new data will be put without replacing the old data. A new file will be created for this newly inserted data inside the directory corresponding to that table. For example :
I have a file named demo.txt which has 2 lines :
ABC
XYZ
Create a table and load this file into it
hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;
Now,if I do a SELECT on this table it'll give me :
hive> select * from demo;
OK
ABC
XYZ
Suppose, I have one more file named demo2.txt which has :
PQR
And I do a LOAD again on this table without using overwrite,
hive> load data inpath '/demo2.txt' into table demo;
Now, if I do a SELECT now, it'll give me,
hive> select * from demo;
OK
ABC
XYZ
PQR
HTH
It's probably a permissions issue but you need to make sure to try these steps to troubleshoot:
sa
and add the net use
and net use /delete
commands before and afterRemember to undo any changes (especially running as sa
). If nothing else works, you can try to change the bulk load into a scheduled task, running on the database server or another server that has bcp installed.
Try This.
$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null
#define NUM_TYPES 4
One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.
Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:
p [tab][enter] Hello world!
When you type p [tab] Emmet expands it to:
<p></p>
Pressing [enter] then further expands it to:
<p>
</p>
With the cursor indented and on the line between the tags. Meaning that typing text results in:
<p>
Hello, world!
</p>
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
split_part()
does what you want in one step:
SELECT split_part(col, ',', 1) AS col1
, split_part(col, ',', 2) AS col2
, split_part(col, ',', 3) AS col3
, split_part(col, ',', 4) AS col4
FROM tbl;
Add as many lines as you have items in col
(the possible maximum). Columns exceeding data items will be empty strings (''
).
Sorry my previous answer was wrong. If you are trying to take total elapsed time between time and timeout in the format Y-m-d H:i:s format, take diff between timeout and time in using DateTime object and format it as '%y-%m-%d %H:%i:%s'.
The other answer is very complete, but here is a rule of thumb:
call
is blocking:
call('notepad.exe')
print('hello') # only executed when notepad is closed
Popen
is non-blocking:
Popen('notepad.exe')
print('hello') # immediately executed
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
Because JavaScript is handling the click event. When you click, the following code is called:
el.addEvent('click', function(e){
if(obj.options.onOpen){
new Event(e).stop();
if(obj.options.open == i){
obj.options.open = null;
obj.options.onClose(this.href, i);
}else{
obj.options.open = i;
obj.options.onOpen(this.href, i);
}
}
})
The onOpen
manually changes the location
.
Edit: Regarding your comment...
If you can modify ImageMenu.js, you could update the script which calls onClose
to pass the a
element object (this
, rather than this.href
)
obj.options.onClose(this, i);
Then update your ImageMenu instance, with the following onOpen
change:
window.addEvent('domready', function(){
var myMenu = new ImageMenu($$('#imageMenu a'), {
openWidth: 310,
border: 2,
onOpen: function(e, i) {
if (e.target === '_blank') {
window.open(e.href);
} else {
location = e.href;
}
}
});
});
This would check for the target property of the element to see if it's _blank
, and then call window.open
, if found.
If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen
handler. Say something like:
<a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a>
Then, update your onOpen
call to:
onOpen: function(e, i) {
if (e.indexOf('_b=1') > -1) {
window.open(e);
} else {
location = e;
}
}
The only downside to this is the user sees the hash on hover.
Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like:
var linksThatOpenInANewWindow = {
'http://www.foracure.org.au': 1
};
onOpen: function(e, i) {
if (linksThatOpenInANewWindow[e] === 1) {
window.open(e);
} else {
location = e
}
}
The only downside is maintenance, depending on the number of links.
Others have suggested modifying the link (using #
or javascript:
) and adding an inline event handler (onclick
) - I don't recommend that at all as it breaks links when JS is disabled/not supported.
It seems like it should be made possible to say:
extra_hosts:
- "loghost:localhost"
So if the part after the colon (normally an IP address) doesn't start with a digit, then name resolution will be performed to look up an IP for localhost, and add something like to the container's /etc/hosts:
127.0.0.1 loghost
...assuming that localhost resolves to 127.0.0.1 on the host system.
It looks like it'd be really easy to add in docker-compose's source code: compose/config/types.py's parse_extra_hosts function would likely do it.
For docker itself, this would probably be addable in opts/hosts.go's ValidateExtraHost function, though then it's not strictly validating anymore, so the function would be a little misnamed.
It might actually be a little better to add this to docker, not docker-compose - docker-compose might just get it automatically if docker gets it.
Sadly, this would probably require a container bounce to change an IP address.
new_hash = old_hash.merge(old_hash) do |_key, value, _value|
value.upcase
end
# old_hash = {"a" => "b", "c" => "d"}
# new_hash = {"a" => "B", "c" => "D"}
<link rel="shortcut icon" type="image/x-icon" href="FolderName/favicon.ico" />
Ctrl + Shift + C . Works great on .java, .xhtml, .properties and maybe on others but I only tested these ones. Can comment single or multiple lines.
If you're going to bet your business or job on a development project, you want to be in control of the foundations - i.e. the build system. With Maven, you are not in control. It is declarative and opaque. The maven-framework developers have no idea how to build a transparent or intuitive system and this is clear from the log output and the documentation.
The dependency management is very tempting since it could same you some time at project inception but be warned, it is fundamentally broken and will eventually cause you a lot of headaches. When two dependencies have incompatible transient dependencies you will be blocked by a rat's nest of complexity that will break the build for your entire team and block development for days. The build process with Maven is also notoriously inconsistent for different developers in your team due to inconsistent states of their local repositories. Depending on when a developer created their environment, or what other projects they're working on, they will have different results. You'll find that you're deleting your entire local repository and having Maven re-download jars far more often than the first time setup for a dev branch. I believe OSGI is an initiative that is attempting to fix this fundamental problem. I would say that perhaps if something needs to be so complex, the fundamental premise is wrong.
I've been a maven user/victim for over 5 years now and I have to say that it will save you far more time to just check your dependencies into your source repository and write nice and simple ant tasks. With ant, you know EXACTLY what your build system is doing.
I've experienced many, many lost man weeks of time at several different companies due to Maven problems.
I've recently tried to bring an old GWT/Maven/Eclipse project back to life and 2 weeks of all my spare time later, I still can't get it to build consistently. It's time to cut my losses and develop using ant / eclipse me thinks...
I also encountered this problem, and I have to change the folder name from Chinese to English. Pity that current gradle build tool does not support Unicode names.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
server.servlet.context-path=/api
would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path
solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.
Cheers
#/bin/bash
# $1 is the file name
# usage: this_script <filename>
IP_address="xx.xxx.xx.xx"
username="username"
domain=my.ftp.domain
password=password
echo "
verbose
open $IP_address
USER $username $password
put $1
bye
" | ftp -n > ftp_$$.log
I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.
[^ ]+
(or \d+
, or whatever you prefer)Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).
Where did you put the code in?
I try your code in my demo, I found out, if you put the code in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
will fail, because key window have been setting yet.
But I put your code in some view controller's
override func viewDidLoad() {
It just works.
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
<div id="scroll">
<p>Try to add more text</p>
</div>
here's the css code
#scroll {
overflow-y:auto;
height:auto;
max-height:200px;
border:1px solid black;
width:300px;
}
here's the demo JSFIDDLE
Use nohup
if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.
Redirect the stdout and stderr to /dev/null
to ignore the output.
nohup /path/to/your/script.sh > /dev/null 2>&1 &
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />
<script>
var card = document.getElementById("cardtype");
if (card.options[card.selectedIndex].value == 'selectcard') {
alert("Please select a card type");
return false;
}
</script>
If you need exact your example, you should add format to ToString()
string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But it's better to use straight formatting:
string test = DateTime.Now.ToString("yyyy-MM-dd")