Pointing to Best Practices for Using Strings in the .NET Framework:
StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for comparisons as your safe default for culture-agnostic string matching.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for better performance.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
values instead of string operations based on CultureInfo.InvariantCulture
when the comparison is linguistically irrelevant (symbolic, for example).And finally:
StringComparison.InvariantCulture
in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.Try out this package - https://www.npmjs.com/package/gen-random-colors.
It also provides the ability to configure the color set from 0 to 5 (0 is the darkest).
babel-preset-es2015
is now deprecated and you'll get a warning if you try to use Laurence's solution.
To get this working with Babel 6.24.1+, use babel-preset-env
instead:
npm install babel-preset-env --save-dev
Then add env
to your presets in your .babelrc
:
{
"presets": ["env"]
}
See the Babel docs for more info.
To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the IP_MULTICAST_TTL
socket option as an unsigned char. Otherwise you will get an error.
This worked for me on Solaris 10 and 11:
import socket
import struct
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
Do an UPSERT:
UPDATE MyTable SET FieldA=@FieldA WHERE Key=@Key IF @@ROWCOUNT = 0 INSERT INTO MyTable (FieldA) VALUES (@FieldA)
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
this works too.
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
output will look like this
df #enter
x y z #col names
1 2 3
This command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.
node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js
I had the same problem, just use console.log(...)
(like firebug), and the install a log viewer application, this will allow you to view all the logs for your browser.
First, select the element. You can usually use the ID like this:
$("#searchField"); // select element by using "#someid"
Then, to set the value, use .val("something")
as in:
$("#searchField").val("something"); // set the value
Note that you should only run this code when the element is available. The usual way to do this is:
$(document).ready(function() { // execute when everything is loaded
$("#searchField").val("something"); // set the value
});
For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.
@interface MyViewController () {
NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath *currentIndex;//Current Selected Row
@implementation MyViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
txtDetails.delegate = self;
txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
return cell;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
currentTxtRow = self.currentIndex.row;
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
currentTxtRow += 1;
self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
[currentTxtfield becomeFirstResponder];
} else {
[self.view endEditing:YES];
[currentTxtfield resignFirstResponder];
}
}
To grab the text from textfield-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
switch (self.currentIndex.row) {
case 0:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 1:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 2:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
default:
break;
}
}
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
you have to install the service, go to wamp->Apache->Service->Install service, then a command prompt window will pop up, then press enter, and after a few seconds go to the same route Services-> and click Start/Resume service, and you ready
Put it in config/config.php
, It will work for whole application or index.php
of codeigniter.
I prefer /^\s+$|^$/gi
to match empty and empty spaces.
console.log(" ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
Node.js doesn't enforce any file naming conventions (except index.js
). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";
xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
The above code is taken directly off csharp.net please take a look on the site.
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
Here is a solution in case you use jquery and Facebook Asynchronous Lazy Loading:
// listen to an Event
$(document).bind('fbInit',function(){
console.log('fbInit complete; FB Object is Available');
});
// FB Async
window.fbAsyncInit = function() {
FB.init({appId: 'app_id',
status: true,
cookie: true,
oauth:true,
xfbml: true});
$(document).trigger('fbInit'); // trigger event
};
Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:
int count;
byte[] bytes = new byte[4096];
try {
while ((count = is.read(bytes)) > 0) {
System.out.println(count);
bos.write(bytes, 0, count);
}
} catch ( Exception e )
{
//It will land here....
}
// Then continue from here
EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!
Hope this post solves any of your issues
Hi try this code....
package my.test.service;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Sample {
public static void main(String args[]) {
final String SMTP_HOST = "smtp.gmail.com";
final String SMTP_PORT = "587";
final String GMAIL_USERNAME = "[email protected]";
final String GMAIL_PASSWORD = "xxxxxxxxxx";
System.out.println("Process Started");
Properties prop = System.getProperties();
prop.setProperty("mail.smtp.starttls.enable", "true");
prop.setProperty("mail.smtp.host", SMTP_HOST);
prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
prop.setProperty("mail.smtp.port", SMTP_PORT);
prop.setProperty("mail.smtp.auth", "true");
System.out.println("Props : " + prop);
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_USERNAME,
GMAIL_PASSWORD);
}
});
System.out.println("Got Session : " + session);
MimeMessage message = new MimeMessage(session);
try {
System.out.println("before sending");
message.setFrom(new InternetAddress(GMAIL_USERNAME));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
message.setSubject("My First Email Attempt from Java");
message.setText("Hi, This mail came from Java Application.");
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
Transport transport = session.getTransport("smtp");
System.out.println("Got Transport" + transport);
transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
System.out.println("message Object : " + message);
System.out.println("Email Sent Successfully");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
C# to JavaScript: you can register script block to run on page like following:
ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);
replace alert()
part with your function name.
For calling C# method from JavaScript you can use ScriptManager
or jQuery
. I personally use jQuery
. You need to decorate the method that you want to call from JavaScript with WebMethod
attribute. For more information regarding calling C# method (called PageMethod
) from jQuery
you can refer to Dave Ward's post.
white-space: pre-wrap
in the terminal on your mac os or linux os type this code
mail -s (subject) (receiversEmailAddress) <<< "how are you?"
for an example try this
mail -s "hi" [email protected] <<< "how are you?"<br>
Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset
is a function to check if something exists and has a value, not to get access to the value.
Change your PHP to be:
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;
The above line will check to see if the post variable exists. If it does exist it will set $uid
to equal the posted value. If it does not exist then it will set $uid
equal to 0.
Later in your code you can check the value of $uid
and react accordingly
if($uid==0) {
echo 'User ID not found';
}
This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.
Multiple parameters can be given like below,
@RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
, @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
//logic
}
Avoid using bind_address
in your my.cnf file, if you have any.
Ref: http://dev.mysql.com/doc/refman/5.5/en/can-not-connect-to-server.html
The following code can cause similar error:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
tx.Commit();
}
Assert.That(movie.Actors.Count == 1);
You can fix it simply:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
Assert.That(movie.Actors.Count == 1);
tx.Commit();
}
You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this
parent-div {
display: flex;
flex-wrap: wrap;
/* for horizontal aligning of child divs */
justify-content: center;
/* for vertical aligning */
align-items: center;
}
child-div {
width: /* yoursize for each div */
;
}
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
This is the official documentation supporting the above answers.
Changing the icon font location Bootstrap assumes icon font files will be located in the ../fonts/ directory, relative to the compiled CSS files. Moving or renaming those font files means updating the CSS in one of three ways: Change the @icon-font-path and/or @icon-font-name variables in the source Less files. Utilize the relative URLs option provided by the Less compiler. Change the url() paths in the compiled CSS. Use whatever option best suits your specific development setup.
Other than this one mistake the new users would do is, after downloading the bootstrap zip from the official website. They would tend to skip the fonts folder for copying in their dev setup. So missing fonts folder can also lead to this problem
Use the ::before
pseudo element. This way only you don't have to deal with Javascript or creating links for each cell. Using the following table
structure
<table>
<tr>
<td><a href="http://domain.tld" class="rowlink">Cell</a></td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
all we have to do is create a block element spanning the entire width of the table using ::before
on the desired link (.rowlink
) in this case.
table {
position: relative;
}
.rowlink::before {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 1.5em; /* don't forget to set the height! */
}
The ::before
is highlighted in red in the demo so you can see what it's doing.
rsync -avlzp /path/to/folder [email protected]:/path/to/remote/folder
As I understand it, an np-hard problem is not "harder" than an np-complete problem. In fact, by definition, every np-complete problem is:
-- Intro. to Algorithms (3ed) by Cormen, Leiserson, Rivest, and Stein, pg 1069
num.toStringAsFixed()
rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:
n = num.parse(n.toStringAsFixed(2));
I got the same error {AttributeError: 'bytes' object has no attribute 'read'}
in python3.
This worked for me later without using json:
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))
float: left
… Below are the most common ways to achieve two elements side-by-side…
Some basic css styles for parent
and child
elements in these examples:
.parent {
background: mediumpurple;
padding: 1rem;
}
.child {
border: 1px solid indigo;
padding: 1rem;
}
Using the float
solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)
html
<div class='parent'>
<div class='child float-left-child'>A</div>
<div class='child float-left-child'>B</div>
</div>
css
.float-left-child {
float: left;
}
html
<div class='parent'>
<div class='child inline-block-child'>A</div>
<div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
Note: the space between these two child elements can be removed, by removing the space between the div tags:
html
<div class='parent'>
<div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
html
<div class='parent flex-parent'>
<div class='child flex-child'>A</div>
<div class='child flex-child'>B</div>
</div>
css
.flex-parent {
display: flex;
}
.flex-child {
flex: 1;
}
html
<div class='parent inline-flex-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.inline-flex-parent {
display: inline-flex;
}
html
<div class='parent grid-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.grid-parent {
display: grid;
grid-template-columns: 1fr 1fr
}
I had the exact same problem. Here is the solution that worked for me: simply put your properties file path in the cmd line this way :
-Dlog4j.configuration=<FILE_PATH> (ex: log4j.properties)
Hope this will help you
Other regex answers in this page will accept an IP with a number over 255.
This regex will avoid this problem:
import re
def validate_ip(ip_str):
reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
if re.match(reg, ip_str):
return True
else:
return False
1.downlad nvm
2.install chocolaty
3.change C:\Program Files\node to C:\Program Files\nodejsx
emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows
If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.
First, the official document does NOT guarantee that the GetHashCode()
returns an unique identifier (see Object.GetHashCode Method ()):
You should not assume that equal hash codes imply object equality.
Second, assume you have a very small amount of objects so that GetHashCode()
will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode()
to always return 0. Then every object of C will get the same hash code.
Unfortunately, Dictionary
, HashTable
and some other associative containers will make use this method:
A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.
So, this approach has great limitations.
And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.
I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;
namespace ObjectSet
{
public interface IObjectSet
{
/// <summary> check the existence of an object. </summary>
/// <returns> true if object is exist, false otherwise. </returns>
bool IsExist(object obj);
/// <summary> if the object is not in the set, add it in. else do nothing. </summary>
/// <returns> true if successfully added, false otherwise. </returns>
bool Add(object obj);
}
public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
{
/// <summary> unit test on object set. </summary>
internal static void Main() {
Stopwatch sw = new Stopwatch();
sw.Start();
ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
for (int i = 0; i < 10000000; ++i) {
object obj = new object();
if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
public bool IsExist(object obj) {
return objectSet.TryGetValue(obj, out tryGetValue_out0);
}
public bool Add(object obj) {
if (IsExist(obj)) {
return false;
} else {
objectSet.Add(obj, null);
return true;
}
}
/// <summary> internal representation of the set. (only use the key) </summary>
private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();
/// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
private static object tryGetValue_out0 = null;
}
[Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
{
/// <summary> unit test on object set. </summary>
internal static void Main() {
Stopwatch sw = new Stopwatch();
sw.Start();
ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
for (int i = 0; i < 10000000; ++i) {
object obj = new object();
if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
public bool IsExist(object obj) {
bool firstTime;
idGenerator.HasId(obj, out firstTime);
return !firstTime;
}
public bool Add(object obj) {
bool firstTime;
idGenerator.GetId(obj, out firstTime);
return firstTime;
}
/// <summary> internal representation of the set. </summary>
private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
}
}
In my test, the ObjectIDGenerator
will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for
loop.
Also, the benchmark result is that the ConditionalWeakTable
implementation is 1.8x faster than the ObjectIDGenerator
implementation.
I just want to add something to the rest of the answers here. Input elements are considered empty or void elements (other empty elements are area , base , br , col , hr , img , input , link , meta , and param. You can also check here), meaning they cannot have any content. In addition to not having any content, empty elements cannot have any pseudo-elements like ::after and ::before, which I consider a major drawback.
SELECT *
FROM TableName
WHERE columnNAme IS NULL OR
LTRIM(RTRIM(columnName)) = ''
return await Task.FromResult(new MyClass());
http://sourceforge.net/projects/eclipse-rbe/
as already stated property files should be encoded in ISO 8859-1
You can use the above plugin for eclipse IDE to make the Unicode conversion for you.
This may be a easy solution.
var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");
'opts' is deprecated.
in ggplot2 >= 0.9.2
use
p + theme(legend.position = "none")
I fix the lack of example's library here:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">
Your JRE_HOME does not need to point to the "bin" directory. Just set it to C:\Program Files\Java\jre1.8.0_25
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
I saw this error when my header file was missing closing brackets.
Causing this error:
// Obj.h
class Obj {
public:
Obj();
Fixing this error:
// Obj.h
class Obj {
public:
Obj();
};
The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload
of the body-element.
You must write that function body outside the ready();
because ready is used to call a function or to bind a function with binding id like this.
$(document).ready(function() {
$("Some id/class name").click(function(){
alert("i'm in");
});
});
but you can't do this if you are calling "showAmount" function onchange/onclick event
$(document).ready(function() {
function showAmount(value){
alert(value);
}
});
You have to write "showAmount" outside the ready();
function showAmount(value){
alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
alert("will display on page load")
});
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
Without using 'length' you can do it like this:
if ($('input[type=checkbox]').is(":checked")) {
//any one is checked
}
else {
//none is checked
}
NaN
means "Not a Number" and is the result of undefined operations on floating point numbers like for example dividing zero by zero. (Note that while dividing a non-zero number by zero is also usually undefined in mathematics, it does not result in NaN but in positive or negative infinity).
This should display the image inline:
.content-dir-item img.mail {
display: inline-block;
*display: inline; /* for older IE */
*zoom: 1; /* for older IE */
}
You can use:
System.getProperty("os.name")
P.S. You may find this code useful:
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)
$command = "php ".CRON_PATH.php ";_x000D_
if(substr(php_uname(), 0, 7) == "Windows"){_x000D_
pclose(popen("start /B ". $command, "r"));_x000D_
}else{_x000D_
shell_exec($command ." > /dev/null &");_x000D_
}
_x000D_
I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.
double d = 3.14159;
printf ("%.2f", d);
But if you need rounding please refer to this post
Just use MultipleActiveResultSets=True
in your connection string.
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
Here's what we do:
Create a new connection, set the name, IP address and the appropriate port:
Set up authentication, if required
Optionally set up other available settings for SSL, SSH, etc.
Save and connect
android.text.style.ClickableSpan
can solve your problem.
SpannableString ss = new SpannableString("Android is a Software stack");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
startActivity(new Intent(MyActivity.this, NextActivity.class));
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
In XML:
<TextView
...
android:textColorLink="@drawable/your_selector"
/>
Today I got this error, and after debugging I figured out that the actual tables were misssing, which I was referring using synonyms. So I suggest - first check that whether the tables exists!! :-))
You need to make sure images come first and put in a comma after the background image call. then it actually does work:
background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */
public class Outer {
public static class Inner {}
}
... it can be declared static - as long as it is a member class.
From the JLS:
Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.3).
and here:
The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.
A CHAR(x)
column can only have exactly x
characters.
A VARCHAR(x)
column can have up to x
characters.
Since your MD5 hashes will always be the same size, you should probably use a CHAR
.
However, you shouldn't be using MD5 in the first place; it has known weaknesses.
Use SHA2 instead.
If you're hashing passwords, you should use bcrypt.
It is also possible to use enumeration.
typedef enum {
typeNo1 = 1,
typeNo2,
typeNo3,
typeNo4,
NumOfTypes = typeNo4
} TypeOfSomething;
This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve
ones.
So just to leave no confusions:
--env
is not supported in angular 6
--env
got changed into --configuration
|| -c
(and is now more powerful)angular.json
file:
{ ... "build": "configurations": ...
propertyfileReplacements
part, (but more options are available){ ... "serve": "configurations": ...
propertybrowserTarget="your-project-name:build:staging"
I had a similar problem:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.
In my case, I know the image works in other places, then was a corrupted local image.
I solved the issue removing the image (docker rmi <imagename>
) and pulling it again(docker pull <imagename>
).
I did a docker system prune
too, but I think it's not mandatory.
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
In may case, I'd simply used
vagrant up
instead of
homestead up
for my forge larval setup using homestead. I'm assuming this meant the site was getting served, but the MySQL server wasn't ever booted. When I used the latter command to launch my vagrant box, the error went away.
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span>
by itself.
In Regards to Bootstrap:
span6
: this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6
would have a width of 50%..col-*
classes (e.g. col-sm-6
), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadaysEscaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.
Try something like this:
start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
You can use these Extension Methods: (Save as PartialWithScript.cs)
namespace System.Web.Mvc.Html
{
public static class PartialWithScript
{
public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
{
if (htmlHelper.ViewBag.ScriptPartials == null)
{
htmlHelper.ViewBag.ScriptPartials = new List<string>();
}
if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
{
htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
}
htmlHelper.ViewBag.ScriptPartialHtml = true;
htmlHelper.RenderPartial(partialViewName);
}
public static void RenderPartialScripts(this HtmlHelper htmlHelper)
{
if (htmlHelper.ViewBag.ScriptPartials != null)
{
htmlHelper.ViewBag.ScriptPartialHtml = false;
foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
{
htmlHelper.RenderPartial(partial);
}
}
}
}
}
Use like this:
Example partial: (_MyPartial.cshtml) Put the html in the if, and the js in the else.
@if (ViewBag.ScriptPartialHtml ?? true)
<p>I has htmls</p>
}
else {
<script type="text/javascript">
alert('I has javascripts');
</script>
}
In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.
@{ Html.RenderPartialScripts(); }
Then to use your partial, simply do this: It will render only the html at this location.
@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}
In my project i am using ajax and i create a web method in my code behind like this
in front
$("#attachedfiles a").live("click", function () {
var row = $(this).closest("tr");
var fileName = $("td", row).eq(0).html();
$.ajax({
type: "POST",
url: "SendEmail.aspx/RemoveFile",
data: '{fileName: "' + fileName + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { },
failure: function (response) {
alert(response.d);
}
});
row.remove();
});
in code behind
[WebMethod]
public static void RemoveFile(string fileName)
{
List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName)))
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName));
}
}
i think this will help you.
While entering the serial port name into the code in arduino IDE, enter the whole port address i.e:
/dev/cu.usbmodem*
or
/dev/cu.UG-*
where the *
is the port number.
And for the port number in case of mac just open terminal and type
ls /dev/*
and then search for the port that u have set in arduino IDE.
So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.
So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:
RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be
Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).
Go to Java tab:
Set your Java properties, for example:
Java virtual machine
C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll
Java virtual machine
C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar
Java Options:
-Dcatalina.home=C:\tomcat
-Dcatalina.base=C:\tomcat
-Djava.io.tmpdir=C:\tomcat\temp
-Djava.util.logging.config.file=C:\tomcat\conf\logging.properties
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000
Java 9 options:
--add-opens=java.base/java.lang=ALL-UNNAMED
--add-opens=java.base/java.io=ALL-UNNAMED
--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
My clarification on this matter:
Basically all of the mentioned types (service, factory, provider, etc.) are just creating and configuring global variables (that are of course global to the entire application), just as old fashioned global variables were.
While global variables are not recommended, the real usage of these global variables is to provide dependency injection, by passing the variable to the relevant controller.
There are many levels of complications in creating the values for the "global variables":
app.config
.
app.config
file , and this $.get function behaves just as the factory above, in that its return value is used to initialize the "global" variables. There is a simple one-line answer:
Write - exit()
in the command
That's it!
You can do the following:
Load the data:
test <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
header=FALSE)
Note that the default value of the header
argument for read.csv
is TRUE
so in order to get all lines you need to set it to FALSE
.
Add names to the different columns in the data.frame
names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
or alternative and faster as I understand (not reloading the entire dataset):
colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
In my situation it was matter of the permissions:
sudo chmod -R +777 <your_folder_path>
If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.
See this answer... How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
To clear the referencing memory, and run the next MYSQL fetch
If you either use Buffered
or Unbuffered
result set for fetching data, first you must simply clear the fetched data from the memory, once you have fetched all the data. As you can't execute another MYSQL procedure on the same connection until you clear the fetched memory.
Add this below function right end of your script, so it will solve the problem
$numRecords->close(); or $numRecords->free(); // This clears the referencing memory, and will be ready for the next MYSQL fetch
textField.layer.borderWidth = 3;
will add border, which worked as padding for me.
I do like this,you can have a try
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
echo json_encode($array); //outputs---> "name1":"value1", "name2":"value2", ...
OR
echo print_r($array, true);
if you already install nodejs from source for example, and execjs isn't recognizing it you might want to try this tip: https://coderwall.com/p/hyjdlw
For fine tuning the position of an inline-block
item, use top and left:
position: relative;
top: 5px;
left: 5px;
Thanks CSS-Tricks!
Your query apparently returned all correct dates, even considering the time.
If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.
Make sure your mydate
column is a datetime
type.
As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.
The C89 standard states that UINT_MAX
should be at least 2^16-1, USHRT_MAX
2^16-1 and ULONG_MAX
2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (CHAR_BIT
).
C++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values.
You should however not derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case CHAR_BIT
must be at least 32. Just remember that "byte" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.
Try Stretch="UniformToFill" on the Image
To remove all array elements irrespective of any given id, use this:
collection.update(
{ },
{ $pull: { 'contact.phone': { number: '+1786543589455' } } }
);
Instead of hiding each element, you can hide the whole axis:
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
Or, you can set the ticks to an empty list:
frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])
In this second option, you can still use plt.xlabel()
and plt.ylabel()
to add labels to the axes.
This has been answered and accepted, but if someone is still wondering why are things a bit messed up today, you'll have to read this:
http://webaim.org/blog/user-agent-string-history/
It gives a good idea of how gecko, webkit and other major rendering engines evolved and what led to the current state of messed up user-agent strings.
Quoting the last paragraph for TL;DR purposes:
And then Google built Chrome, and Chrome used Webkit, and it was like Safari, and wanted pages built for Safari, and so pretended to be Safari. And thus Chrome used WebKit, and pretended to be Safari, and WebKit pretended to be KHTML, and KHTML pretended to be Gecko, and all browsers pretended to be Mozilla, and Chrome called itself
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13
, and the user agent string was a complete mess, and near useless, and everyone pretended to be everyone else, and confusion abounded.
There is another way to archive it.
In the BaseController
class create a method that returns a Model class like for instance.
public MenuPageModel GetTopMenu() { var m = new MenuPageModel(); // populate your model here return m; }
Layout
page you can call that method GetTopMenu()
@using GJob.Controllers <header class="header-wrapper border-bottom border-secondary"> <div class="sticky-header" id="appTopMenu"> @{ var menuPageModel = ((BaseController)this.ViewContext.Controller).GetTopMenu(); } @Html.Partial("_TopMainMenu", menuPageModel) </div> </header>
double d;
int rounded = (int)Math.Round(d);
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
I use WinForms and my way to use File.Exists(string path) is the next one:
public bool FileExists(string fileName)
{
var workingDirectory = Environment.CurrentDirectory;
var file = $"{workingDirectory}\{fileName}";
return File.Exists(file);
}
fileName must include the extension like myfile.txt
CGFloat is a regular float on 32-bit systems and a double on 64-bit systems
typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit
So you won't get any performance penalty.
You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
I found it in http://www.baeldung.com/hikaricp and it works.
Your pom.xml
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.3</version>
</dependency>
Your data.xml
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"
/>
Your jdbc.properties
jdbc.driverClassName=org.postgresql.Driver
jdbc.dialect=org.hibernate.dialect.PostgreSQL94Dialect
jdbc.databaseurl=jdbc:postgresql://localhost:5432/dev_db
jdbc.username=dev
jdbc.password=dev
Sorry for adding another answer to an old post but I usually get a scroll event very well by using this code (it works at least on 6.1)
element.addEventListener('scroll', function() {
console.log(this.scrollTop);
});
// This is the magic, this gives me "live" scroll events
element.addEventListener('gesturechange', function() {});
And that works for me. Only thing it doesn't do is give a scroll event for the deceleration of the scroll (Once the deceleration is complete you get a final scroll event, do as you will with it.) but if you disable inertia with css by doing this
-webkit-overflow-scrolling: none;
You don't get inertia on your elements, for the body though you might have to do the classic
document.addEventListener('touchmove', function(e) {e.preventDefault();}, true);
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
Here's a move that I'm using to set the color dynamically, it defaults to primary theme if the variable is undefined.
in your component define your color
/**Sets the button colors - Defaults to primary them color */
@Input('buttonsColor') _buttonsColor: string
in your style (sass here) - this forces the icon to use the color of it's container
.mat-custom{
.mat-icon, .mat-icon-button{
color:inherit !important;
}
}
in your html surround your button with a div
<div [class.mat-custom]="!!_buttonsColor" [style.color]="_buttonsColor">
<button mat-icon-button (click)="doSomething()">
<mat-icon [svgIcon]="'refresh'" color="primary"></mat-icon>
</button>
</div>
A better polyfill from the MDN that supports removal of BOM and NBSP:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string)
instead. That being said, if you are targeting an older environment without native .trim()
support, you are likely to have more important performance issues to deal with.
I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :
https://gist.github.com/smalot/6183152
Hope it helps everone
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.
Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.
In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.
Below a useless code is given, but it will suffice to do away with your some confusions about Runnable
. It will print "Hello World".
class NamedRunnable implements Runnable {
public void run() { // The run method prints a message to standard output.
System.out.println("Hello World");
}
public static void main(String[]arg){
NamedRunnable namedRunnable = new NamedRunnable( );
namedRunnable.run();
}
}
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
It's quite unclear how you are computing the size ("the size in debug mode"?").
Use printf()
:
printf("the size of c is %u\n", (unsigned int) sizeof c);
Normally you'd print a size_t
value (which is the type sizeof
returns) with %zu
, but if you're using a pre-C99 compiler like Visual Studio that won't work.
You need to find the typedef
statements in your code that define the custom names like uint8
and so on; those are not standard so nobody here can know how they're defined in your code.
New C code should use <stdint.h>
which gives you uint8_t
and so on.
Might also be interesting for you to know that you can use:
{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)
to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)
Try this piece of code to create circular progress bar(pie chart). pass it integer value to draw how many percent of filling area. :)
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}
I suspect you are having a problem with factors. For example,
> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8
Some comments:
as.numeric
to do with these values?read.csv
, try using the argument stringsAsFactors=FALSE
sep="/t
and not sep="\t"
head(pitchman)
to check the first fews rows of your datapichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
since I don't have access to the data set.Try including stdint.h
or inttypes.h
.
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
==
has higher precedence than &
. You might want to wrap your operations in ()
to specify how you want your operands to bind to the operators.
((a[0] & 1) == 0)
Similarly for all parts of the if
condition.
Someone else recommend dos2unix
and I strongly recommend it as well. I'm just providing more details.
If installed, jump to the next step. If not already installed, I would recommend installing it via yum
like:
yum install dos2unix
Then you can use it like:
dos2unix fileIWantToRemoveWindowsReturnsFrom.txt
In MSBuild or Teamcity use command line
MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64
or use shorter form:
MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64
However you need to set up platform in your project anyway, see the answer by Julien Hoarau.
you can use json_decode to decode that boolean
$string = 'false';
$boolean = json_decode($string);
if($boolean) {
// Do something
} else {
//Do something else
}
You can use the before
or after
pseudo-element and apply some CSS to it. There are various ways. You can add both before
and after
, and rotate and position each of them to form one of the bars. An easier solution is adding two borders to just the before
element and rotate it using transform: rotate
.
Scroll down for a different solution that uses an actual element instead of the pseuso elements
In this case, I've added the arrows as bullets in a list and used em
sizes to make them size properly with the font of the list.
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul.big {_x000D_
list-style: none;_x000D_
font-size: 300%_x000D_
}_x000D_
_x000D_
li::before {_x000D_
position: relative;_x000D_
/* top: 3pt; Uncomment this to lower the icons as requested in comments*/_x000D_
content: "";_x000D_
display: inline-block;_x000D_
/* By using an em scale, the arrows will size with the font */_x000D_
width: 0.4em;_x000D_
height: 0.4em;_x000D_
border-right: 0.2em solid black;_x000D_
border-top: 0.2em solid black;_x000D_
transform: rotate(45deg);_x000D_
margin-right: 0.5em;_x000D_
}_x000D_
_x000D_
/* Change color */_x000D_
li:hover {_x000D_
color: red; /* For the text */_x000D_
}_x000D_
li:hover::before {_x000D_
border-color: red; /* For the arrow (which is a border) */_x000D_
}
_x000D_
<ul>_x000D_
<li>Item1</li>_x000D_
<li>Item2</li>_x000D_
<li>Item3</li>_x000D_
<li>Item4</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="big">_x000D_
<li>Item1</li>_x000D_
<li>Item2</li>_x000D_
<li>Item3</li>_x000D_
<li>Item4</li>_x000D_
</ul>
_x000D_
Of course you don't need to use before
or after
, you can apply the same trick to a normal element as well. For the list above it is convenient, because you don't need additional markup. But sometimes you may want (or need) the markup anyway. You can use a div
or span
for that, and I've even seen people even recycle the i
element for 'icons'. So that markup could look like below. Whether using <i>
for this is right is debatable, but you can use span for this as well to be on the safe side.
/* Default icon formatting */_x000D_
i {_x000D_
display: inline-block;_x000D_
font-style: normal;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
/* Additional formatting for arrow icon */_x000D_
i.arrow {_x000D_
/* top: 2pt; Uncomment this to lower the icons as requested in comments*/_x000D_
width: 0.4em;_x000D_
height: 0.4em;_x000D_
border-right: 0.2em solid black;_x000D_
border-top: 0.2em solid black;_x000D_
transform: rotate(45deg);_x000D_
}
_x000D_
And so you can have an <i class="arrow" title="arrow icon"></i> in your text._x000D_
This arrow is <i class="arrow" title="arrow icon"></i> used to be deliberately lowered slightly on request._x000D_
I removed that for the general public <i class="arrow" title="arrow icon"></i> but you can uncomment the line with 'top' <i class="arrow" title="arrow icon"></i> to restore that effect.
_x000D_
If you seek more inspiration, make sure to check out this awesome library of pure CSS icons by Nicolas Gallagher. :)
I agree with @Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:
import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';
class App extends React.Component {
handleClick(){
const data = this.props.someStateObject.data;
this.props.someDispatchFunction(data);
}
render(){
return (
<div>
<div onClick={ this.handleClick.bind(this)}>Click Me!</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { someStateObject: state.someStateObject };
};
const mapDispatchToProps = (dispatch) => {
return {
someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
I used @hobodave's code, with this little tweak to prevent re-crawling all fragment variants of the same URL:
<?php
function crawl_page($url, $depth = 5)
{
$parts = parse_url($url);
if(array_key_exists('fragment', $parts)){
unset($parts['fragment']);
$url = http_build_url($parts);
}
static $seen = array();
...
Then you can also omit the $parts = parse_url($url);
line within the for loop.
The function expects a string.
file_exists()
does not work properly with HTTP URLs.
For creating git tag you can simply run git tag <tagname>
command by replacing with the actual name of the tag.
Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more
To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example
insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);
now, select the inserted record.
select ename, hiredate from emp where ename='Mac';
the result is
ENAME HIREDATE
Mac 06-JAN-13
voila, now your actual date format is found.
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
You need "VT-x supported processor" at least to run Android emulator with Hardware acceleration.
If you have enabled or installed "Hyper-V" in your windows 8 then please remove it and disable the "Hyper threading" and enable "Virtualization".
For using custom drawable:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:drawable="@drawable/my_drawable"
android:pivotX="50%"
android:pivotY="50%" />
(add under res/drawable progress.xml
). my_drawable
may be xml, png
Then in your layout use
<ProgressBar
android:id="@+id/progressBar"
android:indeterminateDrawable="@drawable/progress_circle"
...
/>
Using your radio button's ID, try rb.SelectedValue
.
Step 1: Install Graphviz binary
Windows:
Linux:
Step 2: Install graphviz module for python
pip:
conda:
to anyone looking for solution to the flickering/blinking issue when you already have DividerItemDecoration
. i seem to have solved it like this:
override fun onDrawOver(...)
{
//code from before
//do NOT return on null
val childInContact = getChildInContact(recyclerView, currentHeader.bottom)
//add null check
if (childInContact != null && mHeaderListener.isHeader(recyclerView.getChildAdapterPosition(childInContact)))
{
moveHeader(...)
return
}
drawHeader(...)
}
this seems to be working but can anyone confirm i did not break anything else?
At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:
sed -i '' -e's/[[:space:]]*$//' "$1"
This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1)
There are seven possible actions to take when such event occurs:
CASCADE
: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE
.PROTECT
: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT
.RESTRICT
: (introduced in Django 3.1) Similar behavior as PROTECT
that matches SQL's RESTRICT
more accurately. (See django documentation example)SET_NULL
: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL
.SET_DEFAULT
: Set the default value. SQL equivalent: SET DEFAULT
.SET(...)
: Set a given value. This one is not part of the SQL standard and is entirely handled by Django.DO_NOTHING
: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: NO ACTION
. (2)Source: Django documentation
See also the documentation of PostgreSQL for instance.
In most cases, CASCADE
is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT
and SET_NULL
are often useful. Setting CASCADE
where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.
Additional note to clarify cascade direction
It's funny to notice that the direction of the CASCADE
action is not clear to many people. Actually, it's funny to notice that only the CASCADE
action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that CASCADE
direction is not clear to you, it actually means that on_delete
behavior is not clear to you.
In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don't bother if it's deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, and it's part of its attributes (article=article_B
, but what is article_B???). This is where on_delete
steps in, to determine how to resolve this integrity error, either by saying:
PROTECT
or RESTRICT
in Django/SQL)SET_NULL
)CASCADE
behavior).SET_DEFAULT
, or even SET(...)
).DO_NOTHING
)I hope it makes cascade direction clearer. :)
Footnotes
(1) Django has its own implementation on top of SQL. And, as mentioned by @JoeMjr2 in the comments below, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is an open ticket to add support for database-level on delete constrains in Django.
(2) Actually, there is one case where
DO_NOTHING
can be useful: If you want to skip Django's implementation and implement the constraint yourself at the database-level.
There's this way too (new to EcmaScript5):
dictionary.data.forEach(function(item){
console.log(item.name + ' ' + item.id);
});
Same approach for images
Given that most recommended error mode for PDO is ERRMODE_EXCEPTION
, no direct execute()
result verification will ever work. As the code execution won't even reach the condition offered in other answers.
So, there are three possible scenarios to handle the query execution result in PDO:
try..catch
operator.For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever
On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.
Only in case you have a handling scenario other than just reporting the error, put your insert statement in a try..catch
operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example code from my article on error handling with PDO:
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
echo "Success!";
In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.
While again - just to tell a user something like "Your insert was successful" no condition is ever needed.
Well, for your sample and any with a limited number of unique columns, this should do it.
select
distinct a,
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'),
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT')
from t t1
For callback purposes I usually implement my own generic Runnable
with input parameter(s):
public interface Runnable<TResult> {
void run(TResult result);
}
Usage is simple:
myManager.doCallbackOperation(new Runnable<MyResult>() {
@Override
public void run(MyResult result) {
// do something with the result
}
});
In manager:
public void doCallbackOperation(Runnable<MyResult> runnable) {
new AsyncTask<Void, Void, MyResult>() {
@Override
protected MyResult doInBackground(Void... params) {
// do background operation
return new MyResult(); // return resulting object
}
@Override
protected void onPostExecute(MyResult result) {
// execute runnable passing the result when operation has finished
runnable.run(result);
}
}.execute();
}
Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.
Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.
Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)
Good luck.
A solution with numpy for quick access to all indexes:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
I know I'm am very late on this, but here some usefull samples:
'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select
or
'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
.value = .value
end with
To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like
lngLast = cells(rows.count,3).end(xlUp).row
I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).
The "timestamp" column in this example is like a "last-touched" column.x`
The code below uses a separate column "version" for optimistic locking.
private long version;
private Date timeStamp
@Version
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)
From the MySQL manual regarding TIMESTAMP :
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
It can be done this way as well
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}
NOTE: Not 100% Cross Browser
Check browser compatibility @ http://caniuse.com/#search=FileReader
as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..
The Fiddle: http://jsfiddle.net/d2atnbrt/3/
THE HTML CODE:
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
THE JS CODE:
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed
This is as basic as i could get it,
EDIT - Generating A Table
The Fiddle: http://jsfiddle.net/d2atnbrt/5/
This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..
One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least
Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls
This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.
For mongoDB database restore use this command here
mongorestore --db databasename --drop dump file path
ShowPopUpForToDoList: function (id, apprId, tab) {
var snapShot = "isFromAlert";
if (tab != "Request")
snapShot = "isFromTodoList";
$.ajax({
type: "GET",
url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
data: { id: id, tab: tab },
async:false,
success: function (data) {
ActionForm.EditActionFormPopup(id, snapShot);
}
});
},
Here SetParamForToDoList
will be excecuted first after the function ActionForm.EditActionFormPopup
will fire.
The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are
Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.
SQL> CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID NUMBER,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5 6
Table created.
SQL> CREATE TABLE USER
(
ID NUMBER NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5
CREATE TABLE USER
*
ERROR at line 1:
ORA-00903: invalid table name
SQL>
That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:
SQL> 1
1* CREATE TABLE USER
SQL> a s
1* CREATE TABLE USERs
SQL> l
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
SQL> r
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
Table created.
SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);
Table altered.
SQL>
And lo! No ORA-2270 error.
Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.
Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:
ORA-02267: column type incompatible with referenced column type
An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:
CREATE TABLE USERs
(
ID number NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
);
CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID constraint FK_USERID references users,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
);
Environment.Exit(exitCode); //exit code 0 is a proper exit and 1 is an error
You don't need to use display:inline
to achieve this:
.inline {
border: 1px solid red;
margin:10px;
float:left;/*Add float left*/
margin :10px;
}
You can use float-left
.
Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.
Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
$resp = array();
foreach ($entries as $entry) {
$row = array();
foreach ($entry as $key => $value) {
array_push($row, $value);
}
array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);
Note that for the $key => $value
to work, your object
's attributes must be public, the private ones will not get fetched.
The end result is that you get something like this:
blah,blah,blah
blah,blah,blah
<input type="text" autoFocus />
always try the simple and basic solution first, works for me.
We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:
https://gitlab.example.com/<group>/<project>/commit/<commit hash>
We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.
For me just ${workspace}
worked without even initializing the variable 'workspace.'
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
You can use contains
(this works with an arbitrary sequence):
df.filter($"foo".contains("bar"))
like
(SQL like with SQL simple regular expression whith _
matching an arbitrary character and %
matching an arbitrary sequence):
df.filter($"foo".like("bar"))
or rlike
(like with Java regular expressions):
df.filter($"foo".rlike("bar"))
depending on your requirements. LIKE
and RLIKE
should work with SQL expressions as well.
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
I had the same error with python manage.py runserver
.
For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. :)
So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.
you can use just
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version></version>
</dependency>
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
It's used for proxying requests to other servers.
An example from http://wiki.nginx.org/LoadBalanceExample is:
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_pass http://myproject;
}
}
}
This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.
Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _
underscores.
Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }
EDIT :
Optionally, the Where-Object
command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:
To skip any document files
Dir |
Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
To process only directories (pre-3.0 version)
Dir |
Where-Object { $_.Mode -match "^d" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
PowerShell v3.0 introduced new Dir
flags. You can also use Dir -Directory
there.
To skip any files already containing an underscore (or some other character)
Dir |
Where-Object { -not $_.Name.Contains("_") } |
Rename-Item -NewName { $_.Name -replace " ","_" }
This is an informational message only. What the message is telling you is that the chromedriver executable will only accept connections from the local machine.
Most driver implementations (the Chrome driver and the IE driver for sure) create a HTTP server. The language bindings (Java, Python, Ruby, .NET, etc.) all use a JSON-over-HTTP protocol to communicate with the driver and automate the browser. Since the HTTP server is simply listening on an open port for HTTP requests generated by the language bindings, connections to the HTTP server started by the language bindings are only allowed to come from other processes on the same host. Note carefully that this limitation does not apply to connections the browser can make to outside websites; rather it simply prevents incoming connections from other websites.
Try and retrieve the text property of the link button in the code behind:
protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
string val = ((LinkButton)sender).Text
}
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName + "="));
var suffix = url.substring(url.indexOf(paramName + "="));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url + hash;
}
Call the function above in your onclick event.
You can try this as well, which is really a combination of previous answers from other posters here :
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "RubberMat")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore.
Intellij 2018.3:
hard wrap
- idea will automatically wrap the line as you type, this is not what the OP was asking for
visual guide
- just a vertical line indicating a characters limit, default is 120
If you just want to change the visual guide
from the default 120
to lets say 80
in my example:
Also you can change the color or the visual guide
by clicking on the Foreground
:
Lastly, you can also set the visual guide
for all file types (unless specified) here:
I usually do:
import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0) # To print now without microsecond.
# To print now:
print(now)
output:
2019-01-13 14:40:28
SQL Server / MS Access Syntax:
SELECT TOP 1 * FROM table_name ORDER BY RAND()
MySQL Syntax:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1
Since Spring Boot v2+
I have verified with Spring Boot v2.3.5.RELEASE
With Spring Boot Maven Plugin
You can provide commandline argument like this:
mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"
You can provide JVM argument like this:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=dev"
java -jar
java -Dspring.profiles.active=dev -jar app.jar
(Note order)
or
java -jar app.jar --spring.profiles.active=dev
(Note order)
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
You need to declare y and c outside the scope of the if/else statement. A variable is only valid inside the scope it is declared (and a scope is marked with { })
#include <iostream>
using namespace std;
//Using the Gaussian algorithm
int dayofweek(int date, int month, int year ){
int d=date;
int y, c;
if (month==1||month==2)
{y=((year-1)%100);c=(year-1)/100;}
else
{y=year%100;c=year/100;}
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}
int main(){
cout<<dayofweek(19,1,2054);
return 0;
}
hashCode()
method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable
, HashMap
like data structure. By default, Object’s hashCode()
method returns and integer representation of memory address where object is stored.
The hashCode()
method of objects is used when we insert them into a HashTable
, HashMap
or HashSet
. More about HashTables
on Wikipedia.org for reference.
To insert any entry in map data structure, we need both key and value. If both key and values are user define data types, the hashCode()
of the key will be determine where to store the object internally. When require to lookup the object from the map also, the hash code of the key will be determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The HashTable
then iterates this area (all keys with the same hash code) and uses the key's equals()
method to find the right key. Once the right key is found, the object stored for that key is returned.
So, as we can see, a combination of the hashCode()
and equals()
methods are used when storing and when looking up objects in a HashTable
.
NOTES:
Always use same attributes of an object to generate hashCode()
and equals()
both. As in our case, we have used employee id.
equals()
must be consistent (if the objects are not modified, then it must keep returning the same value).
Whenever a.equals(b)
, then a.hashCode()
must be same as b.hashCode()
.
If you override one, then you should override the other.
http://parameshk.blogspot.in/2014/10/examples-of-comparable-comporator.html
I just took a sampling of screen resolutions from all of the client sites I have access to, this includes more then 20 sites in more then 8 industries here are the results:
alt text http://unkwndesign.com/so/percentScreenResolutions.png
Based on this I would say makes sure it looks good on 1024x768 as that is the majority here by a long shot. Also don't worry about the height as much, however try to avoid making most pages more then 1-2 printed pages at your default font size, most people wont read a page that long, and if a user installs a toolbar that takes up vertical space, my personal preference is that it's their problem, but I don't think it's to big of a deal.
*note the percentage adds up to 100.05% because of rounding.
Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).
Just use one of the GUI-based tools that support index management, for example:
git gui
<-- uses the Tk windowing framework -- similar style to gitk
git cola
<-- a more modern-style GUI interfaceThese let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.
How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:
git rm --cached [file]
git reset HEAD <file>
...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.
Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:
git commit -a
git commit (list of files)
git commit -a
then amend via git gui
git difftool --dir-diff --tool=meld
Unfortunately, the most popular answer did not work for me entirely. I had to add .select_option
to end of the statement
select("option_name_here", from: "organizationSelect").select_option
without the select_option
, no select was being performed
Why not just use this?
var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = Screen.FromHandle(interopHelper.Handle);
You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.
I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.
If you want to do it with multiline/multiple command/s then you can do this:
output=$( bash <<EOF
#multiline/multiple command/s
EOF
)
Or:
output=$(
#multiline/multiple command/s
)
Example:
#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"
Output:
first
second
third
As James mentioned above, the best way is to look at the header where the type is defined.
You can find the definition of pthread_t in pthreadtypes.h which can be found at:
/usr/include/bits/pthreadtypes.h
You can also do this globally via a rcParams dictionary:
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
This typically is caused by the mount directory being left mounted due to a crash of your filesystem. Go to the parent directory of the mount point and enter fusermount -u YOUR_MNT_DIR
.
If this doesn't do the trick, do sudo umount -l YOUR_MNT_DIR
.
Go to your GitHub account dashboard, find your project repository, click Settings tab - under Deploy keys you'll have to add your SSH key. Open Terminal and type:
cat ~/.ssh/id_rsa.pub | pbcopy
This will copy the key from your id_rsa.pub file. So just go back to GitHub dashboard, paste it, click Add Key and that's it.
The same solution applies to Bitbucket accounts.
Use pyplot.text()
(import matplotlib.pyplot as plt
)
import matplotlib.pyplot as plt
x=[1,2,3]
y=[9,8,7]
plt.plot(x,y)
for a,b in zip(x, y):
plt.text(a, b, str(b))
plt.show()
$("#myid li").click(function() {
alert(this.id); // id of clicked li by directly accessing DOMElement property
alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
alert($(this).html()); // gets innerHTML of clicked li
alert($(this).text()); // gets text contents of clicked li
});
If you are talking about replacing the ID with something:
$("#myid li").click(function() {
this.id = 'newId';
// longer method using .attr()
$(this).attr('id', 'newId');
});
Demo here. And to be fair, you should have first tried reading the documentation:
For outputing String
as text/plain
use:
@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
return "bar";
}
You can also use redirect()
method like this:-
return redirect('https://stackoverflow.com/');
Another way to look at this is to simply use another field.
paths:
root_path: &root
val: /path/to/root/
patha: &a
root_path: *root
rel_path: a
pathb: &b
root_path: *root
rel_path: b
pathc: &c
root_path: *root
rel_path: c