I too advise to use the simple way (KISS !-)
-- but some optimization could be found, namely not to test the length of an array more than once:
var elements = document.getElementsByTagName('div');
for (var i=0, im=elements.length; im>i; i++) {
doSomething(elements[i]);
}
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
There are a few characters which can indicate a new line. The usual ones are these two: '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF). '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).
Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:
DOS and Windows
They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).
Unix (and hence Linux as well)
Unix uses a single '\n' to indicate a new line.
Mac
Macs use a single '\r'.
Try replacing your meta tag with this below:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />
Or in addition to what you have, you should add http://*
to both style-src
and script-src
as seen above added after 'self'.
If your server is including the Content-Security-Policy
header, the header will override the meta.
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
There are many options:
rspec spec # All specs
rspec spec/models # All specs in the models directory
rspec spec/models/a_model_spec.rb # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test" # Runs specs that match the text
rspec spec --tag focus # Runs specs that have :focus => true
rspec spec --tag focus:special # Run specs that have :focus => special
rspec spec --tag focus ~skip # Run tests except those with :focus => true
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'd020915'))
BEGIN
declare @result int
set @result=1
select @result as result
END
you can still use
String Item = getIntent().getExtras().getString("name");
in the fragment
, you just need call getActivity()
first:
String Item = getActivity().getIntent().getExtras().getString("name");
This saves you having to write some code.
In 2017, the thing closest to Javadoc would probably DocFx which was developed by Microsoft and comes as a Commmand-Line-Tool as well as a VS2017 plugin.
It's still a little rough around the edges but it looks promising.
Another alternative would be Wyam which has a documentation recipe suitable for net aplications. Look at the cake documentation for an example.
I had the similar issue. its resolved for me with a simple command.
lsnrctl start
The Network Adapter exception is caused because:
lsnrctl
utility.Try to start the listener using the command prompt:
cmd
in the search field, and when cmd
shows up in the list of options, right click it and select ‘Run as Administrator’.lsnrctl start
without the quotes and press Enter.Exit
and press Enter.Hope it helps.
This could be a problem with IPV6 address SOAP UI picking. Adding the following JVM option fixed it for me:
-Djava.net.preferIPv4Stack=true
I added it here:
C:\Program Files\SmartBear\soapUI-4.5.2\bin\soapUI-4.5.2.vmoptions
New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()
Here is a code snippet which demonstrates the List.sort() feature:
List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));
// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]
// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]
The Fruit class is:
public class Fruit implements Comparable<Fruit>
{
private String name;
private String color;
private int quantity;
public Fruit(String name,String color,int quantity)
{ this.name = name; this.color = color; this.quantity = quantity; }
public String getFruitName() { return name; }
public String getColor() { return color; }
public int getQuantity() { return quantity; }
@Override public final int compareTo(Fruit f) // sorting the color
{
return this.color.compareTo(f.color);
}
@Override public String toString()
{
return (name + " is: " + color);
}
} // end of Fruit class
Since the release of iOS 8, UIAlertView
is now deprecated; UIAlertController is the replacement.
Here is a sample of how it looks in Swift:
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!
Updated for Swift 4.2
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
Update for React Router 5.1+.
import React from 'react';
import { useLocation, Switch } from 'react-router-dom';
const App = () => {
const location = useLocation();
React.useEffect(() => {
console.log('Location changed');
}, [location]);
return (
<Switch>
{/* Routes go here */}
</Switch>
);
};
This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).
sun.reflect.Reflection
/** Returns the class of the method <code>realFramesToSkip</code>
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
<code>getCallerClass(0)</code> returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
public static native Class getCallerClass(int realFramesToSkip);
As far as what the realFramesToSkip
value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System
, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3)
, but in my helper utility class I used 4 since there is the added frame of the helper class invocation.
If you want to use it as a date instead of a varchar
again afterwards, don't forget to convert it back:
select convert(datetime,CONVERT(char(10), GetDate(),126))
As explained here, The “Iterable” was introduced to be able to use in the foreach
loop. A class implementing the Iterable interface can be iterated over.
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href
.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
In my case I needed to create a new folder in the www
directory called scripts
. Within scripts
I added a new file called test.py
.
I then used sudo chown www-data:root scripts
and sudo chown www-data:root test.py
.
Then I went to the new scripts
directory and used sudo chmod +x test.py
.
My test.py file it looks like this. Note the different Python version:
#!/usr/bin/env python3.5
print("Hello World!")
From php I now do this:
$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);
And you should see: Hello World!
This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:
---------------------------------
| EXTENSION | DOCTYPE |
---------------------------------
| .doc | Document |
| .docx | Document |
| .pdf | Document |
| ... | ... |
| .bmp | Image |
| .jpg | Image |
| ... | ... |
---------------------------------
Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:
private static string GetUploadFilter()
{
// Desired format:
// "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
// "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"
string filter = String.Empty;
string nameFilter = String.Empty;
string extFilter = String.Empty;
// Used to get extensions
DataTable dt = new DataTable();
dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");
// Used to cycle through doctype groupings ("Images", "Documents", etc.)
DataTable dtDocTypes = new DataTable();
dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");
// For each doctype grouping...
foreach (DataRow drDocType in dtDocTypes.Rows)
{
nameFilter = drDocType["DOCTYPE"].ToString() + " files (";
// ... add its associated extensions
foreach (DataRow dr in dt.Rows)
{
if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
{
nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
extFilter += "*" + dr["EXTENSION"].ToString() + ";";
}
}
// Remove endings put in place in case there was another to add, and end them with pipe characters:
nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
nameFilter += ")|";
extFilter = extFilter.TrimEnd(';');
extFilter += "|";
// Add the name and its extensions to our main filter
filter += nameFilter + extFilter;
extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
}
filter = filter.TrimEnd('|');
return filter;
}
private void UploadFile(string fileType, object sender)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string filter = GetUploadFilter();
dlg.Filter = filter;
if (dlg.ShowDialog().Value == true)
{
string fileName = dlg.FileName;
System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
byte[] array = new byte[fs.Length];
// This will give you just the filename
fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
...
Should yield a filter that looks like this:
angular 5 :
getImage(id: string): Observable<Blob> {
return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}
The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event
.
Use the rect
attribute of the pygame.sprite.Sprite
object and the collidepoint
method to see if the Sprite was clicked.
Pass the list of events to the update
method of the pygame.sprite.Group
so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos()
. The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed()
returns a list of Boolean values ??that represent the state (True
or False
) of all mouse buttons. The state of a button is True
as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True
. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update
method of the pygame.sprite.Sprite
object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
I was getting the same error in python 3.4.3 too and I tried using the solutions mentioned here and elsewhere with no success.
Microsoft makes a compiler available for Python 2.7 but it didn't do me much good since I am on 3.4.3.
Python since 3.3 has transitioned over to 2010 and you can download and install Visual C++ 2010 Express for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express
Here is the official blog post talking about the transition to 2010 for 3.3: http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html
Because previous versions gave a different error for vcvarsall.bat I would double check the version you are using with "pip -V"
C:\Users\B>pip -V
pip 6.0.8 from C:\Python34\lib\site-packages (python 3.4)
As a side note, I too tried using the latest version of VC++ (2013) first but it required installing 2010 express.
From that point forward it should work for anyone using the 32 bit version, if you are on the 64 bit version you will then get the ValueError: ['path'] message because VC++ 2010 doesn't have a 64 bit compuler. For that you have to get the Microsoft SDK 7.1. I can't hyperlink the instruction for 64 bit because I am limited to 2 links per post but its at
Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
why not simply:
./aaa.sh 2>&1 | tee -a log
This simply redirects stderr
to stdout
, so tee echoes both to log and to screen. Maybe I'm missing something, because some of the other solutions seem really complicated.
Note: Since bash version 4 you may use |&
as an abbreviation for 2>&1 |
:
./aaa.sh |& tee -a log
You can try as below :
declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'
while( @i < LEN(@list))
begin
declare @item varchar(MAX)
SELECT @item = SUBSTRING(@list, @i,CHARINDEX(',',@list,@i)-@i)
select @item
--do your stuff here with @item
exec p_MyInnerProcedure @item
set @i = CHARINDEX(',',@list,@i)+1
if(@i = 0) set @i = LEN(@list)
end
You could use location.go(url)
which will basically change your url, without change in route of application.
NOTE this could cause other effect like redirect to child route from the current route.
Related question which describes location.go
will not intimate to Router
to happen changes.
Just as a follow up to comments on the efficiency of exponentiation by squaring.
The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.
Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.
Edit:
I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.
Do you have access to your database, if so just open it up and look up the column and use an SQL call to retrieve the needed.
A short example on a form to retrieve data from a database table:
Form contain only a GataGridView named DataGrid
Database name: DB.mdf
Table name: DBtable
Column names in table: Name as varchar(50), Age as int, Gender as bit.
Private Sub DatabaseTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Public ConString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\{username}\documents\visual studio 2010\Projects\Userapplication prototype v1.0\Userapplication prototype v1.0\Database\DB.mdf;" & "Integrated Security=True;User Instance=True"
Dim conn As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Dim da As New SqlClient.SqlDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New SqlClient.SqlConnection(ConString)
conn.Open() 'connects to the database
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT * FROM DBtable" 'Sql to be executed
cmd.CommandText = sSQL 'makes the string a command
da.SelectCommand = cmd 'puts the command into the sqlDataAdapter
da.Fill(dt) 'populates the dataTable by performing the command above
Me.DataGrid.DataSource = dt 'Updates the grid using the populated dataTable
'the following is only if any errors happen:
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close() 'closes the connection again so it can be accessed by other users or programs
End Try
End Sub
This will fetch all the rows and columns from your database table for review.
If you want to only fetch the names just change the sql call with: "SELECT Name FROM DBtable" this way the DataGridView will only show the column names.
I'm only a rookie but i would strongly advise to get rid of theses auto generate wizards. Using SQL you have full access to your database and what happens.
Also one last thing, if your database doesn't use SQLClient just change it to OleDB.
Example: "Dim conn As New SqlClient.SqlConnection
" becomes: Dim conn As New OleDb.OleDbConnection
Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;
MySQL – Temporarily disable Foreign Key Checks or Constraints
You can use Func<T, TResult>
generic delegate. (See MSDN)
Func<MyType, ReturnType> func = (db) => { return new MyType(); }
Also there are useful generic delegates which considers a return value:
Method:
public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)
Generic delegate:
Func<InputArgumentType, MyType> createInstance = db => return new MyType();
Execute:
MyType myTypeInstance = SimpleUsing.DoUsing(
createInstance(new InputArgumentType()));
OR explicitly:
MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
Assume that you have an array of classes to being added, you can use ES6 spread syntax:
let classes = ['first', 'second', 'third'];
elem.classList.add(...classes);
Put the identity
element before the authentication
element
If you are binding to an actual enum property on your ViewModel, not a int representation of an enum, things get tricky. I found it is necessary to bind to the string representation, NOT the int value as is expected in all of the above examples.
You can tell if this is the case by binding a simple textbox to the property you want to bind to on your ViewModel. If it shows text, bind to the string. If it shows a number, bind to the value. Note I have used Display twice which would normally be an error, but it's the only way it works.
<ComboBox SelectedValue="{Binding ElementMap.EdiDataType, Mode=TwoWay}"
DisplayMemberPath="Display"
SelectedValuePath="Display"
ItemsSource="{Binding Source={core:EnumToItemsSource {x:Type edi:EdiDataType}}}" />
Greg
You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.
function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});
Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.
The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.
When dealing with infinity and greater-than >
or less-than <
operators, the following counts:
+inf
is higher than -inf
-inf
is lower than +inf
+inf
is neither higher nor lower than +inf
-inf
is neither higher nor lower than -inf
NaN
is false (inf
is neither higher, nor lower than NaN
)When compared for equality, +inf
and +inf
are equal, as are -inf
and -inf
. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.
Of course, +inf
is unequal to -inf
and everything, including NaN
itself, is unequal to NaN
.
Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:
NaN
0.0
or -0.0
².NaN
.inf - inf
, the result is undefined: NaN
;inf - -inf
, the result is inf
;-inf - inf
, the result is -inf
;-inf - -inf
, the result is undefined: NaN
.inf + inf
, the result is inf
;inf + -inf
, the result is undefined: NaN
;-inf + inf
, the result is undefined: NaN
;-inf + -inf
, the result is -inf
.math.pow
, pow
or **
is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf
or -inf
, it behaves correctly and returns either inf
or 0.0
. When the second argument is NaN
, it returns NaN
, unless the first argument is 1.0
. There are more issues, not all covered in the docs.math.exp
suffers the same issues as math.pow
. A solution to fix this for overflow is to use code similar to this:
try:
res = math.exp(420000)
except OverflowError:
res = float('inf')
Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0
yields inf
.
Note 2: because any calculation with NaN
returns NaN
and any comparison to NaN
, including NaN
itself is false
, you should use the math.isnan
function to determine if a number is indeed NaN
.
Note 3: though Python supports writing float('-NaN')
, the sign is ignored, because there exists no sign on NaN
internally. If you divide -inf / +inf
, the result is NaN
, not -NaN
(there is no such thing).
Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.
¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf')
keeps its sign and -1 / float('inf')
yields -0.0
, 1 / float(-inf)
yields -0.0
, 1 / float('inf')
yields 0.0
and -1/ float(-inf)
yields 0.0
. In addition, 0.0 == -0.0
is true
, you have to manually check the sign if you don't want it to be true.
With the assumption that there's only one element:
$("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()
...are all equivalent, returning the single underlying element.
From the jQuery source code, you can see that get(0)
, under the covers, essentially does the same thing as the [0]
approach:
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
print df.sort_index(by='Frequency',ascending=False)
where by is the name of the column,if you want to sort the dataset based on column
Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.
Thread myThread= new Thread(nameOfFunction);
workerThread.Start();
Calling the start function on the thread object will cause the execution of your function call in a new thread.
With Java 7 you can use
if (Objects.equals(foo, null)) {
...
}
which will return true
if both parameters are null
.
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
If you want to redirect the error output as well, you have to do:
$cmdOutput = command 2>&1
Or, if the program name has spaces in it:
$cmdOutput = & "command with spaces" 2>&1
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
For Ubuntu 18.04 I just edited the file /usr/share/phpmyadmin/libraries/config.default.php
Change:
$cfg['LoginCookieValidity'] = 1440
int sum=0;
for(int i:A)
sum+=i;
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
Ok, here is a safe way of doing it.
with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('\n')
This writes 1 to 10 each number on a new line.
<div>©<script>document.write(new Date().getFullYear());</script>, Company._x000D_
</div>
_x000D_
you can simply write:
for item,i in zip(your_list, range(len(your_list)):
if type(item) == list:
print(f"{item} at index {i} is a list")
As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}
From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.
This along with @BlackHawkDesign comment should help you find what you need.
I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00
its very simple
just write:
//first create table named test....
create table test (name varchar2(10),age number(5));
//when you run the above code a table will be created....
//now we have to insert a name & an age..
Make sure age will be inserted via opening a form that seeks our help to enter the value in it
insert into test values('Deepak', :age);
//now run the above code and you'll get "1 row inserted" output...
/now run the select query to see the output
select * from test;
//that's all ..Now i think no one has any queries left over accepting a user data...
If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)
You might want to look at setting up a jail.
ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();
Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?
Try:
$("#mylist li").length
Just curious: why do you need to know the size? Can't you just use:
$("#mylist").append("<li>New list item</li>");
?
string[] str = new string[]{"1","2"};
string[] str = new string[4];
If you are using Java8 or + version, JDBC and MySql8 and facing this issue then try this:
Add parameter to connection string:
jdbc:mysql://localhost:3306/tempDB?allowLoadLocalInfile=true
Also, set
local_infile = 1
in my.cnf file.
The latest version of mysql-java-connector might be wont allow directly to connect to local file. So with this parameter, you can able to enable it. This works for me.
I could suggest just install Terminal-ide on you device which available in play market. Its free, does not require root and provide convenient *nix environment like cp, find, du, mc and many other utilities which installed in binary form by one button tap.
This function works for MM:SS as well:
const convertTime = (hms) => {_x000D_
if (hms.length <3){_x000D_
return hms_x000D_
} else if (hms.length <6){_x000D_
const a = hms.split(':')_x000D_
return hms = (+a[0]) * 60 + (+a[1])_x000D_
} else {_x000D_
const a = hms.split(':')_x000D_
return hms = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])_x000D_
}_x000D_
}
_x000D_
If you meant just ABC as simple value, answer above is the one that works fine.
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
Something like this may work:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though
Two ways to position a tag in the middle of screen or its parent tag:
Set the parent tag position
to relative
(if the target tag has a parent tag) and then set the target tag style like this:
#center {
...
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
The parent tag style should looks like this:
#parent-tag {
display: flex;
align-items: center;
justify-content: center;
}
This solution has left aligned text and button on the far right.
If anyone is looking for a material design answer:
<div layout="column" layout-align="start start">
<div layout="row" style="width:100%">
<div flex="grow">Left Aligned text</div>
<md-button aria-label="help" ng-click="showHelpDialog()">
<md-icon md-svg-icon="help"></md-icon>
</md-button>
</div>
</div>
Try this approach if you have symbols and you want just numbers:
String s = "@##9823l;Azad9927##$)(^738#";
System.out.println(s=s.replaceAll("[^0-9]", ""));
StringTokenizer tok = new StringTokenizer(s,"`~!@#$%^&*()-_+=\\.,><?");
String s1 = "";
while(tok.hasMoreTokens()){
s1+= tok.nextToken();
}
System.out.println(s1);
MsgBox("Variable {0} " , variable)
You can just do:
git rev-parse HEAD
To explain a bit further: git rev-parse
is git's basic command for interpreting any of the exotic ways that you can specify the name of a commit and HEAD
is a reference to your current commit or branch. (In a git bisect
session, it points directly to a commit ("detached HEAD") rather than a branch.)
Alternatively (and easier to remember) would be to just do:
git show
... which defaults to showing the commit that HEAD
points to. For a more concise version, you can do:
$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation
Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.
Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA
Example
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://stackoverflow.com";
char outfilename[FILENAME_MAX] = "page.html";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
i'm impressed of the deep discussion.
my 2 cents:
from datetime import datetime import time
the timestamp in utc is:
timestamp = \
(datetime.utcnow() - datetime(1970,1,1)).total_seconds()
or,
timestamp = time.time()
if now results from datetime.now(), in the same DST
utcoffset = (datetime.now() - datetime.utcnow()).total_seconds()
timestamp = \
(now - datetime(1970,1,1)).total_seconds() - utcoffset
I had the same issue after an upgrade from VS2013 to VS2015.
The project I was working at referenced itself. While VS2013 didn't care, VS2015 didn't like that and I got that error. After deleting the reference, the error was gone. It took me around 4 hours to find that out...
You should use the flex
or flex-basis
property rather than width
. Read more on MDN.
.flexbox .red {
flex: 0 0 25em;
}
The flex
CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:
flex-grow: 0; /* do not grow - initial value: 0 */
flex-shrink: 0; /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height - initial value: auto */
A simple demo shows how to set the first column to 50px
fixed width.
.flexbox {_x000D_
display: flex;_x000D_
}_x000D_
.red {_x000D_
background: red;_x000D_
flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
background: green;_x000D_
flex: 1;_x000D_
}_x000D_
.blue {_x000D_
background: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
<div class="red">1</div>_x000D_
<div class="green">2</div>_x000D_
<div class="blue">3</div>_x000D_
</div>
_x000D_
See the updated codepen based on your code.
white-space: pre-wrap
You get your browser's language for your button. There's no way to change it programmatically.
AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:
def book_author(self):
return self.book.author
Then the admin part works nicely.
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
It was suggested to use numpy's bincount, however it works only for 1d arrays with non-negative integers. Also, the resulting array might be confusing (it contains the occurrences of the integers from min to max of the original list, and sets to 0 the missing integers).
A better way to do it with numpy is to use the unique function with the attribute return_counts
set to True. It returns a tuple with an array of the unique values and an array of the occurrences of each unique value.
# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True) # array([0, 1, 2, 3]), array([2, 3, 1, 2]
and then we can pair them as
dict(zip(a_uniq, counts)) # {0: 2, 1: 3, 2: 1, 3: 2}
It also works with other data types and "2d lists", e.g.
>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}
xampp in ubuntu
cd /opt/lampp/etc
vim php.ini
Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M
Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
sudo /opt/lampp/lampp restart
This page is a neat summary, but is not entirely accurate:
I would avoid using a relative path. Remember that docker is a daemon/client relationship.
When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database
is then relative to the daemon, not the client.
Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.
In short, don't use a relative path, use an absolute path.
Here is a nice solution using the Gooogle Maps API itself. No external service, no extra library. And it enables custom shapes and multiple colors and styles. The solution uses vectorial markers, which googlemaps api calls Symbols.
Besides the few and limited predefined symbols, you can craft any shape of any color by specifying an SVG path string (Spec).
To use it, instead of setting the 'icon' marker option to the image url, you set it to a dictionary containing the symbol options. As example, I managed to craft one symbol that is quite similar to the standard marker:
function pinSymbol(color) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
};
}
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
icon: pinSymbol("#FFF"),
});
I you are careful to keep the shape key point at 0,0 you avoid having to define marker icon centering parameters. Another path example, the same marker without the dot:
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
And here you have a very simple and ugly coloured flag:
path: 'M 0,0 -1,-2 V -43 H 1 V -2 z M 1,-40 H 30 V -20 H 1 z',
You can also create the paths using a visual tool like Inkscape (GNU-GPL, multiplatform). Some useful hints:
Although building the URL or using tools is still possible, it is not needed anymore.
https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.
(at the bottom of the right column).
Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)
You are lucky that you didn't complete the rebase, so you can still do git rebase --abort
. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.
The best solution, you can manage the multiple node versions using nvm installer. then, install the required node's version using below command
nvm install version
Use below command as a working node with mentioned version alone
nvm use version
now, you can use any version node without uninstalling previous installed node.
With small modifications to your code, you can achieve it in a more generic way.
final Handler responseHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
//txtView.setText((String) msg.obj);
Toast.makeText(MainActivity.this,
"Result from UIHandlerThread:"+(int)msg.obj,
Toast.LENGTH_LONG)
.show();
}
};
HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
public void run(){
Integer a = 2;
Message msg = new Message();
msg.obj = a;
responseHandler.sendMessage(msg);
System.out.println(a);
}
};
handlerThread.start();
Solution :
Handler
in UI Thread,which is called as responseHandler
Handler
from Looper
of UI Thread. HandlerThread
, post message on this responseHandler
handleMessgae
shows a Toast
with value received from message. This Message object is generic and you can send different type of attributes.With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable
objects on this HandlerThread
and each Runnable
can set value in Message
object, which can be received by UI Thread.
$("#formid").ajaxForm({ success: function(){ //to do after submit } });
Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction()
you do whatever you want, (with AJAX or not) and in the ending, you add return false;
to tell the browser not to submit the form...
Credit to Sandeep Jindal and Premraj. Their explanation help me to understand after confused about this for a while.
I created some full code examples & some simple explanations here https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/ . I think it may help others to understand.
In short from the link, You should not try to understand all three at once, first you should understand the relationship in these groups:
1. Life Cycle vs Phase
Life Cycle is a collection of phase in sequence see here Life Cycle References. When you call a phase, it will also call all phase before it.
For example, the clean life cycle has 3 phases (pre-clean, clean, post-clean).
mvn clean
It will call pre-clean and clean.
2. Plugin vs Goal
Goal is like an action in Plugin. So if plugin is a class, goal is a method.
you can call a goal like this:
mvn clean:clean
This means "call the clean goal, in the clean plugin" (Nothing relates to the clean phase here. Don't let the word"clean" confusing you, they are not the same!)
3. Now the relation between Phase & Goal:
Phase can (pre)links to Goal(s).For example, normally, the clean phase links to the clean goal. So, when you call this command:
mvn clean
It will call the pre-clean phase and the clean phase which links to the clean:clean goal.
It is almost the same as:
mvn pre-clean clean:clean
More detail and full examples are in https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/
set meta tag in head as
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
use the link http://www.i18nqa.com/debug/utf8-debug.html to replace the symbols character you want.
then use str_replace like
$find = array('“', '’', '…', '—', '–', '‘', 'é', 'Â', '•', 'Ëœ', 'â€'); // en dash
$replace = array('“', '’', '…', '—', '–', '‘', 'é', '', '•', '˜', '”');
$content = str_replace($find, $replace, $content);
Its the method i use and help alot. Thanks!
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
<a href="#" id="refreshItem">Refresh</a>
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
Using CONCAT(CONCAT(,),)
worked for me when concatenating more than two strings.
My problem required working with date strings (only) and creating YYYYMMDD
from YYYY-MM-DD
as follows (i.e. without converting to date format):
CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD
I just solved this issue on HackerRank, so I'm here to share my result
function timeConversion(s) {
const isPM = s.indexOf('PM') !== -1;
let [hours, minutes, seconds] = s.replace(isPM ? 'PM':'AM', '').split(':');
if (isPM) {
hours = parseInt(hours, 10) + 12;
hours = hours === 24 ? 12 : hours;
} else {
hours = parseInt(hours, 10);
hours = hours === 12 ? 0 : hours;
if (String(hours).length === 1) hours = '0' + hours;
}
const time = [hours, minutes, seconds].join(':');
return time;
}
This works for inputs like 06:40:03AM
.
Another example is available here:
Sending a JSON to server and retrieving a JSON in return, without JQuery
Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.
Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
this portion to
CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT
and change the following line too.
DECLARE NAME_FOUND TEXT DEFAULT "";
It should work.
<a href="javascript:call_func();">...</a>
where the function then has to return false so that the browser doesn't go to another page.
But I'd recommend to use jQuery (with $(...).click(function () {}))
)
One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color
, the correct way is:
ng-style="{backgroundColor:myColor}"
Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value. If you don't provide a default value, None
is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist
On RHEL 6 this worked for me also:
umount -f -a -t cifs -l FOLDER_NAME
Here's quite a good example of how you can get caught out from not declaring local variables with var
:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i
is reset at every iteration of the loop, as it's not declared locally in the for
loop but globally) eventually resulting in infinite loop
You can just sum
and set param axis=1
to sum the rows, this will ignore none numeric columns:
In [91]:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
a b c d e
0 1 2 dd 5 8
1 2 3 ee 9 14
2 3 4 ff 1 8
If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:
In [98]:
col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:
df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
a b c d e
0 1 2 dd 5 3
1 2 3 ee 9 5
2 3 4 ff 1 7
The previous answer is correct but I'll give you all the code as well.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
</configSections>
<ServicesSection>
<Services>
<add Port="6996" ReportType="File" />
<add Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
Your ServiceConfig
and ServiceCollection
classes remain unchanged.
You need a new class:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}
And that should do the trick. To consume it you can use:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];
executable path
to find the address to gdb32.exe
CodeBlock -> MinGW -> bin -> gdb32.exe (locate it and double click on it)
If value
is a string
in that format and you'd like to convert it into a DateTime
object, you can use DateTime.ParseExact
static method:
DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);
Example:
string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(myDate.ToShortDateString());
Result:
2012-12-01
This don't need to day of week comments.
I recommend this code~!
import datetime
DAY_OF_WEEK = {
"MONDAY": 0,
"TUESDAY": 1,
"WEDNESDAY": 2,
"THURSDAY": 2,
"FRIDAY": 2,
"SATURDAY": 2,
"SUNDAY": 6
}
def string_to_date(dt, format='%Y%m%d'):
return datetime.datetime.strptime(dt, format)
def date_to_string(date, format='%Y%m%d'):
return datetime.datetime.strftime(date, format)
def day_of_week(dt):
return string_to_date(dt).weekday()
dt = '20210101'
if day_of_week(dt) == DAY_OF_WEEK['SUNDAY']:
None
ruby-dev
is installedmake
is installedgem install pg
you will also need to install the lib libpq-dev
(sudo apt-get install libpq-dev
).Ok, I will give a small example on how to do what you ask
public class ClassB extends Activity
{
ClassA A1 = new ClassA(this); // for activity context
ClassA A2 = new ClassA(getApplicationContext()); // for application context.
}
The find
method returns a Cursor
instance, which allows you to iterate over all matching documents.
To get the first document that matches the given criteria you need to use find_one
. The result of find_one
is a dictionary.
You can always use the list
constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.
You should do that if you need to reuse the cursor and have a good reason not to use rewind()
Demo using find
:
>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
... print(doc) # or do something with the document
...
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}
Demo using find_one
:
>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
CMake is more like a script language if comparing it with other ways to create Makefile (e.g. make or qmake). It is not very cool like Python, but still.
There are no such thing like a "proper way" if looking in various opensource projects how people include directories. But there are two ways to do it.
Crude include_directories will append a directory to the current project and all other descendant projects which you will append via a series of add_subdirectory commands. Sometimes people say that such approach is legacy.
A more elegant way is with target_include_directories. It allows to append a directory for a specific project/target without (maybe) unnecessary inheritance or clashing of various include directories. Also allow to perform even a subtle configuration and append one of the following markers for this command.
PRIVATE - use only for this specified build target
PUBLIC - use it for specified target and for targets which links with this project
INTERFACE -- use it only for targets which links with the current project
PS:
Both commands allow to mark a directory as SYSTEM to give a hint that it is not your business that specified directories will contain warnings.
A similar answer is with other pairs of commands target_compile_definitions/add_definitions, target_compile_options/CMAKE_C_FLAGS
Statically typed languages like C++, Java and Dynamically typed languages like Python differ only in terms of the execution of the type of the variable. Statically typed languages have static data type for the variable, here the data type is checked during compiling so debugging is much simpler...whereas Dynamically typed languages don't do the same, the data type is checked which executing the program and hence the debugging is bit difficult.
Moreover they have a very small difference and can be related with strongly typed and weakly typed languages. A strongly typed language doesn't allow you to use one type as another eg. C and C++ ...whereas weakly typed languages allow eg.python
In my view, With Expire Header, server can tell the client when my data would be stale, while with Etag, server would check the etag value for client' each request.
I finally implemented it this way
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].GetContentBounds(e.RowIndex).Contains(e.Location))
{
cellEndEditTimer.Start();
}
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{ /*place your code here*/}
private void cellEndEditTimer_Tick(object sender, EventArgs e)
{
dataGridView1.EndEdit();
cellEndEditTimer.Stop();
}
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
Apache doesn't support SSL on name-based virtual host, only on IP based Virtual Hosts.
Source: Apache 2.2 SSL FAQ question Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?
Unlike SSL, the TLS specification allows for name-based hosts (SNI as mentioned by someone else), but Apache doesn't yet support this feature. It supposedly will in a future release when compiled against openssl 0.9.8.
Also, mod_gnutls claims to support SNI, but I've never actually tried it.
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
Kindly try the below, Hope it will work for you.
SELECT TOP
( SELECT COUNT(foo)
From MyTable
WHERE ISNUMERIC (foo) = 1) *
FROM bar WITH(NOLOCK)
ORDER BY foo
WHERE CAST(foo AS int) > 100
)
Before answering, let's add some background, explaining what this HEAD
is.
First of all what is HEAD?
HEAD
is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD
at any given time (excluding git worktree
).
The content of HEAD
is stored inside .git/HEAD
and it contains the 40 bytes SHA-1 of the current commit.
detached HEAD
If you are not on the latest commit - meaning that HEAD
is pointing to a prior commit in history it's called detached HEAD
.
On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD
is not pointing to the tip of the current branch:
git checkout
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back
This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.
# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>
# Create a new branch forked to the given commit
git checkout -b <branch name>
git reflog
You can always use the reflog
as well.
git reflog
will display any change which updated the HEAD
and checking out the desired reflog entry will set the HEAD
back to this commit.
Every time the HEAD is modified there will be a new entry in the reflog
git reflog
git checkout HEAD@{...}
This will get you back to your desired commit
git reset --hard <commit_id>
"Move" your HEAD back to the desired commit.
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
git rebase --no-autostash
as well.git revert <sha-1>
"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.
# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>
This schema illustrates which command does what.
As you can see there, reset && checkout
modify the HEAD
.
this prints all the "printable" characters of your basic bash setup:
printf '%b\n' $(printf '\\%03o' {30..127})
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
You can change axis text and label size with arguments axis.text=
and axis.title=
in function theme()
. If you need, for example, change only x axis title size, then use axis.title.x=
.
g+theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"))
There is good examples about setting of different theme()
parameters in ggplot2 page.
This works good for me.
String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");
or you can use
String no_o = hi.replace("o", "");
You have your arguments to the remote add
command reversed:
git remote add <NAME> <PATH>
So:
git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git
See git remote --help
for more information.
I have used this query in our production code for nearly 10 years:
SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
Swift 4.1
use it when you delete row using selectedTag of row.
self.tableView.beginUpdates()
self.yourArray.remove(at: self.selectedTag)
print(self.allGroups)
let indexPath = NSIndexPath.init(row: self.selectedTag, section: 0)
self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)
self.tableView.endUpdates()
self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)
You can also do this with the ol' good method :
String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
translatedString += Integer.toBinaryString((int) stringArray[i]);
}
Store
lastFirstVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
Restore
((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition);
and if that doesn't work, try
((LinearLayoutManager) rv.getLayoutManager()).scrollToPositionWithOffset(lastFirstVisiblePosition,0)
Put store in onPause()
and restore in onResume()
Here is a generic function for it. Keep the RNG creation outside the high frequency code.
public static Random RNG = new Random();
public static T RandomEnum<T>()
{
Type type = typeof(T);
Array values = Enum.GetValues(type);
lock(RNG)
{
object value= values.GetValue(RNG.Next(values.Length));
return (T)Convert.ChangeType(value, type);
}
}
Usage example:
System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r
This way, everything is packager managed, so there's no need to manually download and install anything.
to answer to : int a = (b == 5) ? c : d;
just write:
b=5
c=1
d=2
let a="(b==5)?c:d"
echo $a # 1
b=6;
c=1;
d=2;
let a="(b==5)?c:d"
echo $a # 2
remember that " expression " is equivalent to $(( expression ))
In the first regex, each space character is being replaced, character by character, with the empty string.
In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +
.
However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.
If you change the replacement string to '#'
, the difference becomes much clearer:
var str = ' A B C D EF ';
console.log(str.replace(/\s/g, '#')); // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
<input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">
<div id="content"></div>
</body>
</html>
-----------------JS- code------------
var targetDiv = document.getElementById('content');
var htmlContent = '';
function populateData(event){
switch(event.target.value){
case 'A':{
htmlContent = 'Content for A';
break;
}
case 'B':{
htmlContent = "content for B";
break;
}
}
targetDiv.innerHTML = htmlContent;
}
Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);
Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.
Live Code
Its a little bit not sophisticated but this should work, for example lets say you want to cap your uilabel to 120x120, with max font size of 28:
magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
for (int i = 28; i>3; i--) {
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
if (size.height < 120) {
magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
break;
}
}
The following is of course all not quite precise. Take it with a grain of salt when you read it :)
Well, the three things you refer to are automatic, static and dynamic storage duration, which has something to do with how long objects live and when they begin life.
You use automatic storage duration for short lived and small data, that is needed only locally within some block:
if(some condition) {
int a[3]; // array a has automatic storage duration
fill_it(a);
print_it(a);
}
The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.
You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have namespace scope and local scope and class scope. What is true about both of them is, once their life begins, lifetime ends at the end of the program. Here are two examples:
// static storage duration. in global namespace scope
string globalA;
int main() {
foo();
foo();
}
void foo() {
// static storage duration. in local scope
static string localA;
localA += "ab"
cout << localA;
}
The program prints ababab
, because localA
is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime when control reaches their definition. For localA
, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at program startup. The same is true for static objects of class scope:
class A {
static string classScopeA;
};
string A::classScopeA;
A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;
As you see, classScopeA
is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term static initialization order fiasco.
The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are big, and if you want to create arrays of size only known at runtime. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate new operator invocation happens:
int main() {
// the object that s points to has dynamic storage
// duration
string *s = new string;
// pass a pointer pointing to the object around.
// the object itself isn't touched
foo(s);
delete s;
}
void foo(string *s) {
cout << s->size();
}
Its lifetime ends only when you call delete for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. Explicit garbage collection for particular objects can be established by using a smart pointer:
int main() {
shared_ptr<string> s(new string);
foo(s);
}
void foo(shared_ptr<string> s) {
cout << s->size();
}
You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So its lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared_ptr reference, see boost documents: http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm
Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.
While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#)
value appropriately if you have long strings in your versioning system.)
def versiontuple(v):
filled = []
for point in v.split("."):
filled.append(point.zfill(8))
return tuple(filled)
.
>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True
>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:
declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)
insert into @MonthsSale
select
1, 'January', 100.00
union select
2, 'February', 200.00
union select
3, 'March', 300.00
union select
4, 'April', 400.00
union select
5, 'May', 500.00
union select
6, 'June', 600.00
union select
7, 'July', 700.00
union select
8, 'August', 800.00
union select
9, 'September', 900.00
union select
10, 'October', 1000.00
union select
11, 'November', 1100.00
union select
12, 'December', 1200.00
select * from @MonthsSale
select SUM(MonthSale) as [TotalSales] from @MonthsSale
for counting:
$('.yourClass').length;
should work fine.
storing in a variable is as easy as:
var count = $('.yourClass').length;
Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.
The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.
The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.
The Android SDK directory is just the folder you get after uncompressing one of these files:
http://developer.android.com/sdk/index.html
There's no such "SDK installation"... may be, what you installed was the ADT plugin (which does not include the SDK). You have to download one of the ZIP files you find in the link above, uncompress it and boila! you have the SDK Folder.
ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:
SQL> grant dba to UserName; //Put This username which user show this error message.
Grant succeeded.
A SysOps guy once taught me the Three-Fingered Claw technique:
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try()
your statement and code on.
(based on flying sheep comment).
yell
: print the script name and all arguments to stderr
:
$0
is the path to the script ;$*
are all arguments. >&2
means >
redirect stdout to & pipe 2
. pipe 1
would be stdout
itself. die
does the same as yell
, but exits with a non-0 exit status, which means “fail”. try
uses the ||
(boolean OR
), which only evaluates the right side if the left one failed.
$@
is all arguments again, but different. In case if you are still stumbling over this question. Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:
def foo():
if bar:
print "bar"
print "baz" # ends the if and foo at the same time
The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.
Lines with no statement, no matter the indentation, does not matter
def foo():
print "The line below has no indentation"
print "Still part of foo"
But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:
def foo():
print "Still correct"
print "Error because there is no block at this indentation"
Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.
BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.
I would use "du" instead.
$ cat files.txt | xargs du -c | tail -1
4480 total
If you just want the number:
cat files.txt | xargs du -c | tail -1 | awk '{print $1}'
Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32
. This leads to a broken array with wrong dimensions and the above mentioned error.
To solve the problem, make sure that all images have the correct dimensions.
You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.
e.g.
filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines
and
filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines
If you are using Appcompact
Activity use these three lines in your theme.
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowActionBarOverlay">false</item>
you can try this indside findall for loop:
item_price = item.find('span', attrs={'class':'s-item__price'}).text
it extracts only text and assigs it to "item_pice"
Get and Set
Get
string getEnv = Environment.GetEnvironmentVariable("envVar");
Set
string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);
For the ones who need to get the all data record, you can add
returning *
to the end of your query to get the all object including the id.
I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.
If I try the first class I see:
BTW: It didn't show me a warning until I added { }
to the end of each class to fix the compile error.
if you have npm, install run the command
npm install -g @angular/cli
then bind your ng using this:
cd
alias ng=".npm-global/bin/ng"
Follow the Pictures for more help.
Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.
Here would be the service:
import {Injectable} from '@angular/core';
@Injectable()
export class SharedService {
dataArray: string[] = [];
insertData(data: string){
this.dataArray.unshift(data);
}
}
Now, here would be the PARENT component
import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
selector: 'parent-component',
template: `
<h1>Parent</h1>
<div>
<child-component></child-component>
<child-sibling-component></child-sibling-component>
</div>
`,
providers: [SharedService],
directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{
}
and its two children
child 1
import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'
@Component({
selector: 'child-component',
template: `
<h1>I am a child</h1>
<div>
<ul *ngFor="#data in data">
<li>{{data}}</li>
</ul>
</div>
`
})
export class ChildComponent implements OnInit{
data: string[] = [];
constructor(
private _sharedService: SharedService) { }
ngOnInit():any {
this.data = this._sharedService.dataArray;
}
}
child 2 (It's sibling)
import {Component} from 'angular2/core';
import {SharedService} from './shared.service'
@Component({
selector: 'child-sibling-component',
template: `
<h1>I am a child</h1>
<input type="text" [(ngModel)]="data"/>
<button (click)="addData()"></button>
`
})
export class ChildSiblingComponent{
data: string = 'Testing data';
constructor(
private _sharedService: SharedService){}
addData(){
this._sharedService.insertData(this.data);
this.data = '';
}
}
NOW: Things to take note of when using this method.
GNU find (see man find
) has a -printf
parameter for displaying the files in Epoch mtime and relative path name.
redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '{print $2}'
If you're running a WHM-powered VPS (virtual private server) you may find that you do not have permissions to edit PHP.INI directly; the system must do it. In the WHM host control panel, go to Service Configuration → PHP Configuration Editor and modify memory_limit
:
You can also change the pop-up options themselves, to be more convenient for your normal use. Summary:
Select SQL Server Object Explorer . Now you should be able to see the options
Give the Values 0 here to select/ Edit all the Records
Full Instructions with screenshots are here: http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html
I wanted to address something none of the answers have so far:
From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID. As an[sic] supplementary question, is a Generic list the best repository for these objects?
Assuming VehicleID
is unique as the name suggests, a list is a terribly inefficient way to store them when you get a lot of vehicles, as removal(and other methods like Find
) is still O(n). Have a look at a HashSet<Vehicle>
instead, it has O(1) removal(and other methods) using:
int GetHashCode(Vehicle vehicle){return vehicle.VehicleID;}
int Equals(Vehicle v1, Vehicle v2){return v1.VehicleID == v2.VehicleID;}
Removing all vehicles with a specific EnquiryID still requires iterating over all elements this way, so you could consider a GetHashCode
that returns the EnquiryID
instead, depending on which operation you do more often. This has the downside of a lot of collisions if a lot of Vehicles share the same EnquiryID though.
In this case, a better alternative is to make a Dictionary<int, List<Vehicle>>
that maps EnquiryIDs to Vehicles and keep that up to date when adding/removing vehicles. Removing these vehicles from a HashSet is then an O(m) operation, where m is the number of vehicles with a specific EnquiryID.
You just need to use below code when launching the new activity.
startActivity(new Intent(this, newactivity.class));
finish();
Go to http://rubyinstaller.org/downloads/
Make sure that you check "Add ruby ... to your PATH".
Now you can use "ruby" in your "cmd".
If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193
.
install Development Kit in rubyinstaller.
Make new folder such as C:\RubyDevKit
and unzip.
Go to the devkit directory and type ruby dk.rb init
to generate config.yml
.
If you installed devkit for 1.9.3, I expect that the config.yml
will be written as C:\Ruby193
.
If not, please correct path to your ruby folders.
After reviewing the config.yml
, you can finally type ruby dk.rb install
.
Now you can use "gem" in your "cmd". It's done!
if you want to force using BETWEEN keyword on Codeigniter query helper. You can use where without escape false like this code. Works well on CI version 3.1.5. Hope its help someone.
if(!empty($tglmin) && !empty($tglmax)){
$this->db->group_start();
$this->db->where('DATE(create_date) BETWEEN "'.$tglmin.'" AND "'.$tglmax.'"', '',false);
$this->db->group_end();
}
I have written a jquery plugin to solve this problem.. it's free..
JQuery Directory:
worked for me:
AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)
If you really want to get the type by name you may use the following:
System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");
Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.
If you need to have jquery use !important for more than one item, this is how you would do it.
e.g. set an img
tags max-width and max-height to 500px each
$('img').css('cssText', "max-width: 500px !important;' + "max-height: 500px !important;');
int indexOf()
can be used. It returns -1 if no matching finds
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
if i > 10:
break
Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:
$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/c++/5.4.0/",
"usr/local/include/",
"usr/include/"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++14",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
I like Imagemagick. http://www.imagemagick.org/script/api.php
C does not have strings per se -- what you have is a char pointer pointing to some read-only memory containing the characters "blablabla\0". In order to append a character there, you need a) writable memory and b) enough space for the string in its new form. The string literal "blablabla\0" has neither.
The solutions are:
1) Use malloc()
et al. to dynamically allocate memory. (Don't forget to free()
afterwards.)
2) Use a char array.
When working with strings, consider using strn*
variants of the str*
functions -- they will help you stay within memory bounds.
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
I had the same problem with Visual Studio 2015 and Resharper 9.2
"Resharper 9 keyboard shortcuts not working in Visual Studio 2015"
I had tried all possible resetting and applying keyboard schemes and found the answer from Yuri Fedoseev.
My Windows 10 language configuration only had Swedish in the language preferences "Control Panel\Clock, Language, and Region\Language"
The solution was to add English(I chose the US version) in the language list. And then go to Resharper > Options > Keyboard & Menus > Apply Scheme. (perhaps you do not even need to apply the scheme)
I have got the same error but I have resolved the issue in the following ways:
Very late to the party but I want to supply a more modern solution to any future developers looking at this question. It's based off of Toprak's answer but simplified to make it clearer as to what is happening.
<div>Result: <span id="result"></span></div>
<script>
var output = null;
// Define an asynchronous function which will not block where it is called.
async function test(){
// Create a promise with the await operator which instructs the async function to wait for the promise to complete.
await new Promise(function(resolve, reject){
// Execute the code that needs to be completed.
// In this case it is a timeout that takes 2 seconds before returning a result.
setTimeout(function(){
// Just call resolve() with the result wherever the code completes.
resolve("success output");
}, 2000);
// Just for reference, an 'error' has been included.
// It has a chance to occur before resolve() is called in this case, but normally it would only be used when your code fails.
setTimeout(function(){
// Use reject() if your code isn't successful.
reject("error output");
}, Math.random() * 4000);
})
.then(function(result){
// The result variable comes from the first argument of resolve().
output = result;
})
.catch(function(error){
// The error variable comes from the first argument of reject().
// Catch will also catch any unexpected errors that occur during execution.
// In this case, the output variable will be set to either of those results.
if (error) output = error;
});
// Set the content of the result span to output after the promise returns.
document.querySelector("#result").innerHTML = output;
}
// Execute the test async function.
test();
// Executes immediately after test is called.
document.querySelector("#result").innerHTML = "nothing yet";
</script>
Here's the code without comments for easy visual understanding.
var output = null;
async function test(){
await new Promise(function(resolve, reject){
setTimeout(function(){
resolve("success output");
}, 2000);
setTimeout(function(){
reject("error output");
}, Math.random() * 4000);
})
.then(function(result){
output = result;
})
.catch(function(error){
if (error) output = error;
});
document.querySelector("#result").innerHTML = output;
}
test();
document.querySelector("#result").innerHTML = "nothing yet";
On a final note, according to MDN, Promises are supported on all modern browsers with Internet Explorer being the only exception. This compatibility information is also supported by caniuse. However with Bootstrap 5 dropping support for Internet Explorer, and the new Edge based on webkit, it is unlikely to be an issue for most developers.
Despite there being loads of answers here, none of the suggestions for linking to the developers apps seem to work anymore.
When I last visited I was able to get it working using the format:
itms-apps://itunes.apple.com/developer/developer-name/id123456789
This no longer works, but removing the developer name does:
itms-apps://itunes.apple.com/developer/id123456789
@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.Task
and Task<T>
.So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
You can specify how to initialize members in the member initializer list:
BigMommaClass {
BigMommaClass(int, int);
private:
ThingOne thingOne;
ThingTwo thingTwo;
};
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}
I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img
, without "wrapping" it into the a
tag (so instead of the document.MyImage
, I used this.src
)
<img
onMouseOver="this.src='ico/view.hover.png';"
onMouseOut="this.src='ico/view.png';"
src="ico/view.png" alt="hover effect" />
It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.
Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES];
Scrolls the receiver until a row identified by index path is at a particular location on the screen.
And
scrollToNearestSelectedRowAtScrollPosition:animated:
Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.
If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.
class CallbackTest {
myCallback: Function;
}
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
1> Yes... There is pencil icon when we go to Personal==> <app name> ==>Resources
then click on Pencil Icon and drag to left side and Dynos will go down.
2> You can validate using Heroku cli
heroku logs --app {your-appname}
it worked for me.
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.getfullname = function () {
return `${this.firstname} ${this.lastname}`;
};
let that = this;
this.sayHi = function() {
console.log(`i am this , ${this.firstname}`);
console.log(`i am that , ${that.firstname}`);
};
}
let thisss = new Person('thatbetty', 'thatzhao');
let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
thisss.sayHi.call(thatt);
As the cause of the error is obvious, here's some information that should help you solve the problem:
See this MS article about Naming Files, Paths, and Namespaces
Here's a quote from the link:
Maximum Path Length Limitation In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
And a few workarounds (taken from the comments):
There are ways to solve the various problems. The basic idea of the solutions listed below is always the same: Reduce the path-length in order to have path-length + name-length < MAX_PATH
. You may:
//THIS IS WORKING CODE
Microsoft.Office.Interop.Excel.Range Range_Number,r2;
Range_Number = wsheet.UsedRange.Find("smth");
string f_number="";
r2 = wsheet.Cells;
int n_c = Range_Number.Column;
int n_r = Range_Number.Row;
var number = ((Range)r2[n_r + 1, n_c]).Value;
f_number = (string)number;
Execute in bash:
redis-cli KEYS "prefix:*" | xargs redis-cli DEL
UPDATE
Ok, i understood. What about this way: store current additional incremental prefix and add it to all your keys. For example:
You have values like this:
prefix_prefix_actuall = 2
prefix:2:1 = 4
prefix:2:2 = 10
When you need to purge data, you change prefix_actuall first (for example set prefix_prefix_actuall = 3), so your application will write new data to keys prefix:3:1 and prefix:3:2. Then you can safely take old values from prefix:2:1 and prefix:2:2 and purge old keys.
df_1.join(df_2)
df_1.merge(df_2)
on
parameter has different meaning in both casesdf_1.merge(df_2, on='column_1')
df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')
I would like just to add that if you want to use windows socket library you have to :
at the beginning : call WSAStartup()
at the end : call WSACleanup()
Regards;
Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.
Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.
well if you really need a curl equivalent you can try node-curl
npm install node-curl
you will probably need to add libcurl4-gnutls-dev
.
You mean something like this?
List<object> objects = new List<object>();
var strings = (from o in objects
select o.ToString()).ToList();
I don't if anybody else has a better option...
<% if (Model.VariableName == "" || Model.VariableName== null) { %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "",
new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"],
Model.VariableName, new{stlye=" "})%>
<% }>
If nothing helps and you are still getting this exception, review your equals()
methods - and don't include child collection in it. Especially if you have deep structure of embedded collections (e.g. A contains Bs, B contains Cs, etc.).
In example of Account -> Transactions
:
public class Account {
private Long id;
private String accountName;
private Set<Transaction> transactions;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Account))
return false;
Account other = (Account) obj;
return Objects.equals(this.id, other.id)
&& Objects.equals(this.accountName, other.accountName)
&& Objects.equals(this.transactions, other.transactions); // <--- REMOVE THIS!
}
}
In above example remove transactions from equals()
checks. This is because hibernate will imply that you are not trying to update old object, but you pass a new object to persist, whenever you change element on the child collection.
Of course this solutions will not fit all applications and you should carefully design what you want to include in the equals
and hashCode
methods.
From the documentation of InetAddress.getByName(String host)
:
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
So you can use it.