I have to answer, too. The JIT generates tables together with the code from it's static analysis of variable usage. Those table entries are the "GC-Roots" in the current stack frame. As the instruction pointer advances, those table entries become invalid and so ready for garbage collection. Therefore: If it is a scoped variable, you don't need to set it to null - the GC will collect the object. If it is a member or a static variable, you have to set it to null
Here is a data.table
example. I used grep
in this example because that's how I often select many columns by using partial matches to their names.
library(data.table)
data <- data.table(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
factorCols <- grep(pattern = "A|C|D|H", x = names(data), value = TRUE)
data[, (factorCols) := lapply(.SD, as.factor), .SDcols = factorCols]
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
Note that time.gmtime
maps timestamp 0
to 1970-1-1 00:00:00
.
In [61]: import time
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
time.mktime(time.gmtime(0))
gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.
In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0
The inverse of time.gmtime
is calendar.timegm
:
In [62]: import calendar
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0
When the post-link
function is called, all previous steps have taken place - binding, transclusion, etc.
This is typically a place to further manipulate the rendered DOM.
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
Try this code
select (DATEDIFF(DD,'2014-08-01','2014-08-14')+1)- (DATEDIFF(WK,'2014-08-01','2014-08-14')* 2)
Below is the code which can be use to find the mode of a vector variable in R.
a <- table([vector])
names(a[a==max(a)])
You should use <h:panelGroup ...>
tag with attribute rendered
. If you set true
to rendered, the content of <h:panelGroup ...>
won't be shown. Your XHTML file should have something like this:
<h:panelGroup rendered="#{userBean.showPassword}">
<h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
private boolean showPassword = false;
private String password = "";
public boolean isShowPassword(){
return showPassword;
}
public void setPassword(password){
this.password = password;
}
public String getPassword(){
return this.password;
}
}
<span>
elements are inline elements, as such layout properties such as width
or margin
don't work. You can fix that by either changing the <span>
to a block element (such as <div>
), or by using padding instead.
Note that making a span
element a block element by adding display: block;
is redundant, as a span
is by definition a otherwise style-less inline element whereas div
is an otherwise style-less block element. So the correct solution is to use a div
instead of a block-span
.
Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.
For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
double d = 2.22977777;
d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;
Of course, this won't work if you're trying to truncate rounding error, but it should work fine with the values you give in your examples. See the first two answers to this question for details on why it won't work sometimes.
Frameworks usually use bracket names in forms, like:
<input name=user[first_name] />
They can be accessed by:
// in JS:
this.querySelectorAll('[name="user[first_name]"]')
// in jQuery:
$('[name="user[first_name]"]')
// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")
The install:install
goal is provided by «Apache Maven Install Plugin»:
Apache Maven Install Plugin
The Install Plugin is used during the install phase to add artifact(s) to the local repository. The Install Plugin uses the information in the POM (
groupId
,artifactId
,version
) to determine the proper location for the artifact within the local repository.The local repository is the local cache where all artifacts needed for the build are stored. By default, it is located within the user's home directory (
~/.m2/repository
) but the location can be configured in~/.m2/settings.xml
using the<localRepository>
element.
Having said that, the exact goal purpose:
install:install
is used to automatically install the project's main artifact (the JAR, WAR or EAR), its POM and any attached artifacts (sources, javadoc, etc) produced by a particular project.
For additional details on the goal, please refer to the Apache Maven Install Plugin - install:install page.
For additional details on the build lifecycle in general and on which place the goal has in the build lifecycle, please refer to the Maven – Introduction to the Build Lifecycle page.
Get the data you need and combine it in the String;
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();
Check out : Working With Dates
insertRow2 <- function(existingDF, newrow, r) {
existingDF <- rbind(existingDF,newrow)
existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
row.names(existingDF) <- 1:nrow(existingDF)
return(existingDF)
}
insertRow2(existingDF,newrow,r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
microbenchmark(
+ rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+ insertRow(existingDF,newrow,r),
+ insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2 insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415 499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216
yaml.load
Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.
The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: [email protected]
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.
The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.
The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format
).
A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).
YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.
YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.
There are YAML extension libraries, but these are not part of the native YAML spec.
sprintf
or str.format
style functionality from the hosting languageAssuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned BigInteger and similar immutable BigDecimal, I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.
Isn't :
Complex a, b, c; a = b + c;
much simpler than:
Complex a, b, c; a = b.add(c);
A simple way to do so is to add the below code (for Seaborn):
for p in splot.patches:
splot.annotate(format(p.get_height(), '.1f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 9),
textcoords = 'offset points')
Example :
splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
splot.annotate(format(p.get_height(), '.1f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 9),
textcoords = 'offset points')
plt.show()
With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).
Try this if you want exact height of top bar (both navigation bar + status bar):
UPDATE
iOS 13
As the statusBarFrame
was deprecated in iOS13
you can use this:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Objective-C
CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
(self.navigationController.navigationBar.frame.size.height ?: 0.0));
Swift 4
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
For ease, try this UIViewController extension
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Swift 3
let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
add the following to the end of the first function
return $.Deferred().resolve();
call both functions like so
functionOne().done(functionTwo);
You can check an example in Plunker over here plunker example filters
filter() {
let storeId = 1;
this.bookFilteredList = this.bookList
.filter((book: Book) => book.storeId === storeId);
this.bookList = this.bookFilteredList;
}
You can set the calendar to use only AM or PM using
calendar.set(Calendar.AM_PM, int);
0 = AM
1 = PM
Hope this helps
It's basically jQuery for C#. It depends on HTML Agility Pack for parsing the HTML.
The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:
int x = 0; //x is 0
int y = ++x; //x is 1 and y is 1
If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:
int x = 0; //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:
while (x < 5) //evaluates conditional statement
{
//some code
++x; //increments x
}
or
while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
//some code
}
You can also do this while indexing arrays and such:
int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
Etc, etc...
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
Try to use appendChild method:
select.appendChild(option);
Check out Abraxas Code Check http://www.abxsoft.com/codchk_user.html
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
and now you can compile & run your application successfully.
I want to know how can I update some field(not all) like method 1 where id = 1
Use @Query
, as you did in Method 2.
is too long query in my case because I have many field in my entity
Then have smaller entities. Or, do not update fields individually, but instead have more coarse-grained interactions with the database.
IOW, there is nothing in Room itself that will do what you seek.
UPDATE 2020-09-15: Room now has partial entity support, which can help with this scenario. See this answer for more.
You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus
See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.
The following snippet will iterate over nested objects. Objects within the objects. Feel free to change it to meet your requirements. Like if you want to add array support make if-else and make a function that loop through arrays ...
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3",_x000D_
"p4": {_x000D_
"p4": 'value 4'_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
/**_x000D_
* Printing a nested javascript object_x000D_
*/_x000D_
function jsonPrinter(obj) {_x000D_
_x000D_
for (let key in obj) {_x000D_
// checking if it's nested_x000D_
if (obj.hasOwnProperty(key) && (typeof obj[key] === "object")) {_x000D_
jsonPrinter(obj[key])_x000D_
} else {_x000D_
// printing the flat attributes_x000D_
console.log(key + " -> " + obj[key]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
jsonPrinter(p);
_x000D_
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
git reset --hard
This is to revert all your local changes to the origin head
JPA is the interface, Hibernate is one implementation of that interface.
For ENOENT on Windows, https://github.com/nodejs/node-v0.x-archive/issues/2318#issuecomment-249355505 fix it.
e.g. replace spawn('npm', ['-v'], {stdio: 'inherit'}) with:
for all node.js version:
spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['-v'], {stdio: 'inherit'})
for node.js 5.x and later:
spawn('npm', ['-v'], {stdio: 'inherit', shell: true})
In the second you can access the attributes of the exception object:
>>> def catch():
... try:
... asd()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)
But it doesn't catch BaseException
or the system-exiting exceptions SystemExit
, KeyboardInterrupt
and GeneratorExit
:
>>> def catch():
... try:
... raise BaseException()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch
BaseException
Which a bare except does:
>>> def catch():
... try:
... raise BaseException()
... except:
... pass
...
>>> catch()
>>>
See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.
You can snoop around in your memory using RTLMoveMemory and retrieve the desired information directly from there:
32-Bit:
Option Explicit
'Provide direct memory access:
Public Declare Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As Long, _
ByVal Source As Long, _
ByVal Length As Long)
Function CollectionKeys(oColl As Collection) As String()
'Declare Pointer- / Memory-Address-Variables
Dim CollPtr As Long
Dim KeyPtr As Long
Dim ItemPtr As Long
'Get MemoryAddress of Collection Object
CollPtr = VBA.ObjPtr(oColl)
'Peek ElementCount
Dim ElementCount As Long
ElementCount = PeekLong(CollPtr + 16)
'Verify ElementCount
If ElementCount <> oColl.Count Then
'Something's wrong!
Stop
End If
'Declare Simple Counter
Dim index As Long
'Declare Temporary Array to hold our keys
Dim Temp() As String
ReDim Temp(ElementCount)
'Get MemoryAddress of first CollectionItem
ItemPtr = PeekLong(CollPtr + 24)
'Loop through all CollectionItems in Chain
While Not ItemPtr = 0 And index < ElementCount
'increment Index
index = index + 1
'Get MemoryAddress of Element-Key
KeyPtr = PeekLong(ItemPtr + 16)
'Peek Key and add to temporary array (if present)
If KeyPtr <> 0 Then
Temp(index) = PeekBSTR(KeyPtr)
End If
'Get MemoryAddress of next Element in Chain
ItemPtr = PeekLong(ItemPtr + 24)
Wend
'Assign temporary array as Return-Value
CollectionKeys = Temp
End Function
'Peek Long from given MemoryAddress
Public Function PeekLong(Address As Long) As Long
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLong), Address, 4&)
End Function
'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As Long) As String
Dim Length As Long
If Address = 0 Then Stop
Length = PeekLong(Address - 4)
PeekBSTR = Space(Length \ 2)
Call MemCopy(VBA.StrPtr(PeekBSTR), Address, Length)
End Function
64-Bit:
Option Explicit
'Provide direct memory access:
Public Declare PtrSafe Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As LongPtr, _
ByVal Source As LongPtr, _
ByVal Length As LongPtr)
Function CollectionKeys(oColl As Collection) As String()
'Declare Pointer- / Memory-Address-Variables
Dim CollPtr As LongPtr
Dim KeyPtr As LongPtr
Dim ItemPtr As LongPtr
'Get MemoryAddress of Collection Object
CollPtr = VBA.ObjPtr(oColl)
'Peek ElementCount
Dim ElementCount As Long
ElementCount = PeekLong(CollPtr + 28)
'Verify ElementCount
If ElementCount <> oColl.Count Then
'Something's wrong!
Stop
End If
'Declare Simple Counter
Dim index As Long
'Declare Temporary Array to hold our keys
Dim Temp() As String
ReDim Temp(ElementCount)
'Get MemoryAddress of first CollectionItem
ItemPtr = PeekLongLong(CollPtr + 40)
'Loop through all CollectionItems in Chain
While Not ItemPtr = 0 And index < ElementCount
'increment Index
index = index + 1
'Get MemoryAddress of Element-Key
KeyPtr = PeekLongLong(ItemPtr + 24)
'Peek Key and add to temporary array (if present)
If KeyPtr <> 0 Then
Temp(index) = PeekBSTR(KeyPtr)
End If
'Get MemoryAddress of next Element in Chain
ItemPtr = PeekLongLong(ItemPtr + 40)
Wend
'Assign temporary array as Return-Value
CollectionKeys = Temp
End Function
'Peek Long from given Memory-Address
Public Function PeekLong(Address As LongPtr) As Long
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLong), Address, 4^)
End Function
'Peek LongLong from given Memory Address
Public Function PeekLongLong(Address As LongPtr) As LongLong
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLongLong), Address, 8^)
End Function
'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As LongPtr) As String
Dim Length As Long
If Address = 0 Then Stop
Length = PeekLong(Address - 4)
PeekBSTR = Space(Length \ 2)
Call MemCopy(VBA.StrPtr(PeekBSTR), Address, CLngLng(Length))
End Function
Although ididak's response is pretty cool, and Handyman5 provides a script to use it, I found it a little restricted to use that approach.
Sometimes you need to search for something that can appear/disappear over time, so why not search against all commits? Besides that, sometimes you need a verbose response, and other times only commit matches. Here are two versions of those options. Put these scripts on your path:
git-find-file
for branch in $(git rev-list --all)
do
if (git ls-tree -r --name-only $branch | grep --quiet "$1")
then
echo $branch
fi
done
git-find-file-verbose
for branch in $(git rev-list --all)
do
git ls-tree -r --name-only $branch | grep "$1" | sed 's/^/'$branch': /'
done
Now you can do
$ git find-file <regex>
sha1
sha2
$ git find-file-verbose <regex>
sha1: path/to/<regex>/searched
sha1: path/to/another/<regex>/in/same/sha
sha2: path/to/other/<regex>/in/other/sha
See that using getopt you can modify that script to alternate searching all commits, refs, refs/heads, been verbose, etc.
$ git find-file <regex>
$ git find-file --verbose <regex>
$ git find-file --verbose --decorated --color <regex>
Checkout https://github.com/albfan/git-find-file for a possible implementation.
This happens when you are trying to run application on emulator. Emulator does not have shared google maps library.
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
you are looking for the modulo operator:
a % b
for example:
26 % 7
Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.
This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d
.
I had to delete all target folders showing in the message and then executing git submodule update --remote
In case you are using quite popular in Spring Boot environment Kubernetes (K8S) or OpenShift, there's a possibility to store and retrieve application properties on runtime. This technique called secrets. In your configuration yaml file for Kubernetes or OpenShift you declare variable and placeholder for it, and on K8S\OpenShift side declare actual value which corresponds to this placeholder. For implementation details, see: K8S: https://kubernetes.io/docs/concepts/configuration/secret/ OpenShift: https://docs.openshift.com/container-platform/3.11/dev_guide/secrets.html
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
For simple things, the following tzinfo
implementation can be used, which queries the OS for time zone offsets:
import datetime
import time
class LocalTZ(datetime.tzinfo):
_unixEpochOrdinal = datetime.datetime.utcfromtimestamp(0).toordinal()
def dst(self, dt):
return datetime.timedelta(0)
def utcoffset(self, dt):
t = (dt.toordinal() - self._unixEpochOrdinal)*86400 + dt.hour*3600 + dt.minute*60 + dt.second + time.timezone
utc = datetime.datetime(*time.gmtime(t)[:6])
local = datetime.datetime(*time.localtime(t)[:6])
return local - utc
print datetime.datetime.now(LocalTZ())
print datetime.datetime(2010, 4, 27, 12, 0, 0, tzinfo=LocalTZ())
# If you're in the EU, the following datetimes are right on the DST change.
print datetime.datetime(2013, 3, 31, 0, 59, 59, tzinfo=LocalTZ())
print datetime.datetime(2013, 3, 31, 1, 0, 0, tzinfo=LocalTZ())
print datetime.datetime(2013, 3, 31, 1, 59, 59, tzinfo=LocalTZ())
# The following datetime is invalid, as the clock moves directly from
# 01:59:59 standard time to 03:00:00 daylight savings time.
print datetime.datetime(2013, 3, 31, 2, 0, 0, tzinfo=LocalTZ())
print datetime.datetime(2013, 10, 27, 0, 59, 59, tzinfo=LocalTZ())
print datetime.datetime(2013, 10, 27, 1, 0, 0, tzinfo=LocalTZ())
print datetime.datetime(2013, 10, 27, 1, 59, 59, tzinfo=LocalTZ())
# The following datetime is ambigous, as 02:00 can be either DST or standard
# time. (It is interpreted as standard time.)
print datetime.datetime(2013, 10, 27, 2, 0, 0, tzinfo=LocalTZ())
Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.
The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason.
So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &vector[0] for instance, and use the std::vector to manage the array internally.
Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).
For 64 bit OS, its here (If .Net 4.5) : C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE
Not a direct response to your question, but wouldn't it be better for your RPC to return some structure (be it XML or JSON or whatever) with those image data (urls in your example) inside that structure?
Then you could just parse it in your javascript and build the <img>
using javascript itself.
The structure you recieve from RPC could look like:
{"img" : ["myimage.jpg", "myimage2.jpg"]}
I think it's better this way, as injecting a code that comes from external source into your page doesn't look very secure. Imaging someone hijacking your XML-RPC script and putting something you wouldn't want in there (even some javascript...)
On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.
https://webpack.js.org/configuration/devtool
devtool best dev options
build rebuild quality look
eval-source-map slow pretty fast original source worst
inline-source-map slow slow original source medium
cheap-module-eval-source-map medium fast original source (lines only) worst
inline-cheap-module-source-map medium pretty slow original source (lines only) best
lines only
Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.
REVISITING THIS
On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s
>>> a=12345
>>> a.__str__().__len__()
5
Unit Test - testing an individual unit, such as a method (function) in a class, with all dependencies mocked up.
Functional Test - AKA Integration Test, testing a slice of functionality in a system. This will test many methods and may interact with dependencies like Databases or Web Services.
There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.
By default, Web API uses the following rules to bind parameters:
If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
For complex types, Web API tries to read the value from the message body, using a media-type formatter.
So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri]
attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody]
attribute to the parameter.
So, to answer your question, the need of the [FromBody]
and [FromUri]
attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.
There is a lot more information on the web if you google "web api parameter binding".
An example of how you could do this:
Some notes:
LoggingHandler
intercepts the request before it handles it to HttpClientHandler
which finally writes to the wire.
PostAsJsonAsync
extension internally creates an ObjectContent
and when ReadAsStringAsync()
is called in the LoggingHandler
, it causes the formatter
inside ObjectContent
to serialize the object and that's the reason you are seeing the content in json.
Logging handler:
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
Console.WriteLine();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine("Response:");
Console.WriteLine(response.ToString());
if (response.Content != null)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
Console.WriteLine();
return response;
}
}
Chain the above LoggingHandler with HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
Output:
Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Fri, 20 Sep 2013 20:21:26 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 15
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
While sort
takes O(n log(n)) time, I prefer using
awk '!seen[$0]++'
awk '!seen[$0]++'
is an abbreviation for awk '!seen[$0]++ {print}'
, print line(=$0) if seen[$0]
is not zero.
It take more space but only O(n) time.
int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageResource(id);
someLinearLayout.addView(imageView);
This piece of configuration in web.config file can help as helped to me: in the system.webServer section:
<security>
<requestFiltering>
<verbs applyToWebDAV="true">
<remove verb="PUT" />
<add verb="PUT" allowed="true" />
<remove verb="DELETE" />
<add verb="DELETE" allowed="true" />
<remove verb="PATCH" />
<add verb="PATCH" allowed="true" />
</verbs>
</requestFiltering>
</security>
Escape your HTML tags ...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
There is an option in WinSCP that does exactly what you are looking for:
Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:
public class BankAccount {
/**
* @param args
*/
int accountNumber;
double accountBalance;
public synchronized boolean Deposit(double amount){
double newAccountBalance=0;
if(amount<=0){
return false;
}
else {
newAccountBalance = accountBalance+amount;
accountBalance=newAccountBalance;
return true;
}
}
public synchronized boolean Withdraw(double amount){
double newAccountBalance=0;
if(amount>accountBalance){
return false;
}
else{
newAccountBalance = accountBalance-amount;
accountBalance=newAccountBalance;
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BankAccount b = new BankAccount();
b.accountBalance=2000;
System.out.println(b.Withdraw(3000));
}
I have done experimentation on this.
It's true that System.gc();
only suggests to run the Garbage Collector.
But calling System.gc();
after setting all references to null
, will improve performance and memory occupation.
For me (being on Windows 10) the npmrc file was located in:
%USERPROFILE%\.npmrc
Tested with:
Your should also separate the javascript from the HTML.
HTML:
<a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>
javascript:
myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);
Just make sure the last line in the ShowOld function is:
return false;
as this will stop the link from opening in the browser.
See Converting unix timestamp to excel date-time forum thread.
CREATE GLOBAL TEMPORARY TABLE Table_name
(startdate DATE,
enddate DATE,
class CHAR(20))
ON COMMIT DELETE ROWS;
On python 3.6 with django 2.0, decode on a byte literal does not works as expected. Yeah i get the right result when i print it, but the b'value' is still there even if you print it right.
This is what im encoding
uid': urlsafe_base64_encode(force_bytes(user.pk)),
This is what im decoding:
uid = force_text(urlsafe_base64_decode(uidb64))
This is what django 2.0 says :
urlsafe_base64_encode(s)[source]
Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.
urlsafe_base64_decode(s)[source]
Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
This is my account_activation_email_test.html file
{% autoescape off %}
Hi {{ user.username }},
Please click on the link below to confirm your registration:
http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}
This is my console response:
Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Activate Your MySite Account From: webmaster@localhost To: [email protected] Date: Fri, 20 Apr 2018 06:26:46 -0000 Message-ID: <152420560682.16725.4597194169307598579@Dash-U>
Hi testuser,
Please click on the link below to confirm your registration:
http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/
as you can see uid = b'MjU'
expected uid = MjU
test in console:
$ python
Python 3.6.4 (default, Apr 7 2018, 00:45:33)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>>
After investigating it seems like its related to python 3. My workaround was quite simple:
'uid': user.pk,
i receive it as uidb64 on my activate function:
user = User.objects.get(pk=uidb64)
and voila:
Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: [email protected]
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>
Hi testuser,
Please click on the link below to confirm your registration:
http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/
now it works fine. :)
You need something like this :
UPDATE P
SET ExtrasPrice = E.TotalPrice
FROM dbo.BookingPitches AS P
INNER JOIN (SELECT BPE.PitchID, Sum(BPE.Price) AS TotalPrice
FROM BookingPitchExtras AS BPE
WHERE BPE.[Required] = 1
GROUP BY BPE.PitchID) AS E ON P.ID = E.PitchID
WHERE P.BookingID = 1
Actually it is much more useful use the method that came with the library like this $(".datepicker").datepicker("clearDates");
I recommend you to always take a look at the documentation of the library, here is the one I used for this.
Go to the Sql tab run one of the below query:
delete from tableName;
Delete: will delete all rows from your table. Next insert will take next auto increment id.
or
truncate tableName;
Truncate: will also delete the rows from your table but it will start from new row with 1.
A detailed blog with example: http://sforsuresh.in/phpmyadmin-deleting-rows-mysql-table/
The following function will take in a list and return a string of the lists' items. This can then be used for logging or printing purposes.
def listToString(inList):
outString = ''
if len(inList)==1:
outString = outString+str(inList[0])
if len(inList)>1:
outString = outString+str(inList[0])
for items in inList[1:]:
outString = outString+', '+str(items)
return outString
When all the stuff above didn't work, try giving Excel some time to close its sheets:
app.workbooks.Close();
Thread.Sleep(500); // adjust, for me it works at around 300+
app.Quit();
...
FinalReleaseComObject(app);
Why not use 410? It suggests the requested resource no longer exists and the client is expected to never make a request for that resource, in your case users/9
.
You can find more details about 410 here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
I know its an old post, but just in case anyone is looking here. I added this to my style.xml and it worked for me.
<!-- This is the main theme parent -->
<style name="MyTabStyle">
<item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
</style>
<style name="MyTabTextStyle" parent="@android:style/Widget.ActionBar.TabText">
<item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
<item name="android:textSize">14sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/pressed_skylogtheme</item>
</style>
Something like this:
import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()
Note that this will also work if you are using the seaborn
package for plotting:
import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
Our global AsyncTask class variable
LongOperation LongOperationOdeme = new LongOperation();
And KEYCODE_BACK action which interrupt AsyncTask
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LongOperationOdeme.cancel(true);
}
return super.onKeyDown(keyCode, event);
}
It works for me.
If you want to overwrite the element with key 0
function[0] = 42;
Otherwise:
function.insert(std::make_pair(0, 42));
I met the issue before when using a fullscreen dialogFragment: there is always a padding while having set fullscreen. try this code in dialogFragment's onActivityCreated() method:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
Window window = getDialog().getWindow();
LayoutParams attributes = window.getAttributes();
//must setBackgroundDrawable(TRANSPARENT) in onActivityCreated()
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (needFullScreen)
{
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
}
Accepted answer is correct, but I like to define this little utility in most projects I build.
var types = {
'get': function(prop) {
return Object.prototype.toString.call(prop);
},
'null': '[object Null]',
'object': '[object Object]',
'array': '[object Array]',
'string': '[object String]',
'boolean': '[object Boolean]',
'number': '[object Number]',
'date': '[object Date]',
}
Used like this:
if(types.get(prop) == types.number) {
}
If you're using angular you can even have it cleanly injected:
angular.constant('types', types);
Use +
plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.
java.util.TimeZone represents a time zone offset, and also figures out daylight savings.
sample code:
TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);
Dependencies vs dev dependencies
Dev dependencies are modules which are only required during development whereas dependencies are required at runtime. If you are deploying your application, dependencies has to be installed, or else your app simply will not work. Libraries that you call from your code that enables the program to run can be considered as dependencies.
Eg- React , React - dom
Dev dependency modules need not be installed in the production server since you are not gonna develop in that machine .compilers that covert your code to javascript , test frameworks and document generators can be considered as dev-dependencies since they are only required during development .
Eg- ESLint , Babel , webpack
@FYI,
mod-a
dev-dependents:
- mod-b
dependents:
- mod-c
mod-d
? dev-dependents:
- mod-e
dependents:
- mod-a
----
npm install mod-d
installed modules:
- mod-d
- mod-a
- mod-c
----
checkout the mod-d code repository
npm install
installed modules:
- mod-a
- mod-c
- mod-e
If you are publishing to npm, then it is important that you use the correct flag for the correct modules. If it is something that your npm module needs to function, then use the "--save" flag to save the module as a dependency. If it is something that your module doesn't need to function but it is needed for testing, then use the "--save-dev" flag.
# For dependent modules
?npm install dependent-module --save
?# For dev-dependent modules
np?m install development-module --save-dev
Mr.Iam4fun your code answer here..You will use thread...
findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
DownloadFiles();
}
}).start();
And,then..
public void DownloadFiles(){
try {
URL u = new URL("http://www.qwikisoft.com/demo/ashade/20001.kml");
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "data/test.kml"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
}
}
Sure, it will be working..
Include <ctime>
and use the time
function.
because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.
I also faced this problem because I just only installed JRE not with JDK. So , adding dependency for jdk.tools can't fix for me because tools.jar was not exist at my ${JAVA_HOME}/lib/ directory.
Now I downloaded and installed JDK to fix it.
select distinct owner
from dba_segments
where owner in (select username from dba_users where default_tablespace not in ('SYSTEM','SYSAUX'));
First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:
function Field() {
return (
<View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>
);
}
Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:
renderFields() {
const noGuest = this.state.guest;
const fields = [];
for (let i=0; i < noGuest; i++) {
// Try avoiding the use of index as a key, it has to be unique!
fields.push(
<Field key={"guest_"+i} />
);
}
return fields;
}
render () {
return (
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>
{this.renderFields()}
</View>;
)
}
However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!
You need to download the Native Development Kit.
You can use this.props.children
to render whatever children the component contains:
const Wrap = ({ children }) => <div>{children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
You can see the information regarding the transfer by doing:
curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);
before the request, and
$information = curl_getinfo($curl_exect);
after the request
View: http://www.php.net/manual/en/function.curl-getinfo.php
You can also use the CURLOPT_HEADER
in your curl_setopt
curl_setopt($curl_exect, CURLOPT_HEADER, true);
$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
return $httpcode == 200;
These are just some methods of using the headers.
Try with the following code:
$("textarea[id^='options_'],input[id^='options_']").on('keyup onmouseout keydown keypress blur change',
function() {
}
);
This is a good overview:
http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html
or run this code:
32 bit process:
NSLog(@"Primitive sizes:");
NSLog(@"The size of a char is: %d.", sizeof(char));
NSLog(@"The size of short is: %d.", sizeof(short));
NSLog(@"The size of int is: %d.", sizeof(int));
NSLog(@"The size of long is: %d.", sizeof(long));
NSLog(@"The size of long long is: %d.", sizeof(long long));
NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
NSLog(@"The size of a float is: %d.", sizeof(float));
NSLog(@"The size of a double is %d.", sizeof(double));
NSLog(@"Ranges:");
NSLog(@"CHAR_MIN: %c", CHAR_MIN);
NSLog(@"CHAR_MAX: %c", CHAR_MAX);
NSLog(@"SHRT_MIN: %hi", SHRT_MIN); // signed short int
NSLog(@"SHRT_MAX: %hi", SHRT_MAX);
NSLog(@"INT_MIN: %i", INT_MIN);
NSLog(@"INT_MAX: %i", INT_MAX);
NSLog(@"LONG_MIN: %li", LONG_MIN); // signed long int
NSLog(@"LONG_MAX: %li", LONG_MAX);
NSLog(@"ULONG_MAX: %lu", ULONG_MAX); // unsigned long int
NSLog(@"LLONG_MIN: %lli", LLONG_MIN); // signed long long int
NSLog(@"LLONG_MAX: %lli", LLONG_MAX);
NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX); // unsigned long long int
When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:
Primitive sizes:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 4.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 4.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -2147483648
LONG_MAX: 2147483647
ULONG_MAX: 4294967295
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
64 bit process:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
I wrote this script some time ago:
Usage:
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
Just had a similar problem when exporting from dataframe to arcgis table and stumbled on a solution from usgs (https://my.usgs.gov/confluence/display/cdi/pandas.DataFrame+to+ArcGIS+Table). In short your problem has a similar solution:
df
A B C
ID
1 NaN 0.2 NaN
2 NaN NaN 0.5
3 NaN 0.2 0.5
4 0.1 0.2 NaN
5 0.1 0.2 0.5
6 0.1 NaN 0.5
7 0.1 NaN NaN
np_data = np.array(np.rec.fromrecords(df.values))
np_names = df.dtypes.index.tolist()
np_data.dtype.names = tuple([name.encode('UTF8') for name in np_names])
np_data
array([( nan, 0.2, nan), ( nan, nan, 0.5), ( nan, 0.2, 0.5),
( 0.1, 0.2, nan), ( 0.1, 0.2, 0.5), ( 0.1, nan, 0.5),
( 0.1, nan, nan)],
dtype=(numpy.record, [('A', '<f8'), ('B', '<f8'), ('C', '<f8')]))
By removing the parameter from the anonymous function will be available in the body.
myButton.onclick = function() { alert(myMessage); };
For more info search for 'javascript closures'
Another way of changing the size of the bullets would be:
::before
pseudo-element.Example:
ul {_x000D_
list-style-type: none;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
width: 5px;_x000D_
height: 5px;_x000D_
background-color: #000000;_x000D_
margin-right: 8px;_x000D_
content: ' '_x000D_
}
_x000D_
<ul>_x000D_
<li>first element</li>_x000D_
<li>second element</li>_x000D_
</ul>
_x000D_
No markup changes needed
And here is the one liner:
$("<li><div class='bar'>bla</div></li>").find("li").attr("id","1234").end().appendTo("body")
But I'm wondering why you would like to add the "id" attribute at a later stage rather than injecting it directly in the template.
This is from PasswordEncoder interface documentation from Spring Security,
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from
* storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);
Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.
I do not believe this is possible. You could add class1
to all elements which also have class2
. If this is not practical to do manually, you could do it automatically with JavaScript (fairly easy to do with jQuery).
Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:
Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)
Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.
Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.
Mash the build button.
In your Manifest
define windowSoftInputMode
property:
<activity android:name=".MyActivity"
android:windowSoftInputMode="adjustNothing">
You can use in()
:
select *
from table
where id in (multiple row query)
or use a join:
select distinct t.*
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>
The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
For more insight into this issue, also see: An existing connection was forcibly closed by the remote host - WCF
My problem ended up being that my data transfer objects were too complex. Start withsimple properties like public long Id { get; set; }
and once you get that working than start adding additional stuff as needed.
You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.
Here is the command:
version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus
curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz
If you were asking how to get the PID of a known command it would resemble something like this:
If you had issued the command below #The command issued was ***
dd if=/dev/diskx of=/dev/disky
Then you would use:
PIDs=$(ps | grep dd | grep if | cut -b 1-5)
What happens here is it pipes all needed unique characters to a field and that field can be echoed using
echo $PIDs
Perhaps you'll have to check the nodetype too:
if(element.nodeType == 1){//element of type html-object/tag
if(element.tagName=="a"){
//this is an a-element
}
if(element.tagName=="div"){
//this is a div-element
}
}
Edit: Corrected the nodeType-value
You can compile individual files(s) from the command line with:
python -m compileall <file_1>.py <file_n>.py
Using management studio the procedure can be done as follows
You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.
Click option menu and tick Overwrite the existing database(With replace)
you need to prevent the default behavior of your form when submitting
by adding this:
$("#postcontent").on('submit' , function(e) {
e.preventDefault();
//then the rest of your code
}
X <- c(1:3)*0
Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c()
function, which is very frequently cited in tutorials as a usual way to declare a vector.
As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.
Specify maven.compiler.source and target versions.
1) Maven version which supports jdk you use. In my case JDK 11 and maven 3.6.0.
2) pom.xml
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
As an alternative, you can fully specify maven compiler plugin. See previous answers. It is shorter in my example :)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
3) rebuild the project to avoid compile errors in your IDE.
4) If it still does not work. In Intellij Idea I prefer using terminal instead of using terminal from OS. Then in Idea go to file -> settings -> build tools -> maven. I work with maven I downloaded from apache (by default Idea uses bundled maven). Restart Idea then and run mvn clean install
again. Also make sure you have correct Path, MAVEN_HOME, JAVA_HOME environment variables.
I also saw this one-liner, but it does not work.
<maven.compiler.release>11</maven.compiler.release>
I made some quick starter projects, which I re-use in other my projects, feel free to check:
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
I stumbled upon this thread because I wanted to always reference the "cell to the left" but CRUCIALLY in a non-volatile way (no OFFSET, INDIRECT and similar disasters). Looking the web up and down, no answers. (This thread does not actually provide an answer either.) After some tinkering about I stumbled upon the most astonishing method, which I like to share with this community:
Suppose a starting value of 100 in E6. Suppose I enter a delta to this value in F5, say 5. We would then calculate the continuation value (105) in F6 = E6+F5. If you want to add another step, easy: just copy column F to column G and enter a new delta in G5.
This is what we do, periodically. Each column has a date and these dates MUST BE in chronological order (to help with MATCH etc). Every so often it happens that we forget to enter a step. Now suppose you want to insert a column between F and G (to catch up with your omission) and copy F into the new G (to repopulate the continuation formula). This is NOTHING SHORT of a total disaster. Try it - H6 will now say =F6+H5 and NOT (as we absolutely need it to) =G6+H5. (The new G6 will be correct.)
To make this work, we can obfuscate this banal calculation in the most astonishing manner F6=index($E6:F6;1;columns($E1:F1)-1)+F5. Copy right and you get G6=index($E6:G6;1;columns($E1:G1)-1)+G5.
This should never work, right? Circular reference, clearly! Try it out and be amazed. Excel seems to realize that although the INDEX range spans the cell we are recalculating, that cell itself is not addressed by the INDEX and thus DOES NOT create a circular reference.
So now I am home and dry. Insert a column between F and G and we get exactly what we need: The continuation value in the old H will refer back to the continuation value we inserted in the new G.
OAuth 2.0 promises to simplify things in following ways:
If you have hashes '#' in your URL, all the solutions here do not work. This is the only solution that worked for me.
var hrefa = window.location.href.split("#")[1];
var hrefb = window.location.href.split("#")[2];
window.location.href = window.location.pathname + window.location.search + '&x=x#' + hrefa + '#' + hrefb;
The URL has to be different for it to reload if you have a hash. The &x=x does that here. Just substitute this for something you can ignore. THis is abit of a hack, unable to find a better solution..
Tested in Firefox.
First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.
Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt
option of its pkcs8 utility):
KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (!keys.isKeyEntry(alias))
continue;
Key key = keys.getKey(alias, password);
if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
/* Most PrivateKeys use this format, but check for safety. */
try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
os.write(key.getEncoded());
os.flush();
}
}
}
If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.
For OSX (and Linux), a simple solution is to use either os.popen or os.system and run the arp -a
command.
For example:
devices = []
for device in os.popen('arp -a'): devices.append(device)
This will give you a list of the devices on your local network.
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
This is a simple way of doing something.
@Override
public void onBackPressed() {
// do what you want to do when the "back" button is pressed.
startActivity(new Intent(Activity.this, MainActivity.class));
finish();
}
I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.
Object.keys(top_brands).forEach(function(key) {
var value = top_brands[key];
// use "key" and "value" here...
});
Btw, note that Object.keys
and forEach
are not available in ancient browsers, but you should use some polyfill anyway.
You have to add
<script>jQuery.noConflict();</script>
after
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
I use Mac and Idea 14.1.7. Found idea.vmoptions file here: /Applications/IntelliJ IDEA 14.app/Contents/bin
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
Based on a feature mentioned in this answer to another question I have found a very generally applicable solution for placing labels on a bar chart.
Other solutions unfortunately do not work in many cases, because the spacing between label and bar is either given in absolute units of the bars or is scaled by the height of the bar. The former only works for a narrow range of values and the latter gives inconsistent spacing within one plot. Neither works well with logarithmic axes.
The solution I propose works independent of scale (i.e. for small and large numbers) and even correctly places labels for negative values and with logarithmic scales because it uses the visual unit points
for offsets.
I have added a negative number to showcase the correct placement of labels in such a case.
The value of the height of each bar is used as a label for it. Other labels can easily be used with Simon's for rect, label in zip(rects, labels)
snippet.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
def add_value_labels(ax, spacing=5):
"""Add labels to the end of each bar in a bar chart.
Arguments:
ax (matplotlib.axes.Axes): The matplotlib object containing the axes
of the plot to annotate.
spacing (int): The distance between the labels and the bars.
"""
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value = rect.get_height()
x_value = rect.get_x() + rect.get_width() / 2
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
va = 'bottom'
# If value of bar is negative: Place label below bar
if y_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
# Use Y value as label and format number with one decimal place
label = "{:.1f}".format(y_value)
# Create annotation
ax.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(0, space), # Vertically shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
ha='center', # Horizontally center label
va=va) # Vertically align label differently for
# positive and negative values.
# Call the function above. All the magic happens there.
add_value_labels(ax)
plt.savefig("image.png")
Edit: I have extracted the relevant functionality in a function, as suggested by barnhillec.
This produces the following output:
And with logarithmic scale (and some adjustment to the input data to showcase logarithmic scaling), this is the result:
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
Yes. Which platform are you writing for? ASP.NET C#?
List<string> myList = new List<string>();
Session["var"] = myList;
Then, to retrieve:
myList = (List<string>)Session["var"];
The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!
typedef std::shared_ptr<gate> Ptr
vector<Ptr> myConatiner;
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);
for (auto& element : myConatiner)
element->run();
Another case where I received this error was when my database query returned a null value but my user/view model type was set as non-nullable. For example, changing my UserModel field from int
to int?
resolved.
Use pd.MultiIndex.from_product
as an index in an otherwise empty dataframe, then reset its index, and you're done.
a = [1, 2, 3]
b = ["a", "b", "c"]
index = pd.MultiIndex.from_product([a, b], names = ["a", "b"])
pd.DataFrame(index = index).reset_index()
out:
a b
0 1 a
1 1 b
2 1 c
3 2 a
4 2 b
5 2 c
6 3 a
7 3 b
8 3 c
I was facing this same scaring error... :) Then I realized that I was forgetting to set a
@Html.HiddenFor(model => model.UserProfile.UserId)
for the primary key of the object being updated! I tend to forget this simple, but very important thingy!
By the way: HiddenFor
is for ASP.NET MVC.
Did you check the Project settings? I had this problem and I had the Start URL going to a different port than my server specific port. It took me too long to figure out...
I would suggest using tables (pip3 install tables
). You can save your .csv
file to .h5
using pandas (pip3 install pandas
),
import pandas as pd
data = pd.read_csv("dataset.csv")
store = pd.HDFStore('dataset.h5')
store['mydata'] = data
store.close()
You can then easily, and with less time even for huge amount of data, load your data in a NumPy array.
import pandas as pd
store = pd.HDFStore('dataset.h5')
data = store['mydata']
store.close()
# Data in NumPy format
data = data.values
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
I did this before using the MSXML library and then using the XMLHttpRequest object, see here.
Well, you can follow them :). But I don't think that doing a commit and then resetting the branch to remove that commit and similar workarounds suggested in other answers are the clean way to solve this issue.
The following solution seems to be much cleaner to me and it's also suggested by the Git itself — try to execute git status
in the repository with a conflict:
Unmerged paths:
(use "git reset HEAD <file>..." to unstage)
(use "git add <file>..." to mark resolution)
So let's do what Git suggests (without doing any useless commits):
git reset
to mark conflict(s) as resolved and unstage the changes. You can execute it without any parameters and Git will remove everything from the index. You don't have to execute git add
before.git stash drop
, because Git doesn't do that on conflict.Translated to the command-line:
$ git stash pop
# ...resolve conflict(s)
$ git reset
$ git stash drop
There are two ways of marking conflicts as resolved: git add
and git reset
. While git reset
marks the conflicts as resolved and removes files from the index, git add
also marks the conflicts as resolved, but keeps files in the index.
Adding files to the index after a conflict is resolved is on purpose. This way you can differentiate the changes from the previous stash and changes you made after the conflict was resolved. If you don't like it, you can always use git reset
to remove everything from the index.
I highly recommend using any of 3-way merge tools for resolving conflicts, e.g. KDiff3, Meld, etc., instead of doing it manually. It usually solves all or majority of conflicts automatically itself. It's huge time-saver!
If you are finding this question because you have a custom arrow on your select box and the text is going over your arrow, I found a solution that works in some browsers. Just add some padding, to the select
, on the right side.
Before:
After:
CSS:
select {
padding:0 30px 0 10px !important;
-webkit-padding-end: 30px !important;
-webkit-padding-start: 10px !important;
}
iOS ignores the padding
properties but uses the -webkit-
properties instead.
Add this extension to convert your html code to a regular string:
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
And then you show your String inside an UITextView Or UILabel
textView.text = yourString.html2String
or
label.text = yourString.html2String
If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
Assigning questionFrame.frame.size.height= screenSize.height * 0.30
will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.
questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)
Using bash
:
echo "|${COMMAND/$'\n'}|"
(Note that the control character in this question is a 'newline' (\n
), not a carriage return (\r
); the latter would have output REBOOT|
on a single line.)
Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}
:
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.
Also uses the $''
ANSI-C quoting construct to specify a newline as $'\n'
. Using a newline directly would work as well, though less pretty:
echo "|${COMMAND/
}|"
#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|
Or, using newlines:
#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|
After trying the 2 answers above (changing deployment target and restarting my iOS device), what finally fixed it for me was restarting my Mac.
copying the jar files will resolve. If by any chance you are copying the code from any tutorials, make sure the class names are spelled in correct case...for example i copied a code from one of the tutorials which had solr in S cap. Eclipse was continiously throwing the error and i also did a bit of googling ...everything was ok and it took 30 mins for me to realise the cap small issue. Am sure this will help someone
In your quesion code you are using TimeSpan.FromMinutes
incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:
public static TimeSpan FromMinutes(double value)
hence, the following code won't compile
var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile
Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;
Using pdfbox we can achive this
Example :
public static void main(String args[]) {
PDFParser parser = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
PDFTextStripper pdfStripper;
String parsedText;
String fileName = "E:\\Files\\Small Files\\PDF\\JDBC.pdf";
File file = new File(fileName);
try {
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText.replaceAll("[^A-Za-z0-9. ]+", ""));
} catch (Exception e) {
e.printStackTrace();
try {
if (cosDoc != null)
cosDoc.close();
if (pdDoc != null)
pdDoc.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.
I think NDepend looks like a more likely candidate.
Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
Hope this will help you...
RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(first_radio_listener);
and
OnClickListener first_radio_listener = new OnClickListener (){
public void onClick(View v) {
//Your Implementaions...
}
};
Prevent user to enter space in textbox in Angular 6
<input type="text" (keydown.space)="$event.preventDefault();" required />
To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
Of course you can use build in functions, but if you would like to create your own you can do something like this. The trick here is to use ~ operator that flip positive number to negative. For instance ~2 -> -3 and using negative in for list in Python will count items from the end. So if you have mid == 2 then it will take third element from beginning and third item from the end.
def median(data):
data.sort()
mid = len(data) // 2
return (data[mid] + data[~mid]) / 2
I had this when the csproj and sln files were in the same folder (stupid, I know). Once I moved to sln file to the folder above the csproj folder my so
provided I understood correctly, you should look for binascii.unhexlify
import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]
In case you would like to read/check your Target Build Settings
in runtime using code, here is the way:
1) Add a Run Script
:
cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj
It will copy the Target Build Settings
file into your Main Bundle
(will be called BuildSetting.pbxproj
).
2) You can now check the contents of that file at any time in code:
NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];
I'm using Angular 5.
In my case, I needed to import ReactiveFormsModule too.
File app.module.ts (or anymodule.module.ts):
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Here is the Swift 5 version:
let delegate = UIApplication.shared.delegate as? AppDelegate
And to access the managed object context:
if let delegate = UIApplication.shared.delegate as? AppDelegate {
let moc = delegate.managedObjectContext
// your code here
}
or, using guard:
guard let delegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let moc = delegate.managedObjectContext
// your code here
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
No router + no screen + regular Ethernet cable + RPI 2 + Raspbian Lite 2018-11-13 + Ubuntu 18.10
First we must enable the SSH server on the Pi, which is disabled by default for security.
If you already have a shell on the Pi through a non-SSH method such as screen + keyboard or UART (see below), just run:
sudo systemctl enable ssh
sudo service sshd start
as explained at: https://raspberrypi.stackexchange.com/questions/58478/ssh-not-working-with-fresh-install This persists across boots.
Otherwise, insert he SD card on your host, and create a magic empty file named ssh
file in the boot/
partition.
On Ubuntu hosts, it gets mounted automatically and you can do just:
sudo touch /media/$USER/boot/ssh
which you can confirm with:
lsblk
which contains:
mmcblk0 179:0 0 14.4G 0 disk
+-mmcblk0p1 179:1 0 43.9M 0 part /media/ciro/boot
+-mmcblk0p2 179:2 0 14.4G 0 part /media/ciro/rootfs
If you don't enable the SSHD daemon on the Pi then SSH connection will fail with:
ssh: connect to host 10.42.0.160 port 22: Connection refused
when we try it later on.
After enabling the SSH server
Next, boot the Pi, and link an Ethernet cable from your laptop directly to the Pi:
On Ubuntu 17.04 to work around this bug as mentioned on this answer you first need:
sudo apt-get install dnsmasq-base
On the host, open the network manager:
nm-connection-editor
And go:
+
sign (Add a new connection)Find the IP of the Pi on host:
cat /var/lib/misc/dnsmasq.leases
outputs something like:
1532204957 b8:27:eb:0c:1f:69 10.42.0.160 raspberrypi 01:b8:27:eb:0c:1f:69
10.42.0.160
is the IP, then as usual:
ssh [email protected]
I also have the following in my .bashrc
:
piip() ( cat /var/lib/misc/dnsmasq.leases | cut -d ' ' -f 3; )
pissh() ( sshpass -p raspberry ssh "pi@$(piip)"; )
From inside the Pi, notice that it can access the internet normally through your host's other interfaces:
ping google.com
For example on my laptop, the Pi takes up the Ethernet, but the host is also connected to the internet through WiFi.
The crossover cable is not required if the host network card supports Auto MDI-X. This is the case for most recent hardware, including for example the 2012 Lenovo T430 I tested with, which has an "Intel® 82579LM Gigabit Network Connection" which documents support for Auto MDI-X.
Now you can also:
UART serial USB converter
This is an alternative to SSH if you just want to get a shell on the Pi: https://en.wikipedia.org/wiki/Serial_port
This does not use SSH or networking itself, but rather the older, simpler, more direct, more reliable, lower bandwidth, lower distance serial interface. The Pi won't have access to the Internet with this method.
Desktop computers still have a serial port which you can connect directly wire to wire with the Pi, but these are hidden in most laptops, and so we need to buy a cheap USB adapter. Here I've used: https://www.amazon.co.uk/gp/product/B072K3Z3TL See also: https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux/367882#367882
First plug the SD card on the host, and edit the config.txt
file present in the first partition to add:
enable_uart=1
as explained at: https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=141195
This first partition contains the bootloader, its configuration files and the (Linux / your) kernel, config.txt
being one of them. The second partition contains the actual Linux root filesystem.
Now connect your computer to the Pi as:
You only need to attach 3 cables:
This is also documented at: https://www.raspberrypi.org/documentation/usage/gpio/README.md
Be careful not to link the Ground to the 5V, I've already burned 2 UART to USB chips and a RPI UART by doing that!
You don't need to connect the 5V to the 5V at all. I think you can power your Pi like that, but I've read that this is a bad idea, just use the usual USB power source.
Finally, plug the USB side of the connector to your host computer, and get a shell with:
sudo apt install screen
sudo usermod -a -G dialout $USER
screen /dev/ttyUSB0 115200
Exit with Ctrl-A \
.
Here is a video by Adafruit showing it: https://www.youtube.com/watch?v=zUBPeoLW16Q
See also
Similar question on RPI SE: https://raspberrypi.stackexchange.com/questions/3867/ssh-to-rpi-without-a-network-connection
The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.
Exception currentException = null;
As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.
Also, the finally blocks always run before the method exits. You could then requite the code snippet to:
public class C1 {
public static void main(String [] argv) throws Exception {
try {
System.out.print(1);
q();
}
catch ( Exception i ) {
// <-- currentException = Exception, as thrown by q()'s finally block
throw( new MyExc2() ); // <-- currentException = MyExc2
}
finally {
// <-- currentException = MyExc2, thrown from main()'s catch block
System.out.print(2);
throw( new MyExc1() ); // <-- currentException = MyExc1
}
} // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.
static void q() throws Exception {
try {
throw( new MyExc1() ); // <-- currentException = MyExc1
}
catch( Exception y ) {
// <-- currentException = null, because the exception is caught and not rethrown
}
finally {
System.out.print(3);
throw( new Exception() ); // <-- currentException = Exception
}
}
}
The order in which the application executes is:
main()
{
try
q()
{
try
catch
finally
}
catch
finally
}
Splice is the best to remove element from specific index. The given example is tested on console.
card = [1, 2, 3, 4];
card.splice(1,1); // [2]
card // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)
startingIndex start from 0.
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
Update:
if (localStorage.hasOwnProperty("username")) {
//
}
Another way, relevant when value is not expected to be empty string, null or any other falsy value:
if (localStorage["username"]) {
//
}
:vsp
or :sp
- splits vim into two instance but you cannot use :shell in only one of them.
Why not display another tab of the terminal not another tab of vim. If you like the idea you can try it: Ctrl-shift-t.
and move between them with Ctrl - pageup
and Ctrl - pagedown
If you want just a few shell commands you can make any shell command in vim using !
For example :!./a.out
.
Simple answer is NO !!
.
There is no
FOR
in SQL, But you can useWHILE
orGOTO
to achieve the way how theFOR
will work.
WHILE :
DECLARE @a INT = 10
WHILE @a <= 20
BEGIN
PRINT @a
SET @a = @a + 1
END
GOTO :
DECLARE @a INT = 10
a:
PRINT @a
SET @a = @a + 1
IF @a < = 20
BEGIN
GOTO a
END
I always prefer WHILE
over GOTO
statement.
If you in any doubt, have a look at JDK source code
ArrayList.clear()
source code:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
You will see that size
is set to 0 so you start from 0 position.
Please note that when adding elements to ArrayList
, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear()
you only remove references to array elements and sets size
to 0, however, capacity
stays as it was.
Here are few methods useful for printing debug messages in PHPUnit 4.x:
syslog(LOG_DEBUG, "Debug: Message 1!");
More practical example:
syslog(LOG_DEBUG, sprintf("%s: Value: %s", __METHOD__, var_export($_GET, TRUE)));
Calling syslog()
will generate a system log message (see: man syslog.conf
).
Note: Possible levels: LOG_DEBUG
, LOG_INFO
, LOG_NOTICE
, LOG_WARNING
, LOG_ERR
, etc.
On macOS, to stream the syslog messages in realtime, run:
log stream --level debug --predicate 'processImagePath contains "php"'
fwrite(STDERR, "LOG: Message 2!\n");
Note: The STDERR
constant is not available if reading the PHP script from stdin. Here is the workaround.
Note: Instead of STDERR
, you can also specify a filename.
file_put_contents('php://stderr', "LOG: Message 3!\n", FILE_APPEND);
Note: Use this method, if you don't have STDERR
constant defined.
register_shutdown_function('file_put_contents', 'php://stderr', "LOG: Message 4!\n", FILE_APPEND);
Note: Use this method, if you'd like to print something at the very end without affecting the tests.
To dump the variable, use var_export()
, e.g. "Value: " . var_export($some_var, TRUE) . "\n"
.
To print above messages only during verbose or debug mode, see: Is there a way to tell if --debug or --verbose was passed to PHPUnit in a test?
Although if testing the output is part of the test it-self, check out: Testing Output docs page.
You can use like this:
case 4: case 2:
{
//code ...
}
For use 4 or 2 switch case.
USE TIMESTAMPDIFF
MySQL function. For example, you can use:
SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')
In your case, the third parameter of TIMSTAMPDIFF
function would be the current login time (NOW()
). Second parameter would be the last login time, which is already in the database.
Addition to @Binary Nerd
If you are using Spark, use the following to get the Spark version:
spark-submit --version
or
Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
To do this without any headache:
git status
, let's say branch "development".git clone
the project from repository.git checkout development
.rsync
, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1
. You don't have to do this with rsync
of course, but it does it so smooth.The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.
Float won't convert into NVARCHAR directly, first we need to convert float into money datatype and then convert into NVARCHAR, see the examples below.
SELECT CAST(CAST(1234567890.1234 AS FLOAT) AS NVARCHAR(100))
output
1.23457e+009
SELECT CAST(CAST(CAST(1234567890.1234 AS FLOAT) AS MONEY) AS NVARCHAR(100))
output
1234567890.12
In Example2 value is converted into float to NVARCHAR
You can also install the official file
binding for Python, a library called file-magic
(it does not use ctypes, like python-magic
).
It's available on PyPI as file-magic and on Debian as python-magic. For me this library is the best to use since it's available on PyPI and on Debian (and probably other distributions), making the process of deploying your software easier. I've blogged about how to use it, also.
When using the Hibernate implementation of JPA , I've found that simply declaring the type as an ArrayList instead of List allows hibernate to store the list of data.
Clearly this has a number of disadvantages compared to creating a list of Entity objects. No lazy loading, no ability to reference the entities in the list from other objects, perhaps more difficulty in constructing database queries. However when you are dealing with lists of fairly primitive types that you will always want to eagerly fetch along with the entity, then this approach seems fine to me.
@Entity
public class Command implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
ArrayList<String> arguments = new ArrayList<String>();
}
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
You could use wmic command:
wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>
Drivetype 2 indicates that its a removable disk.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
// Inflate the layout for this fragment
txt_name = (TextView) view.findViewById(R.id.name);
txt_usranme = (TextView) view.findViewById(R.id.surname);
txt_number = (TextView) view.findViewById(R.id.number);
txt_province = (TextView) view.findViewById(R.id.province);
txt_write = (EditText) view.findViewById(R.id.editText_write);
txt_show1 = (Button) view.findViewById(R.id.buttonShow1);
txt_show1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("Onclick","Onclick");
txt_show1.setVisibility(View.INVISIBLE);
txt_name.setVisibility(View.VISIBLE);
txt_usranme.setVisibility(View.VISIBLE);
txt_number.setVisibility(View.VISIBLE);
txt_province.setVisibility(View.VISIBLE);
}
});
return view;
}
You OK !!!!
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
Don't define variables in headers. Put declarations in header and definitions in one of the .c files.
In config.h
extern const char *names[];
In some .c file:
const char *names[] =
{
"brian", "stefan", "steve"
};
If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.
I wrote an in-depth blog post about this that you can check out here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
window.location.reload()
will reload from the server and will load all your data, scripts, images, etc. again.
So if you just want to refresh the HTML, the window.location = document.URL
will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.