This solved my problem in ubuntu 18.04 when trying to use python3.6:
rm -rf ~/.local/lib/python3.6
You can move the folder to another place using mv instead of deleting it too, for testing:
mv ~/.local/lib/python3.6 ./python3.6_old
As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
define this "decoratorize function" to generate customized decorator function:
def decoratorize(FUN, **kw):
def foo(*args, **kws):
return FUN(*args, **kws, **kw)
return foo
use it this way:
@decoratorize(FUN, arg1 = , arg2 = , ...)
def bar(...):
...
I had this very same problem; here was my solution:
SCORE_CHOICES = zip( range(1,n), range(1,n) )
score = models.IntegerField(choices=SCORE_CHOICES, blank=True)
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
For me the highest rated answer didn't work.
What did work was to go to Signing and Capabilities -> Team -> add account and add the Apple ID again.
After doing this, when I built again I was asked for my login credentials and the build succeeded.
try this in your post methods callback function
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
for more info read this
You should use classes to make it more simple, instead of the attribute name, or any other jQuery selector.
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
In SQL Developer, from the top menu choose Tools > Data Export. This launches the Data Export wizard. It's pretty straightforward from there.
There is a tutorial on the OTN site. Find it here.
Like the answer above, but it wasn't quite right, or easy to slap into code so I cleaned it up a bit. Add this extension either to it's own .h and .m file or just paste right above the implementation you intend to use it:
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end
@implementation UILabel (VerticalAlign)
- (void)alignTop
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<= newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:@" \n"];
}
}
- (void)alignBottom
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i< newLinesToPad; i++)
{
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
}
@end
And then to use, put your text into the label, and then call the appropriate method to align it:
[myLabel alignTop];
or
[myLabel alignBottom];
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
you can also use: s.lower() in str.lower()
You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
My code is as follows:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here, and if you have to refresh UI put this code:
runOnUiThread(new Runnable() {
public void run() {
//your code
}
});
}
},
5000
);
brew switch to python3 by default, so if you want to still set python2 as default bin python, running:
brew unlink python && brew link python2 --force
First of all, Thank you DTing for awesome answer. It's pretty much perfect.
For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.
wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz
tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz
cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785
./install.sh
It will ask you path to python directory. Enter
../../.localpython
Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads
Based on URL you need to change the name of tar and cd command based on file received.
function loadpage (page_request, containerid)
{
var loading = document.getElementById ( "loading" ) ;
// when connecting to server
if ( page_request.readyState == 1 )
loading.style.visibility = "visible" ;
// when loaded successfully
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById(containerid).innerHTML=page_request.responseText ;
loading.style.visibility = "hidden" ;
}
}
According to Android Sqlite get last insert row id there is another query:
SELECT rowid from your_table_name order by ROWID DESC limit 1
The problem here is that while you can return false from within the .each
callback, the .each
function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each
found a match or not, we will have to use a shared variable using a closure that gets updated.
Each inner iteration of words
refers to the same notFound
variable, so we just need to update it when a match is found, and then return it. The outer closure already has a reference to it, so it can break
out when needed.
$(sentences).each(function() {
var s = this;
var notFound = true;
$(words).each(function() {
return (notFound = (s.indexOf(this) == -1));
});
return notFound;
});
You can try your example here.
I have Windows 10 64 bit, this worked for me, This solution can work for both (Anaconda/MiniConda) distributions.
If you have any antivirus software installed then try to exclude all the folders,subfolders inside 'C:\ProgramData\Anaconda3\' from
*(Note: 'C:\ProgramData\Anaconda3' this folder is default installation folder, you can change it just replace your excluded path at installation destination prompt while installing Anaconda)*
Now open Command prompt or Anaconda prompt and check installation using following command
conda list
If you get any package list then the anaconda/miniconda is successfully installed.
or you could just write the power function, with recursion as a added bonus
int power(int x, int y){
if(y == 0)
return 1;
return (x * power(x,y-1) );
}
yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!
If you are using MySQL use a field type of TIME and the associated functionality that comes with TIME.
00:00:00 is standard unix time format.
If you ever have to look back and review the tables by hand, integers can be more confusing than an actual time stamp.
You can't: DataFrame
columns are Series
, by definition. That said, if you make the dtype
(the type of all the elements) datetime-like, then you can access the quantities you want via the .dt
accessor (docs):
>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205 76032930 2015-01-24 00:05:27.513000
232 76032930 2015-01-24 00:06:46.703000
233 76032930 2015-01-24 00:06:56.707000
413 76032930 2015-01-24 00:14:24.957000
565 76032930 2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205 76032930 1
232 76032930 1
233 76032930 1
413 76032930 1
565 76032930 1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205 76032930 5
232 76032930 6
233 76032930 6
413 76032930 14
565 76032930 23
dtype: int64
If you're stuck using an older version of pandas
, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:
>>> df["TimeReviewed"].apply(lambda x: x.year)
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
Name: TimeReviewed, dtype: int64
I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it it matters to me. I wrote this extension method to make it a bit nicer:
public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> map,
Expression<Func<TDestination, object>> selector)
{
map.ForMember(selector, config => config.Ignore());
return map;
}
It can be used like so:
Mapper.CreateMap<JsonRecord, DatabaseRecord>()
.Ignore(record => record.Field)
.Ignore(record => record.AnotherField)
.Ignore(record => record.Etc);
You could also rewrite it to work with params
, but I don't like the look of a method with loads of lambdas.
A WSDL is an XML document that describes a web service. It actually stands for Web Services Description Language.
SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.
REST is an architectural style of networked systems and stands for Representational State Transfer. It's not a standard itself, but does use standards such as HTTP, URL, XML, etc.
As byte[] is mutable it is treated as only being .equals()
if its the same object.
If you want to compare the contents you have to use Arrays.equals(a, b)
BTW: Its not the way I would design it. ;)
There are two "quick" methods:
x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]
It appears that [None]*x
is faster:
>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605
But if you are ok with a range (e.g. [0,1,2,3,...,x-1]
), then range(x)
might be fastest:
>>> timeit("range(100)",number=10000)
0.012513160705566406
another way to check in realtime textField source :
@IBOutlet var textField1 : UITextField = UITextField()
override func viewDidLoad()
{
....
self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
}
func yourNameFunction(sender: UITextField) {
if sender.text.isEmpty {
// textfield is empty
} else {
// text field is not empty
}
}
var array = [[1, "grape", 42], [2, "fruit", 9]];
array.sort(function(a, b)
{
// a and b will here be two objects from the array
// thus a[1] and b[1] will equal the names
// if they are equal, return 0 (no sorting)
if (a[1] == b[1]) { return 0; }
if (a[1] > b[1])
{
// if a should come after b, return 1
return 1;
}
else
{
// if b should come after a, return -1
return -1;
}
});
The sort
function takes an additional argument, a function that takes two arguments. This function should return -1
, 0
or 1
depending on which of the two arguments should come first in the sorting. More info.
I also fixed a syntax error in your multidimensional array.
Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.
Example for Google Chrome:
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
For ExpressJs router:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
Client-side:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.
There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.
for example in
$a = array('zero', 'one', 'two', 'three');
if we do
$v = &$a[0]
the 0th element ($a[0]
) becomes a reference variable. $v
points towards that variable; therefore, if we make any change to $v
, it will be reflected in $a[0]
and vice versa.
now if we do
$v = &$a[1]
$a[1]
will become a reference variable and $a[0]
will become a normal variable (Since no one else is pointing to $a[0]
it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)
This is what happens in the first loop
foreach ($a as &$v) {
}
After the last iteration $a[3]
is a reference variable.
Since $v
is pointing to $a[3]
any change to $v
results in a change to $a[3]
in the second loop,
foreach ($a as $v) {
echo $v.'-'.$a[3].PHP_EOL;
}
in each iteration as $v
changes, $a[3]
changes. (because $v
still points to $a[3]
). This is the reason why $a[3]
changes on each iteration.
In the iteration before the last iteration, $v
is assigned the value 'two'. Since $v
points to $a[3]
, $a[3]
now gets the value 'two'. Keep this in mind.
In the last iteration, $v
(which points to $a[3]
) now has the value of 'two', because $a[3]
was set to two in the previous iteration. two
is printed. This explains why 'two' is repeated when $v is printed in the last iteration.
From the definition of height:
Applies to: all elements but non-replaced inline elements, table columns, and column groups
An a
element is, by default an inline element (and it is non-replaced).
You need to change the display (directly with the display property or indirectly, e.g. with float).
A hook that allows for overriding copy events, could be used for doing the same with paste events. The input element cannot be display: none; or visibility: hidden; sadly
export const useOverrideCopy = () => {
const [copyListenerEl, setCopyListenerEl] = React.useState(
null as HTMLInputElement | null
)
const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
() => () => {}
)
// appends a input element to the DOM, that will be focused.
// when using copy/paste etc, it will target focused elements
React.useEffect(() => {
const el = document.createElement("input")
// cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
el.style.width = "0"
el.style.height = "0"
el.style.opacity = "0"
el.style.position = "fixed"
el.style.top = "-20px"
document.body.appendChild(el)
setCopyListenerEl(el)
return () => {
document.body.removeChild(el)
}
}, [])
// adds a event listener for copying, and removes the old one
const overrideCopy = (newOverrideAction: () => any) => {
setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
const copyHandler = (e: ClipboardEvent) => {
e.preventDefault()
newOverrideAction()
}
copyListenerEl?.removeEventListener("copy", prevCopyHandler)
copyListenerEl?.addEventListener("copy", copyHandler)
copyListenerEl?.focus() // when focused, all copy events will trigger listener above
return copyHandler
})
}
return { overrideCopy }
}
Used like this:
const customCopyEvent = () => {
console.log("doing something")
}
const { overrideCopy } = useOverrideCopy()
overrideCopy(customCopyEvent)
Every time you call overrideCopy it will refocus and call your custom event on copy.
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
HTML Code
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" class="send_upload" value="upload" />
jQuery Code using bind method
$(document).ready(function() {
$('#upload').bind("click",function()
{ if(!$('#uploadImage').val()){
alert("empty");
return false;} }); });
I came up with 4 methods to achieve the results. Here is demo
Method 1:
#a {
margin-right: auto;
}
Method 2:
#a {
flex-grow: 1;
}
Method 3:
#b {
margin-left: auto;
}
Method 4:
#container {
justify-content: space-between;
}
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
For a more web-like feel:
const B = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>
I had this issue, and I set the Locale
to US
, then it work.
static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);
for String
"Sun Jul 08 00:06:30 UTC 2012"
inner join with scala
val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show
(change)
event bound to classical input change event.
https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">
(ngModelChange)
is the @Output
of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code, (ngModelChange)
emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
// do something with new value
}
Basically, it seems like there is no big difference between two, but ngModel
events gains the power when you use [ngValue]
.
<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
<option *ngFor="let currentData of allData" [ngValue]="currentData">
{{data.name}}
</option>
</select>
dataChanged(newObj) {
// here comes the object as parameter
}
assume you try the same thing without "ngModel
things"
<select (change)="changed($event)">
<option *ngFor="let currentData of allData" [value]="currentData.id">
{{data.name}}
</option>
</select>
changed(e){
// event comes as parameter, you'll have to find selectedData manually
// by using e.target.data
}
One more way/syntax to do it is: git log -S "word"
Like this you can search for example git log -S "with whitespaces and stuff @/#ü !"
In my case the issue was caused by the same name of target and folder inside a group.
Just rename conflicted file or folder to resolve the issue.
I think you are looking for qsort
.
qsort
function is the implementation of quicksort algorithm found in stdlib.h
in C/C++
.
Here is the syntax to call qsort
function:
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
List of arguments:
base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements
Here is a code example which uses qsort
to sort an array:
#include <stdio.h>
#include <stdlib.h>
int arr[] = { 33, 12, 6, 2, 76 };
// compare function, compares two elements
int compare (const void * num1, const void * num2) {
if(*(int*)num1 > *(int*)num2)
return 1;
else
return -1;
}
int main () {
int i;
printf("Before sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
// calling qsort
qsort(arr, 5, sizeof(int), compare);
printf("\nAfter sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
return 0;
}
You can type man 3 qsort
in Linux/Mac terminal to get a detailed info about qsort
.
Link to qsort man page
With Aspose.Cells library for .NET, you can easily export data of specific rows and columns from one Excel document to another. The following code sample shows how to do this in C# language.
// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");
// Create the destination excel file.
Workbook destWorkbook = new Workbook();
// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];
// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];
// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);
// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);
// Save the destination excel file.
destWorkbook.Save("Destination_Workbook.xlsx");
The following blog post explains in detail how to export data from different sources to an Excel document.
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/
Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
}
}
}
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
Seems to work for me.
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
From here.
For IIS7 and above, you also need to add the lines below:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().
As per this example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
will produce:
To unpack your data from pairs into lists use zip
:
x, y = zip(*li)
So, the one-liner:
plt.scatter(*zip(*li))
Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.
But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.
In non-optimized pseudocode:
def isBetween(a, b, c):
crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
# compare versus epsilon for floating point values, or != 0 if using integers
if abs(crossproduct) > epsilon:
return False
dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0:
return False
squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if dotproduct > squaredlengthba:
return False
return True
In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:
From <some-base-image:tag>
# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image
# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>
# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory
# Switch to user
USER ${uid}:${gid}
# Run non-privileged command
RUN apt <non-privileged command>
Assuming that all viewControllers that you present modally are wrapped inside a new navigationController (which you should always do anyway), you can add this property to your VC.
private var wasPushed: Bool {
guard let vc = navigationController?.viewControllers.first where vc == self else {
return true
}
return false
}
The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out $on
, $broadcast
and $emit
.
I think your best bet if you want both text field and label to hide simultaneously is assign each with a class and hide them like this:
jQuery(".labelClass, .inputClass").hide();
Generic answer
This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example
Object.keys(null)
Object.assign(window.UndefinedVariable, {})
As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.
Object.keys({'key': 'value'})
if (window.UndefinedVariable) {
Object.assign(window.UndefinedVariable, {})
}
Answer specific to the code in question
The line if (obj === 'null') { return null;} // null unchanged
will not
evaluate when given null
, only if given the string "null"
. So if you pass the actual null
value to your script, it will be parsed in the Object part of the code. And Object.keys(null)
throws the TypeError
mentioned. To fix it, use if(obj === null) {return null}
- without the qoutes around null.
You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services
, and checking that the service SQL Server (SQLEXPRESS
) is running. If not, start it.
While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.
You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools
(or SQL Server Configuration Manager
), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.
Verify your SQL Server connection authentication mode matches your connection string:
If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":
-- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
USE [master]
GO
DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
EXEC xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'LoginMode',
REG_DWORD,
@SqlServerAndWindowsAuthenticationMode;
GO
otherwise, run Start -> Run -> Services.msc
If so, is it running?
If it's not running then
It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.
If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.
But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.
First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.
Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data
user, or group.
So in order to make this www-data
get access
first type in;
sudo chgrp "www-data" your_project_folder
once its done, if there is no write access to the following as well;
sudo chown g+w your_project_folder
That will do the trick in Linux.
Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.
No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:
def addId(cls):
class AddId(cls):
def __init__(self, id, *args, **kargs):
super(AddId, self).__init__(*args, **kargs)
self.__id = id
def getId(self):
return self.__id
return AddId
Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:
class Foo:
pass
FooId = addId(Foo)
And in Python 3 like this (but be careful to use super()
in your classes):
@addId
class Foo:
pass
So you can have your cake and eat it - inheritance and decorators!
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Do you mean that you've got code like
if(map.containsKey(key)) doSomethingWith(map.get(key))
all over the place ? Then you should simply check whether map.get(key)
returned null and that's it.
By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey
is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.
If one really wanted to they could make there own version of scanf()
like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext()
should probably be at the bottom of the if-else if
sequence since hasNext()
will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner
implements the Iterator
class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>()
methods; and then storing the input.
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor
That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.
Disable ASLR:
sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'
Disable canaries:
gcc overflow.c -o overflow -fno-stack-protector
After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit
Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.
Now go and clobber that EIP!
The difference is that Visibility.Hidden
hides the control, but reserves the space it occupies in the layout. So it renders whitespace instead of the control.
Visibilty.Collapsed
does not render the control and does not reserve the whitespace. The space the control would take is 'collapsed', hence the name.
The exact text from the MSDN:
Collapsed: Do not display the element, and do not reserve space for it in layout.
Hidden: Do not display the element, but reserve space for the element in layout.
Visible: Display the element.
See: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)
Program
#include <math.h>
#include <stdio.h>
int main(void) {
double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
while (dbl + 1 != dbl) dbl++;
printf("%.0f\n", dbl - 1);
printf("%.0f\n", dbl);
printf("%.0f\n", dbl + 1);
return 0;
}
Result
9007199254740991 9007199254740992 9007199254740992
"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.
@quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:
#include <cstdio>
class A {
public:
virtual void Hello() = 0;
};
void A::Hello() {
printf("A::Hello\n");
}
class B : public A {
public:
void Hello() {
printf("B::Hello\n");
A::Hello();
}
};
int main() {
/* Prints:
B::Hello
A::Hello
*/
B b;
b.Hello();
return 0;
}
According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:
class A {
public:
virtual void Hello() = 0;
};
int main()
{
A a;
return 0;
}
Output:
$ g++ -c virt.cpp
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note: because the following virtual functions are pure within ‘A’:
virt.cpp:3: note: virtual void A::Hello()
Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt
method.
Combined with an ArrayList<String>
for example you can get your array of individual characters.
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
Use below XML configuration to configure logs into two or more files:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
<file value="logs\log1.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<logger additivity="false" name="RollingLogFileAppender2">
<level value="All"/>
<appender-ref ref="RollingLogFileAppender2" />
</logger>
</log4net>
Above XML configuration logs into two different files. To get specific instance of logger programmatically:
ILog logger = log4net.LogManager.GetLogger ("RollingLogFileAppender2");
You can append two or more appender elements inside log4net root element for logging into multiples files.
More info about above XML configuration structure or which appender is best for your application, read details from below links:
https://logging.apache.org/log4net/release/manual/configuration.html https://logging.apache.org/log4net/release/sdk/index.html
Destructing assignment is the best way to solve your problem.
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log("After swap a =", a, " and b =", b);
_x000D_
Any .apk file from market or unsigned
If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.
Download Dex2Jar zip from this link: SourceForge
Unzip the downloaded zip file.
Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.
dex2jar targetapp.apk file
(./dex2jar app.apk on terminal)
http://jd.benow.ca/ download decompiler from this link.
Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.
find -execdir rename
https://stackoverflow.com/a/16541670/895245 works directly only for suffixes, but this will work for arbitrary regex replacements on basenames:
PATH=/usr/bin find . -depth -execdir rename 's/_dbg.txt$/_.txt' '{}' \;
or to affect files only:
PATH=/usr/bin find . -type f -execdir rename 's/_dbg.txt$/_.txt' '{}' \;
-execdir
first cd
s into the directory before executing only on the basename.
Tested on Ubuntu 20.04, find 4.7.0, rename 1.10.
Convenient and safer helper for it
find-rename-regex() (
set -eu
find_and_replace="$1"
PATH="$(echo "$PATH" | sed -E 's/(^|:)[^\/][^:]*//g')" \
find . -depth -execdir rename "${2:--n}" "s/${find_and_replace}" '{}' \;
)
Sample usage to replace spaces ' ' with hyphens '-'.
Dry run that shows what would be renamed to what without actually doing it:
find-rename-regex ' /-/g'
Do the replace:
find-rename-regex ' /-/g' -v
Command explanation
The awesome -execdir
option does a cd
into the directory before executing the rename
command, unlike -exec
.
-depth
ensure that the renaming happens first on children, and then on parents, to prevent potential problems with missing parent directories.
-execdir
is required because rename does not play well with non-basename input paths, e.g. the following fails:
rename 's/findme/replaceme/g' acc/acc
The PATH
hacking is required because -execdir
has one very annoying drawback: find
is extremely opinionated and refuses to do anything with -execdir
if you have any relative paths in your PATH
environment variable, e.g. ./node_modules/.bin
, failing with:
find: The relative path ‘./node_modules/.bin’ is included in the PATH environment variable, which is insecure in combination with the -execdir action of find. Please remove that entry from $PATH
-execdir
is a GNU find extension to POSIX. rename
is Perl based and comes from the rename
package.
Rename lookahead workaround
If your input paths don't come from find
, or if you've had enough of the relative path annoyance, we can use some Perl lookahead to safely rename directories as in:
git ls-files | sort -r | xargs rename 's/findme(?!.*\/)\/?$/replaceme/g' '{}'
I haven't found a convenient analogue for -execdir
with xargs
: https://superuser.com/questions/893890/xargs-change-working-directory-to-file-path-before-executing/915686
The sort -r
is required to ensure that files come after their respective directories, since longer paths come after shorter ones with the same prefix.
Tested in Ubuntu 18.10.
In a query you can just do something like:
SELECT ColumnA * ColumnB FROM table
or
SELECT ColumnA - ColumnB FROM table
You can also create computed columns in your table where you can permanently use your formula.
one of best solution enjoyed it ;)
public DataTable GetContentAsDataTable(bool IgnoreHideColumns=false)
{
try
{
if (dgv.ColumnCount == 0) return null;
DataTable dtSource = new DataTable();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (IgnoreHideColumns & !col.Visible) continue;
if (col.Name == string.Empty) continue;
dtSource.Columns.Add(col.Name, col.ValueType);
dtSource.Columns[col.Name].Caption = col.HeaderText;
}
if (dtSource.Columns.Count == 0) return null;
foreach (DataGridViewRow row in dgv.Rows)
{
DataRow drNewRow = dtSource.NewRow();
foreach (DataColumn col in dtSource .Columns)
{
drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
}
dtSource.Rows.Add(drNewRow);
}
return dtSource;
}
catch { return null; }
}
To fix your code you can simply change [Cov]
to Cov.values
, the first parameter of pd.DataFrame
will become a multi-dimensional numpy
array:
Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')
But the smartest solution still is use pd.read_excel
with header=None
and names=columns_list
.
use StickyTableHeaders.js for this.
Header was transparent . so try to add this css .
thead {
border-top: none;
border-bottom: none;
background-color: #FFF;
}
Here's also an angularjs directive to implement this functionality
pullDown: function() {
return {
restrict: 'A',
link: function ($scope, iElement, iAttrs) {
var $parent = iElement.parent();
var $parentHeight = $parent.height();
var height = iElement.height();
iElement.css('margin-top', $parentHeight - height);
}
};
}
This will resolve all permissions in folder
sudo chown -R $(whoami) ./
I have just experienced the same error, in my case it was caused by the second parameter in angular.module
being missing- hopefully this may help someone with the same issue.
angular.module('MyApp');
angular.module('MyApp', []);
A scenario which I sometimes run into:
Assume you have a trunk, from which you created a release branch. After some changes on trunk (in particular creating "some-dir" directory), you create a feature/fix branch which you want later merge into release branch as well (because changes were small enough and the feature/fix is important for release).
trunk -- ... -- create "some-dir" -- ...
\ \-feature/fix branch
\- release branch
If you then try to merge the feature/fix branch directly into the release branch you will get a tree conflict (even though the directory did not even exist in feature/fix branch):
svn status
! C some-dir
> local missing or deleted or moved away, incoming file edit upon merge
So you need to explicitly merge the commits which were done on trunk before creating feature/fix branch which created the "some-dir" directory before merging the feature/fix branch.
I often forget that as that is not necessary in git.
Beginning with C# 7.3, you can use closer approximation - the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.
class SomeGeneric<T> where T : unmanaged
{
//...
}
The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.
A type is an unmanaged type if it's any of the following types:
To restrict further and eliminate pointer and user-defined types that do not implement IComparable add IComparable (but enum is still derived from IComparable, so restrict enum by adding IEquatable < T >, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):
class SomeGeneric<T> where T : unmanaged, IComparable, IEquatable<T>
{
//...
}
But this doesn't prevent from DateTime instantiation.
With LINQ, and using C# (I don't know VB much these days):
bool b = listOfStrings.Any(s=>myString.Contains(s));
or (shorter and more efficient, but arguably less clear):
bool b = listOfStrings.Any(myString.Contains);
If you were testing equality, it would be worth looking at HashSet
etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.
update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch
to find each item - check by lookup to see if it is a full or partial match.
File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
This line has the error because what the code expected is the directory name + file name
, not the file name.
This is the correct one
File.Copy(source_dir + file_name, destination_dir + file_name.Substring(source_dir.Length), true);
If you look at this bug 224128, it appears that MergeSort is being used by Mozilla.
First I executed:
sudo chown -R $(whoami):admin /usr/local
Then:
cd $(brew --prefix) && git fetch origin && git reset --hard origin/master
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):
./gradlew wrapper --gradle-version 5.5
Moreover, you can use --distribution-type
parameter with either bin
or all
value to choose a distribution type. Use all
distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:
./gradlew wrapper --gradle-version 5.5 --distribution-type all
Or you can create a custom wrapper
task
task wrapper(type: Wrapper) {
gradleVersion = '5.5'
}
and run ./gradlew wrapper
.
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
You could add the following Maven dependency.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.1</version>
</dependency>
You could use following import in your java code.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGett;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.methods.HttpUriRequest;
You could use following code block in your java code.
HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("http://example.domain/someuri");
HttpResponse response = client.execute(httpUriRequest);
System.out.println("Response:"+response);
The most recent and in my opinion preferred approach is the f-string
:
''.join(f'{i:02x}' for i in [1, 15, 255])
The old format style was the %
-syntax:
['%02x'%i for i in [1, 15, 255]]
The more modern approach is the .format
method:
['{:02x}'.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string
syntax:
[f'{i:02x}' for i in [1, 15, 255]]
Note that the f'{i:02x}'
works as follows.
:
is the input or variable to format. x
indicates that the string should be hex. f'{100:02x}'
is '64'
and f'{100:02d}'
is '1001'
.02
indicates that the string should be left-filled with 0
's to length 2
. f'{100:02x}'
is '64'
and f'{100:30x}'
is ' 64'
.Handle the onError
event for the image to reassign its source using JavaScript:
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
The following compatibility table lists the browsers that support the error facility:
Try providing username and password in your client like below
client.ClientCredentials.UserName.UserName = @"Domain\username"; client.ClientCredentials.UserName.Password = "password";
The problem is extra 13 byte which server.py receives at the start. To resolve that write "l = c.recv(1024)" twice before the while loop as below.
print "Receiving..."
l = c.recv(1024) #this receives 13 bytes which is corrupting the data
l = c.recv(1024) # Now actual data starts receiving
while (l):
This resolves the issue, tried with different format and sizes of files. If anyone knows what this starting 13 bytes refers to, please reply.
The Symfony documentation now explicitly shows how to do this:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql
If you don't want use ngOnChange
implement og onChange()
method, you can also subscribe to changes of a specific item by valueChanges
event, ETC.
myForm = new FormGroup({
first: new FormControl(),
});
this.myForm.valueChanges.subscribe((formValue) => {
this.changeDetector.markForCheck();
});
the markForCheck()
writen because of using in this declare:
changeDetection: ChangeDetectionStrategy.OnPush
In my case the data directory was automatically initialized with the --initialize-insecure
option. So /var/log/mysql/error.log
does not contain a temporary password but:
[Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
What worked was:
shell> mysql -u root --skip-password
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
Details: MySQL 5.7 Reference Manual > 2.10.4 Securing the Initial MySQL Account
The way I have done this is to give the user permission to the tables that I didn't want them to have access to. Then fine tune the select permission in SSMS by only allowing select permission to the columns that are in my view. This way, the select clause on the table is only limited to the columns that they see in the view anyways.
Shaji
Such things are best answered by looking at the official specification:
go to the specification: https://www.w3.org/TR/html5/
search for "a
element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element
check "Content attributes", which lists all allowed attributes for the a
element:
- Global attributes
href
target
download
rel
hreflang
type
check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes
As you will see, the alt
attribute is not allowed on the a
element.
Also you’d notice that the src
attribute isn’t allowed either.
By validating your HTML, errors like these are reported to you.
Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a
element can have another attribute in HTML 5.1: rev
.
You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.
instead of query-replace you may also use M-x delete-trailing-whitespace
All algorithms can be defined recursively. That makes it much, much easier to visualize and prove.
Some algorithms (e.g., the Ackermann Function) cannot (easily) be specified iteratively.
A recursive implementation will use more memory than a loop if tail call optimization can't be performed. While iteration may use less memory than a recursive function that can't be optimized, it has some limitations in its expressive power.
public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
if (map1 == null || map2 == null)
return false;
for (String ch1 : map1.keySet()) {
if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
return false;
}
for (String ch2 : map2.keySet()) {
if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
return false;
}
return true;
}
According to the Material design guidelines (here, under "DP unit grid"), your product icon should be of size 48 dp, with a padding of 1dp, except for the case of XXXHDPI, where the padding should be 4dp.
So, in pixels, the sizes are:
I recommend to avoid using VectorDrawable as some launchers don't support it, but I think WEBP should be ok as long as you have your minSdk support transparency for them (API 18 and above - Android 4.3).
If you publish on the Play Store, the requirement to what to upload there are (based on here) :
Starting with Java 8, the general purpose solution for a primitive array arr
, and a value to search val
, is:
public static int indexOf(char[] arr, char val) {
return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}
This code creates a stream over the indexes of the array with IntStream.range
, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst
. findFirst
returns an OptionalInt
, as it is possible that no matching indexes were found. So we invoke orElse(-1)
to either return the value found or -1
if none were found.
Overloads can be added for int[]
, long[]
, etc. The body of the method will remain the same.
For object arrays, like String[]
, we could use the same idea and have the filtering step using the equals
method, or Objects.equals
to consider two null
elements equal, instead of ==
.
But we can do it in a simpler manner with:
public static <T> int indexOf(T[] arr, T val) {
return Arrays.asList(arr).indexOf(val);
}
This creates a list wrapper for the input array using Arrays.asList
and searches the index of the element with indexOf
.
This solution does not work for primitive arrays, as shown here: a primitive array like int[]
is not an Object[]
but an Object
; as such, invoking asList
on it creates a list of a single element, which is the given array, not a list of the elements of the array.
I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!
_you can also add more colors to the gradient if you want or just select other colors from the color generator
.rainbow2 {_x000D_
background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
background-image: -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
background-image: -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
background-image: -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
background-image: linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
Old question, but, why do not use a const
object map?
Instead of doing this:
enum Foo {
BAR = 60,
EVERYTHING_IS_TERRIBLE = 80
}
console.log(Object.keys(Foo))
// -> ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE", 60, 80]
Do this (pay attention to the as const
cast):
const Foo = {
BAR: 60,
EVERYTHING_IS_TERRIBLE: 80
} as const
console.log(Object.keys(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> [60, 80]
Selector name{
font-weight:bold;
}
Suppose you want to make bold for p element
p{
font-weight:bold;
}
You can use other alternative value instead of bold like
p{
font-weight:bolder;
font-weight:600;
}
Under Xcode 4.5.2, you can find the .app file in this way:
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.
Where the files are placed
Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/
folder.
Inside that folder is a folder with the name of your app. Which in turn contains a resources/
directory where you will find the icons/
and splashscreen/
folders.
In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.
What to do
All you have to do is save the icon files in this folder. So that's:
YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons
Same for splashscreen files.
Notes
After placing the files there, rebuild the project using cordova build ios
AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.
It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.
And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />
). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected]
instead of icon-57-2x.png
.
Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).
hope it will work
@Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })
Here String.Empty
will be the empty as a default selector.
As explained before:
ALTER TABLE TABLEName
drop CONSTRAINT FK_CONSTRAINTNAME;
ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
FOREIGN KEY (FId)
REFERENCES OTHERTABLE
(Id)
ON DELETE CASCADE ON UPDATE NO ACTION;
As you can see those have to be separated commands, first dropping then adding.
The ubuntu package name is qt5-default
, not qt
.
You may take a look at this Java based framework for remote command execution, incl. via SSH: https://github.com/jkovacic/remote-exec It relies on two opensource SSH libraries, either JSch (for this implementation even an ECDSA authentication is supported) or Ganymed (one of these two libraries will be enough). At the first glance it might look a bit complex, you'll have to prepare plenty of SSH related classes (providing server and your user details, specifying encryption details, provide OpenSSH compatible private keys, etc., but the SSH itself is quite complex too). On the other hand, the modular design allows for simple inclusion of more SSH libraries, easy implementation of other command's output processing or even interactive classes etc.
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
int maxLength = 100;
if (ViewData["size"] != null)
{
size = (int)ViewData["size"];
}
if (ViewData["maxLength"] != null)
{
maxLength = (int)ViewData["maxLength"];
}
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>
In my view, I use
<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>
Works like a charm for me!
For Ubuntu 14.04 with
PHP 7.0.13-1+deb.sury.org~trusty+1 (cli) ( NTS )
sudo apt-get install php-xml
worked for me.
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:
var result = window.matchMedia("(any-pointer:coarse)").matches;
That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.
The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.
https://patrickhlauke.github.io/touch/touchscreen-detection/
Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia
In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
Alarm Manager:
Add To XML Layout (*init these view on create in main activity)
<TimePicker
android:id="@+id/timepicker"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"></TimePicker>
<Button
android:id="@+id/btn_start"
android:text="start Alarm"
android:onClick="start_alarm_event"
android:layout_width="match_parent"
android:layout_height="52dp" />
Add To Manifest (Inside application tag && outside activity)
<receiver android:name=".AlarmBroadcastManager"
android:enabled="true"
android:exported="true"/>
Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)
public class AlarmBroadcastManager extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
In Main Activity (Add these Functions):
@RequiresApi(api = Build.VERSION_CODES.M)
public void start_alarm_event(View view){
Calendar calendar=Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
setAlarm(calendar.getTimeInMillis());
}
public void setAlarm(long timeInMillis){
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmBroadcastManager.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();
}
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
There are plenty of templating systems that offer more compact syntax for your views. Smarty is venerable and popular. This article lists 10 others.
To install more recent versions of OpenJDK, I use this. Example for OpenJDK 14:
brew info adoptopenjdk
brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk14
See https://github.com/AdoptOpenJDK/homebrew-openjdk for current info.
Try to use this xPath expression:
//book/title[@lang='it']/..
That should give you all book nodes in "it" lang
Three days on this, and I believe there's a race condition between adb and the emulator. On a request to run an app, with no emulator already running, you see the "Initializing ADB", then the emulator choice, it starts and you get "Waiting for target to come online". An adb kill-server, or a kill -9, or an "End Process" of adb with the task manager will cause adb to die, restart, your APK installs and you're good to go. It does seem funky to me that an "adb kill-server" causes adb to die and then restart here, but that's another mystery, maybe.
using Microsoft.Win32;
string chkRegVC = "NO";
private void checkReg_vcredist() {
string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(regKey))
{
if (uninstallKey != null)
{
string[] productKeys = uninstallKey.GetSubKeyNames();
foreach (var keyName in productKeys)
{
if (keyName == "{196BB40D-1578-3D01-B289-BEFC77A11A1E}" ||//Visual C++ 2010 Redistributable Package (x86)
keyName == "{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}" ||//Visual C++ 2010 Redistributable Package (x64)
keyName == "{C1A35166-4301-38E9-BA67-02823AD72A1B}" ||//Visual C++ 2010 Redistributable Package (ia64)
keyName == "{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}" ||//Visual C++ 2010 SP1 Redistributable Package (x86)
keyName == "{1D8E6291-B0D5-35EC-8441-6616F567A0F7}" ||//Visual C++ 2010 SP1 Redistributable Package (x64)
keyName == "{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}" //Visual C++ 2010 SP1 Redistributable Package (ia64)
) { chkRegVC = "OK"; break; }
else { chkRegVC = "NO"; }
}
}
}
}
There are several good articles on the subject on dev2qa.com site, about Contacts Provider
API:
How To Add Contact In Android Programmatically
How To Update Delete Android Contacts Programmatically
How To Get Contact List In Android Programmatically
Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure
Official Google documentation on Contacts Provider here
You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.
declare @TableVar table
(
firstCol varchar(50) NOT NULL,
secondCol varchar(50) NOT NULL
)
BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
firstCol,
secondCol
)
SELECT firstCol,
secondCol
FROM @TableVar
GO
In a nutshell, "fork" creates a copy of the project hosted on your own GitHub account.
"Clone" uses git software on your computer to download the source code and it's entire version history unto that computer
The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).
You can further verify my point by finding the class of your output-
>class(output)
"integer"
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
In DOS you couldn't use environment variables on the command line, only in batch files, where they used the %
sign as a delimiter. If you wanted a literal %
sign in a batch file, e.g. in an echo
statement, you needed to double it.
This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your %
signs in a .cmd file.
This is how I implemented my strcmp: it works like this: it compares first letter of the two strings, if it is identical, it continues to the next letter. If not, it returns the corresponding value. It is very simple and easy to understand: #include
//function declaration:
int strcmp(char string1[], char string2[]);
int main()
{
char string1[]=" The San Antonio spurs";
char string2[]=" will be champins again!";
//calling the function- strcmp
printf("\n number returned by the strcmp function: %d", strcmp(string1, string2));
getch();
return(0);
}
/**This function calculates the dictionary value of the string and compares it to another string.
it returns a number bigger than 0 if the first string is bigger than the second
it returns a number smaller than 0 if the second string is bigger than the first
input: string1, string2
output: value- can be 1, 0 or -1 according to the case*/
int strcmp(char string1[], char string2[])
{
int i=0;
int value=2; //this initialization value could be any number but the numbers that can be returned by the function
while(value==2)
{
if (string1[i]>string2[i])
{
value=1;
}
else if (string1[i]<string2[i])
{
value=-1;
}
else
{
i++;
}
}
return(value);
}
For logging purposes, I'm afraid there's no nicer way of doing this but to construct the string yourself:
string query = cmd.CommandText;
foreach (SqlParameter p in cmd.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
Assuming df
is your dataframe,
df_prime = pd.concat([df, pd.DataFrame([[np.nan] * df.shape[1]], columns=df.columns)], ignore_index=True)
where df_prime
equals df
with an additional last row of NaN's.
Note that pd.concat
is slow so if you need this functionality in a loop, it's best to avoid using it.
In that case, assuming your index is incremental, you can use
df.loc[df.iloc[-1].name + 1,:] = np.nan
String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)
mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);
Add the border to each cell with this:
table > tbody > tr > td { border: 1px solid rgba(255, 255, 255, 0.1); }
Remove the top border from all the cells in the first row:
table > tbody > tr:first-child > td { border-top: 0; }
Remove the left border from the cells in the first column:
table > tbody > tr > td:first-child { border-left: 0; }
Remove the right border from the cells in the last column:
table > tbody > tr > td:last-child { border-right: 0; }
Remove the bottom border from the cells in the last row:
table > tbody > tr:last-child > td { border-bottom: 0; }
VARIABLE = value
Normal setting of a variable, but any other variables mentioned with the value
field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared
VARIABLE := value
Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.
VARIABLE ?= value
Setting of a variable only if it doesn't have a value. value
is always evaluated when VARIABLE
is accessed. It is equivalent to
ifeq ($(origin FOO), undefined)
FOO = bar
endif
See the documentation for more details.
VARIABLE += value
Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)
var ref = Request.ServerVariables("HTTP_REFERER");
Type within the quotes any other server variable name you want.
This works for spanish operation system.
Script accepts two parameters:
script.bat listofurls.txt output.txt
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
set SERVER_ADDRESS=No se pudo resolver el host
for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP')
do (
if %%v==Haciendo set SERVER_ADDRESS=%%z
if %%v==Respuesta set SERVER_ADDRESS=%%x
if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
you may have installed tensorflow to virtualenv. activate it and tensorboard command will become available.
I use lots of erasing level
String donen = "lots of stupid whitespaces and new lines and others..."
//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");
and now we have a clean one row
Here are both way of saving data with insertMany and save
1) Mongoose save array of documents with insertMany
in bulk
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const data = [/* array of object which data need to save in db */];
Potato.insertMany(data)
.then((result) => {
console.log("result ", result);
res.status(200).json({'success': 'new documents added!', 'data': result});
})
.catch(err => {
console.error("error ", err);
res.status(400).json({err});
});
})
2) Mongoose save array of documents with .save()
These documents will save parallel.
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const saveData = []
const data = [/* array of object which data need to save in db */];
data.map((i) => {
console.log(i)
var potato = new Potato(data[i])
potato.save()
.then((result) => {
console.log(result)
saveData.push(result)
if (saveData.length === data.length) {
res.status(200).json({'success': 'new documents added!', 'data': saveData});
}
})
.catch((err) => {
console.error(err)
res.status(500).json({err});
})
})
})
I prefer to setup meld as a separate command, like so:
git config --global alias.meld '!git difftool -t meld --dir-diff'
This makes it similar to the git-meld.pl script here: https://github.com/wmanley/git-meld
You can then just run
git meld
So that works fine, but how on earth do you give the buttons margins so there is space between them?
You call setMargins()
on the LinearLayout.LayoutParams
object.
I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.
LinearLayout.LayoutParams
is a subclass of LinearLayout.MarginLayoutParams
, as indicated in the documentation.
Is this impossible?
No.
it wouldn't be the first Android layout task you can only do in XML
You are welcome to supply proof of this claim.
Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
//get main activity
final Activity main_activity=getActivity();
//list view click listener
final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stringText;
//in normal case
stringText= ((TextView)view).getText().toString();
//in case if listview has separate item layout
TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
stringText=textview.getText().toString();
//show selected
Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
}
});
//populate listview
I use grc
(Generic Colouriser), which allows you to colour the output of a number of commands including diff
.
It is a python script which can be wrapped around any command. So instead of invoking diff file1 file2
, you would invoke grc diff file1 file2
to see colourised output. I have aliased diff
to grc diff
to make it easier.
there is dual method for fcm
fcm messaging notification and app notification
in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default.
in 2nd you can full control what happen when you recieve message example
onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); }
you will recieve data with(yourKey)
but that not from fcm message
that from fcm cloud functions
reguard
For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:
GROUP BY meetingID
HAVING COUNT(caseID) = 3
In your general case:
GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7
Or (possibly easier to read?),
GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6
What about this?
git stash save stashname
git stash apply stash^{/stashname}
If you are using Virtual Machine (VM), allocate more RAM to your VM and your problem will be solved.
to leave the file in the repo but ignore future changes to it:
git update-index --assume-unchanged <file>
and to undo this:
git update-index --no-assume-unchanged <file>
to find out which files have been set this way:
git ls-files -v|grep '^h'
credit for the original answer to http://blog.pagebakers.nl/2009/01/29/git-ignoring-changes-in-tracked-files/
With Git 2.15 (Q4 2017), "git branch
" learned "-c/-C
" to create a new branch by copying an existing one.
See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar
).
See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305
).
(Merged by Junio C Hamano -- gitster
-- in commit 3b48045, 03 Oct 2017)
branch
: add a--copy
(-c
) option to go with--move
(-m
)Add the ability to
--copy
a branch and its reflog and configuration, this uses the same underlying machinery as the--move
(-m
) option except the reflog and configuration is copied instead of being moved.This is useful for e.g. copying a topic branch to a new version, e.g.
work
towork-2
after submitting thework
topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike--move
keeping the other already-submitted branch around for reference.
Note: when copying a branch, you remain on your current branch.
As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:
When creating a new branch
B
by copying the branchA
that happens to be the current branch, it also updatesHEAD
to point at the new branch.
It probably was made this way because "git branch -c A B
" piggybacked its implementation on "git branch -m A B
",This does not match the usual expectation.
If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.
I'm not sure it can be done purely with CSS, unless you're comfortable in sort of faking it with illusions. Maybe use Josh Mein's answer, and set #container
to overflow:hidden
.
For what it's worth, here's a jQuery solution:
var contH = $('#container').height(),
upH = $('#up').height();
$('#down').css('height' , contH - upH);
With /^[a-zA-Z]/
you only check the first character:
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:
a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"If you want to check if all characters are letters, use this instead:
/^[a-zA-Z]+$/.test(str);
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:
+
: Between one and unlimited times, as many as possible, giving back as needed (greedy)a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"$
: Assert position at the end of the string (or before the line break at the end of the string, if any)Or, using the case-insensitive flag i
, you could simplify it to
/^[a-z]+$/i.test(str);
Or, since you only want to test
, and not match
, you could check for the opposite, and negate it:
!/[^a-z]/i.test(str);
In my case, this was the output:
LANGUAGE = (unset),
LC_ALL = (unset),
LC_PAPER = "ro_RO.UTF-8",
LC_ADDRESS = "ro_RO.UTF-8",
....
The solution was:
sudo locale-gen ro_RO.UTF-8
If you insist on running the .html
file locally and not serving it with a webserver, you can prevent those cross origin requests from happening in the first place by making the problematic resources available inline.
I had this problem when trying to to serve .js
files through file://
. My solution was to update my build script to replace <script src="...">
tags with <script>...</script>
.
Here's a gulp
approach for doing that:
1.
run npm install --save-dev
to packages gulp
, gulp-inline
and del
.
2.
After creating a gulpfile.js
to the root directory, add the following code (just change the file paths for whatever suits you):
let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');
gulp.task('inline', function (done) {
gulp.src('dist/index.html')
.pipe(inline({
base: 'dist/',
disabledTypes: 'css, svg, img'
}))
.pipe(gulp.dest('dist/').on('finish', function(){
done()
}));
});
gulp.task('clean', function (done) {
del(['dist/*.js'])
done()
});
gulp.task('bundle-for-local', gulp.series('inline', 'clean'))
gulp bundle-for-local
or update your build script to run it automatically.You can see the detailed problem and solution for my case here.
You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.
When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.
Reference:
C++03 standard, § 14.7.2.4:
The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.
EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:
.cpp
file. #include
the .cpp
file defining the template at the .cpp
file using the template. Each of them have their pros and cons,
Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.
Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.
While including cpp files is confusing at the same time shares the problems of both above approaches.
I find first method the easiest to follow and implement and hence advocte using it.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
In my case Malwarebytes was holding a handle on my program's executable:
Using Process Explorer to close the handle, or just disabling antivirus for a bit work just fine.
If you use this, check man sudo
too:
#!/bin/bash
sudo echo "Hi, I'm root"
sudo -u nobody echo "I'm nobody"
sudo -u 1000 touch /test_user
Me did not nothing, just copied development Bin folder DLLs to online deployed Bin folder and it worked fine for me.
Simply check that the directory/package of the class is marked as "Sources Root". I believe the package should be application or execution in your case.
To do so, right click on the package, and select Mark Directory As->Sources Root.
You can use an ActionFilterAttribute
public class BasicAuthAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected NetworkCredential Nc { get; set; }
public BasicAuthAttribute(string user,string pass)
{
this.Nc = new NetworkCredential(user,pass);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"].ToString();
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring(6)))
.Split(':');
var user = new {Name = cred[0], Pass = cred[1]};
if (user.Name == Nc.UserName && user.Pass == Nc.Password) return;
}
filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
filterContext.Result = new UnauthorizedResult();
}
}
and add the attribute to your controller
[BasicAuth("USR", "MyPassword")]
There is no real "difference". Web site is a more anachronistic term that exists from the early days of the internet where the notion of a dynamic application that can respond to user input was much more limited and much less common. Commercial websites started out largely as interactive brochures (with the notable exception of hotel/airline reservation sites). Over time their functionality (and the supporting technologies) became more and more responsive and the line between an application that you install on your computer and one that exists in the cloud became more and more blurred.
If you're just looking to express yourself clearly when speaking about what you're building, I would continue to describe something that is an interactive brochure or business card as a "web site" and something that actually *does something that feels more like an application as a web app.
The most basic distinction would be if a website has a supporting database that stores user data and modifies what the user sees based on some user specified criteria, then it's probably an app of some sort (although I would be reluctant to describe Amazon.com as a web app, even though it has a lot of very user-specific functionality). If, on the other hand, it is mostly static .html files that link to one another, I would call that a web site.
Most often, these days, a web app will have a large portion of its functionality written in something that runs on the client (doing much of the processing in either javascript or actionscript, depending on how its implemented) and reaches back through some http process to the server for supporting data. The user doesn't move from page to page as much and experiences whatever they're going to experience on a single "page" that creates the app experience for them.
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
The copy constructor given by @Stephen C is the way to go when you have a Set
you created (or when you know where it comes from).
When it comes from a Map.entrySet()
, it will depend on the Map
implementation you're using:
findbugs says
The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.
As addAll()
is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.
Not all Map
implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry
objects yourself:
Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));
Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.
Hello developers,
Please try this code
var default_date= new Date(); // or your date
$('#datetimepicker').datetimepicker({
format: 'DD/MM/YYYY HH:mm', // format you want to show on datetimepicker
useCurrent:false, // default this is set to true
defaultDate: default_date
});
if you want to set default date then please set useCurrent to false otherwise setDate or defaultDate like methods will not work.
I found the Invalidate() creating too much of flickering. Here's my situation. A custom control I am developing draws its whole contents via handling the Paint event.
this.Paint += this.OnPaint;
This handler calls a custom routine that does the actual painting.
private void OnPaint(object sender, PaintEventArgs e)
{
this.DrawFrame(e.Graphics);
}
To simulate scrolling I want to repaint my control every time the cursor moves while the left mouse button is pressed. My first choice was using the Invalidate() like the following.
private void RedrawFrame()
{
var r = new Rectangle(
0, 0, this.Width, this.Height);
this.Invalidate(r);
this.Update();
}
The control scrolls OK but flickers far beyond any comfortable level. So I decided, instead of repainting the control, to call my custom DrawFrame() method directly after handling the MouseMove event. That produced a smooth scrolling with no flickering.
private void RedrawFrame()
{
var g = Graphics.FromHwnd(this.Handle);
this.DrawFrame(g);
}
This approach may not be applicable to all situations, but so far it suits me well.
Use a Thread.UncaughtExceptionHandler
.
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Thread t = new Thread() {
@Override
public void run() {
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException();
}
};
t.setUncaughtExceptionHandler(h);
t.start();
function function_one() {_x000D_
function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
Once you compute the sum of the two sets of word vectors, you should take the cosine between the vectors, not the diff. The cosine can be computed by taking the dot product of the two vectors normalized. Thus, the word count is not a factor.
/var/lib/tomcat7/webapps/
find / -name 'tomcat_version' -type d
You can create an iterator in Python 3.x or a list in Python 2.x by using:
filter(r.match, list)
To convert the Python 3.x iterator to a list, simply cast it; list(filter(..))
.
The following code writes python lists into columns in csv
import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
wr.writerow(("List1", "List2"))
wr.writerows(export_data)
myfile.close()
The output looks like this
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
First solution is Use range_based for loop, like:
Note: When range_expression
’s type is std::map
then a range_declaration
’s type is std::pair
.
for ( range_declaration : range_expression )
//loop_statement
Code 1:
typedef std::map<std::string, std::map<std::string, std::string>> StringToStringMap;
StringToStringMap my_map;
for(const auto &pair1 : my_map)
{
// Type of pair1 is std::pair<std::string, std::map<std::string, std::string>>
// pair1.first point to std::string (first key)
// pair1.second point to std::map<std::string, std::string> (inner map)
for(const auto &pair2 : pair1.second)
{
// pair2.first is the second(inner) key
// pair2.second is the value
}
}
The Second Solution:
Code 2
typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, StringMap> StringToStringMap;
StringToStringMap my_map;
for(StringToStringMap::iterator it1 = my_map.begin(); it1 != my_map.end(); it1++)
{
// it1->first point to first key
// it2->second point to inner map
for(StringMap::iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++)
{
// it2->second point to value
// it2->first point to second(inner) key
}
}
In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
I also got the same error. Reason for that I was compiling the project using Maven. I had JAVA_HOME pointing to JDK7 and hence java 1.7 was being used for compilation and when running the project I was using JDK1.5. Changing the below entry in .classpath file or change in the eclipse as in the screenshot resolved the issue.
classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5
Although a bit hidden it's in the official docs here where can the library be found among the sdk's code, and how to get it with resources (the Eclipse way)
it's just your own style,nothing a bad style code,and nothing a good style code,just difference our code with the others.
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
This also closely relates to:
if ("foo".equals(bar)) {
which is convenient if you don't want to deal with NPEs:
if (bar!=null && bar.equals("foo")) {