It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class MemberComment
{
[Key, Column(Order = 0)]
public int MemberID { get; set; }
[Key, Column(Order = 1)]
public int CommentID { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
If you now want to find all comments of members with LastName
= "Smith" for example you can write a query like this:
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
... or ...
var commentsOfMembers = context.MemberComments
.Where(mc => mc.Member.LastName == "Smith")
.Select(mc => mc.Comment)
.ToList();
Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
If you want to find all comments of a member with MemberId
= 1:
var commentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1)
.Select(mc => mc.Comment)
.ToList();
Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something
:
var filteredCommentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1 && mc.Something == 99)
.Select(mc => mc.Comment)
.ToList();
Because of lazy loading things might become easier. If you have a loaded Member
you should be able to get the comments without an explicit query:
var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);
I guess that lazy loading will fetch the comments automatically behind the scenes.
Edit
Just for fun a few examples more how to add entities and relationships and how to delete them in this model:
1) Create one member and two comments of this member:
var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
Something = 102 };
context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2
context.SaveChanges();
2) Add a third comment of member1:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
var comment3 = new Comment { Message = "Good night!" };
var memberComment3 = new MemberComment { Member = member1,
Comment = comment3,
Something = 103 };
context.MemberComments.Add(memberComment3); // will also add comment3
context.SaveChanges();
}
3) Create new member and relate it to the existing comment2:
var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
.SingleOrDefault();
if (comment2 != null)
{
var member2 = new Member { FirstName = "Paul" };
var memberComment4 = new MemberComment { Member = member2,
Comment = comment2,
Something = 201 };
context.MemberComments.Add(memberComment4);
context.SaveChanges();
}
4) Create relationship between existing member2 and comment3:
var member2 = context.Members.Where(m => m.FirstName == "Paul")
.SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
.SingleOrDefault();
if (member2 != null && comment3 != null)
{
var memberComment5 = new MemberComment { Member = member2,
Comment = comment3,
Something = 202 };
context.MemberComments.Add(memberComment5);
context.SaveChanges();
}
5) Delete this relationship again:
var memberComment5 = context.MemberComments
.Where(mc => mc.Member.FirstName == "Paul"
&& mc.Comment.Message == "Good night!")
.SingleOrDefault();
if (memberComment5 != null)
{
context.MemberComments.Remove(memberComment5);
context.SaveChanges();
}
6) Delete member1 and all its relationships to the comments:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
context.Members.Remove(member1);
context.SaveChanges();
}
This deletes the relationships in MemberComments
too because the one-to-many relationships between Member
and MemberComments
and between Comment
and MemberComments
are setup with cascading delete by convention. And this is the case because MemberId
and CommentId
in MemberComment
are detected as foreign key properties for the Member
and Comment
navigation properties and since the FK properties are of type non-nullable int
the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.
Try this:
runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1"
It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.
This will delete the dataframe and will release the RAM/memory
del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()
the data-frame will be explicitly set to null
in the above statements
Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.
more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/
Use PropertyInfo.PropertyType
to get the type of the property.
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(string))
{
string value = propertyInfo.GetValue(data, null);
if value is not OK
{
return false;
}
}
}
return true;
}
This import android packages cannot be resolved
is also occurs when your using some library and that library is not in the same path where your application is there, or if you are importing the library and not coping library to the workspace
Use that code it definitely works and I modified it.
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.*;
public class TestApp {
public static void main(String[] args) throws Exception {
try {
Class forName = Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
con.setAutoCommit(false);
PreparedStatement pstm = null;
FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
POIFSFileSystem fs = new POIFSFileSystem(input);
Workbook workbook;
workbook = WorkbookFactory.create(fs);
Sheet sheet = workbook.getSheetAt(0);
Row row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (Row) sheet.getRow(i);
String name = row.getCell(0).getStringCellValue();
String add = row.getCell(1).getStringCellValue();
int contact = (int) row.getCell(2).getNumericCellValue();
String email = row.getCell(3).getStringCellValue();
String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows " + i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
} catch (IOException e) {
}
}
}
When you
import App from './App.jsx';
That means it will import whatever you export default
. You can rename App
class inside App.jsx
to whatever you want as long as you export default
it will work but you can only have one export default.
So you only need to export default App
and you don't need to export the rest.
If you still want to export the rest of the components, you will need named export.
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
This is a real-world example.
While working with GWT-Bootstrap V2, it will inject some CSS file, which will override my CSS styles. In order to make my properties to be not overridden, I used !important
.
If your object could contain any key/value pairs, you could declare an interface called keyable
like :
interface keyable {
[key: string]: any
}
then use it as follows :
let countryProviders: keyable[];
or
let countryProviders: Array<keyable>;
Or in C# 3.0 using System.Linq
you can skip the intermediate list:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = from nv in nvPairs
select new InputProperty()
{
Name = "udf:" + nv.Name,
Val = nv.Value
};
update.Items = ip.ToArray();
return update;
}
Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine
You can simply do conditional check before doing map like
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
})
}
Now a days .map can be done in two different ways but still the conditional check is required like
.map with return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
return <li key={player.championId}>{player.summonerName}</li>
})
}
.map without return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
return <li key={player.championId}>{player.summonerName}</li>
))
}
both the above functionalities does the same
Use Convert.ToDouble("41.00027357629127");
Do this if you absolutely need to use the -Format
option:
$dateStr = Get-Date $date -Format "yyyMMdd"
However
$dateStr = $date.toString('yyyMMdd')
is probably more efficient.. :)
If you are using FireFox you can use the File HandleAPI
https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API
I had just tested it out and it works!
I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.
It works like this :
let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;
It supports nested childs but you have to decorate your class's member.
A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.
The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.
My solution also starts of with a base view model:
public class LayoutModel
{
public LayoutModel(string title)
{
Title = title;
}
public string Title { get;}
}
What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:
public class LayoutModel<T> : LayoutModel
{
public LayoutModel(T pageModel, string title) : base(title)
{
PageModel = pageModel;
}
public T PageModel { get; }
}
With this solution I have disconnected the need of having inheritance between the layout model and the model.
So now I can go ahead and use the LayoutModel in Layout.cshtml like this:
@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>
And on a page you can use the generic LayoutModel like this:
@model LayoutModel<Customer>
@{
var customer = Model.PageModel;
}
<p>Customer name: @customer.Name</p>
From your controller you simply return a model of type LayoutModel:
public ActionResult Page()
{
return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
Not exactly for this OP, but for those who encountered 404 and cannot set response content-type
to "application/json"
(any content-type
). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.
If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java
. It would run:
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException
and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html
or any suffix, the requestedMediaTypes
would be "text/[that suffix]", and this conflicts with producibleMediaTypes
, which is usually:
"application/json"
"application/xml"
"text/xml"
"application/*+xml"
"application/json"
"application/*+json"
"application/json"
"application/*+json"
"application/xml"
"text/xml"
"application/*+xml"
"application/xml"
"text/xml"
"application/*+xml"
If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:
Super Super compact
var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }
All 3 possible combinations together (ES6)
var t
window.onresize = () => {
resizing(this, this.innerWidth, this.innerHeight) //1
if (typeof t == 'undefined') resStarted() //2
clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}
function resizing(target, w, h) {
console.log(`Youre resizing: width ${w} height ${h}`)
}
function resStarted() {
console.log('Resize Started')
}
function resEnded() {
console.log('Resize Ended')
}
I do this by adding fa-placeholder
class to input text:
<input type="text" name="search" class="form-control" placeholder="" />
so, in css just add this:
.fa-placholder {
font-family: "FontAwesome"; }
It works well for me.
Update:
To change font while user type in your text input, just add your font after font awesome
.fa-placholder {
font-family: "FontAwesome", "Source Sans Pro"; }
You can use the mysqlpump
command with the
--exclude-tables=name
command. It specifies a comma-separated list of tables to exclude.
Syntax of mysqlpump is very similar to mysqldump, buts its way more performant. More information of how to use the exclude option you can read here: https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#mysqlpump-filtering
Decode them and compare them as mgilson comment.
Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)
>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True
But order is important in list; sorting will solve the problem for the lists.
>>> [1, 2] == [2, 1]
False
>>> [1, 2] == sorted([2, 1])
True
>>> a = '{"errors": [{"error": "invalid", "field": "email"}, {"error": "required", "field": "name"}], "success": false}'
>>> b = '{"errors": [{"error": "required", "field": "name"}, {"error": "invalid", "field": "email"}], "success": false}'
>>> a, b = json.loads(a), json.loads(b)
>>> a['errors'].sort()
>>> b['errors'].sort()
>>> a == b
True
Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.
You can do this a number of non-DNS ways. The landing page at subdomain.hostone.com can have an HTTP redirect. The webserver at hostone.com can be configured to redirect (easy in Apache, not sure about IIS), etc.
This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...
To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !
>>> type(cow)
<class 'range'>
>>>
>>> type(cow[0])
<class 'int'>
>>>
>>> type(0)
<class 'int'>
>>>
>>> >>> list(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table
Here goes mix of weekens's and Vovodroid's solutions.
It is more correct than Vovodroid's solution and more complete than weekens's solution.
try {
InputStream inputStream = res.openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
reader.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// process exception
}
I had this issue with Mvc identity when registering new user instead of:
var result = await UserManager.CreateAsync(user);
I was doing:
var result = await UserManager.UpdateAsync(user);
The first argument to a shell script is available as the variable $1
, so the simplest implementation would be
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
But what anubhava said.
I used smth like this:
1.style.fontSize = 15.6/(document.getElementById("2").innerHTML.length)+ 'vw'
Where: 1 - parent div Id and 2 - Id of div with my text
No need of JQuery simply you can do
if(yourObject['email']){
// what if this property exists.
}
as with any value for email
will return you true
, if there is no such property or that property value is null
or undefined
will result to false
In GNU find
you can use -printf
parameter for that, e.g.:
find /dir1 -type f -printf "%f\n"
There are various options are available to test which java version is using your eclipse. The best way is to find first java installed in your machine.
run java -version command on terminal
then to check whether your eclipse pointing to the right version or not.
For that go to
Eclipse >> Preferences >>Java >>Installed JREs
You have a line break <br>
in-between the second and third images in your markup. Get rid of that, and it'll show inline.
WARNING: iTunesConnect may reject apps that are using this method.
New member on my team accidentally broke the solution given by one of the top answers, so I decided to consolidate it in a small wrapper project called CommonCryptoModule. You can install it manually or via Cocoapods:
pod 'CommonCryptoModule', '~> 1.0.2'
Then, all you have to do is to import the module where you need CommonCrypto
, like so:
import CommonCryptoModule
Hope someone else finds this useful.
You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.
Maybe a small recap is in order:
The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).
A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.
For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.
Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.
On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.
The Wikipedia article has many details on the stages of SAX parsing.
you can add a condition to the after_update
like so:
class SomeModel < ActiveRecord::Base
after_update :send_notification, if: :published_changed?
...
end
there's no need to add a condition within the send_notification
method itself.
DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.
I was also wondering how to store it cleanly in a variable. As using
char c = '•';
is not very good practice (I guess). I found out the following way of storing it in a variable
char c = (char)0x2022;// or 0x25cf depending on the one you choose
or even cleaner
char c = '\u2022';// or "\u25cf"
https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx
same for strings
string s = "\u2022";
I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.
I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with pip install --egg --upgrade scons
)
Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
Here's a cross browser solution that triggers an event when your selected images are loaded: http://desandro.github.io/imagesloaded/ you can look up the height and width within the imagesLoaded() function.
try with set sql_mode = 'STRICT_TRANS_TABLES'
OR SET sql_mode='STRICT_ALL_TABLES'
I think functional requirement is from client to developer side that is regarding functionality to the user by the software and non-functional requirement is from developer to client i.e. the requirement is not given by client but it is provided by developer to run the system smoothly e.g. safety, security, flexibility, scalability, availability, etc.
I usualy would enter the path like this ....
FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe");
Did you register the @ at the beginning of the string? ;-)
If you have the luxury of working in C++, use this:
template<typename T>
void swapPrimitives(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
Granted, in the case of char*
, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?
I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)
if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
//do stuff
}
Hope this helps anyone!
SELECT * FROM TABEL1 WHERE DATE= (SELECT MAX(CREATED_DATE) FROM TABEL1)
public class UrlContent{
public static void main(String[] args) {
URL url;
try {
// get URL content
String a="http://localhost:8080/TestWeb/index.jsp";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
HTML5 provides Canvas.toDataURL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions, however (mostly to do with drawing content from another origin onto the canvas).
So you don't need an additional library.
e.g.
<canvas id=canvas width=200 height=200></canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(50, 50, 100, 100);
// no argument defaults to image/png; image/jpeg, etc also work on some
// implementations -- image/png is the only one that must be supported per spec.
window.location = canvas.toDataURL("image/png");
}
</script>
Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven't tested.
After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.
function secsToTime(secs){
var time = new Date();
// create Date object and set to today's date and time
time.setHours(parseInt(secs/3600) % 24);
time.setMinutes(parseInt(secs/60) % 60);
time.setSeconds(parseInt(secs%60));
time = time.toTimeString().split(" ")[0];
// time.toString() = "HH:mm:ss GMT-0800 (PST)"
// time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
// time.toTimeString().split(" ")[0]; = "HH:mm:ss"
return time;
}
I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.
I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.
You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Everything is possible (or almost) with css, just use:
display: none; //to hide
display: table-cell //to show
Simply put inside your script :
source FILE
Or
. FILE # POSIX compliant
$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.
Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.
Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
Is your MySQL server version 5.5.3 or greater?
The utf8mb4, utf16, and utf32 character sets were added in MySQL 5.5.3.
http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-sets.html
Check out umount2
:
Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behaviour of the operation:
MNT_FORCE (since Linux 2.1.116) Force unmount even if busy. (Only for NFS mounts.) MNT_DETACH (since Linux 2.4.11) Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy. MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH. Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
@Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
#include <iostream>
std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
You can use zip
with *
to get transpose of a matrix:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null
solved my issue.
In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
Hey I thought this may be useful for someone who wants to replace the characters comes after the "By", for example in the text he given has by at the 20th position of his string so if you want to ignore the by you should add + 2 to the position then which will ignore the 20th position and it will replace all after coming the by it will work if you give the exact character length of the text you're gonna replace.
$variable = substr($variable, 0, strpos($variable, "By") + 2 );
To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.
For instance, adding two columns (A and B) together from a data frame dfr
:
temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')
When I do this I throw away the intermediate afterwards with remove
/rm
.
Code
train["label_Name"].value_counts().to_frame()
where : label_Name Mean column_name
result (my case) :-
0 29720
1 2242
Name: label, dtype: int64
To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:
Whichever of those you choose, your record will look like the following:
Record: ALIAS
or ANAME
Name: empty or @
Target: example.com.herokudns.com.
That's all you need.
However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.
If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www
to http://example.com
.
If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.
To handle the redirects at the application level, you'll need to:
heroku domains:add example.com
and heroku domains:add www.example.com
)www
pointing to www.example.com.herokudns.com.
SECURE_SSL_REDIRECT
to True
)Check out this post from DNSimple for more.
if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file. an example:
[mysqld]
bind-address = 127.100.10.234
this ip is from a ethX configuration.
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
You can use result.className = 'red';
, but you can also use result.classList.add('red');
. The .classList.add(str)
way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.
gawk can get the matching part of every line using this as action:
{ if (match($0,/your regexp/,m)) print m[0] }
match(string, regexp [, array]) If array is present, it is cleared, and then the zeroth element of array is set to the entire portion of string matched by regexp. If regexp contains parentheses, the integer-indexed elements of array are set to contain the portion of string matching the corresponding parenthesized subexpression. http://www.gnu.org/software/gawk/manual/gawk.html#String-Functions
You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
Private Sub Main()
Dim value = getValue()
'do something with value
End Sub
Private Function getValue() As Integer
Return 3
End Function
Modifying MrWonderful code
import sys
def print_dictionary(obj, ident):
if type(obj) == dict:
for k, v in obj.items():
sys.stdout.write(ident)
if hasattr(v, '__iter__'):
print k
print_dictionary(v, ident + ' ')
else:
print '%s : %s' % (k, v)
elif type(obj) == list:
for v in obj:
sys.stdout.write(ident)
if hasattr(v, '__iter__'):
print_dictionary(v, ident + ' ')
else:
print v
else:
print obj
If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:
declare const modal: IModal;
If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.
const modal: IModal = {
content: '',
form: '',
href: '',
$form: null,
$message: null,
$modal: null,
$submits: null
};
Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content
and so on (properties that the contract says will be there).
const modal = {} as IModal;
Example Class
class Modal implements IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
const modal = new Modal();
You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...
const modal: Modal = new Modal();
Rather than
const modal: IModal = new Modal();
CREATE A FUNCTION:
CREATE DEFINER=`root`@`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255))
RETURNS varchar(255) CHARSET utf8
RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2)))
USE THE FUNCTION
UPDATE tbl_name SET col_name = UC_FIRST(col_name);
This happened to me when I deleted a folder and then copy-pasted it back to the project.
Right-click project folder -> Rebuild
worked for me.
Unless your usage went up a lot, it seems unlikely that there is just a backlog of work. IMO, the most likely option is that something is using connections and not releasing them promptly. Are you sure you are using using
in all cases? Or (through whatever mechanism) releasing the connections?
The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.
Exception currentException = null;
As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.
Also, the finally blocks always run before the method exits. You could then requite the code snippet to:
public class C1 {
public static void main(String [] argv) throws Exception {
try {
System.out.print(1);
q();
}
catch ( Exception i ) {
// <-- currentException = Exception, as thrown by q()'s finally block
throw( new MyExc2() ); // <-- currentException = MyExc2
}
finally {
// <-- currentException = MyExc2, thrown from main()'s catch block
System.out.print(2);
throw( new MyExc1() ); // <-- currentException = MyExc1
}
} // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.
static void q() throws Exception {
try {
throw( new MyExc1() ); // <-- currentException = MyExc1
}
catch( Exception y ) {
// <-- currentException = null, because the exception is caught and not rethrown
}
finally {
System.out.print(3);
throw( new Exception() ); // <-- currentException = Exception
}
}
}
The order in which the application executes is:
main()
{
try
q()
{
try
catch
finally
}
catch
finally
}
When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
It works here:
$ wget -S -O - http://google.com
HTTP request sent, awaiting response...
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 25 Aug 2012 10:15:38 GMT
Expires: Mon, 24 Sep 2012 10:15:38 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29-- http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...
...skipped a few more redirections ...
[<=> ] 0 --.-K/s
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti
... skipped ...
perhaps you need to update your wget (~$ wget --version
GNU Wget 1.14 built on linux-gnu.
)
You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-
last_list.append(p.last)
if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
Taken from @J-Rou's comment
I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.
I've ended up of coding code snippet like this:
#define INIT_STRING_ARRAY(...) \
{ \
char* args[] = __VA_ARGS__; \
ev = args; \
count = _countof(args); \
}
void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
USES_CONVERSION;
char** ev = nullptr;
int count = 0;
if( key.Compare("horizontal_alignment") )
INIT_STRING_ARRAY( { "top", "bottom" } )
if (key.Compare("boolean"))
INIT_STRING_ARRAY( { "yes", "no" } )
if( ev == nullptr )
return;
for( int i = 0; i < count; i++)
item->AddOption(A2T(ev[i]));
item->AllowEdit(FALSE);
}
char** ev
picks up pointer to array strings, and count picks up amount of strings using _countof
function. (Similar to sizeof(arr) / sizeof(arr[0])
).
And there is extra Ansi to unicode conversion using A2T
macro, but that might be optional for your case.
A couple of notes first: when you use Data/data1.txt
as an argument, should it really be /Data/data1.txt
(with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt
and .txt files only:
#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done
Notes:
/Data/*.txt
expands to the paths of the text files in /Data (including the /Data/ part)$( ... )
runs a shell command and inserts its output at that point in the command linebasename somepath .txt
outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt
-> file
)If you needed to run MyProgram with Data/file.txt
instead of /Data/file.txt
, use "${filename#/}"
to remove the leading slash. On the other hand, if it's really Data
not /Data
you want to scan, just use for filename in Data/*.txt
.
A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.
cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.
Well you could solve this with a temp table..
DECLARE @RoleToAdds TABLE
([RoleID] int, [PageID] int)
INSERT INTO @RoleToAdds ([RoleID], [PageID])
VALUES
(1, 2),
(1, 3),
(1, 4),
(2, 5)
INSERT INTO [dbo].[RolePages] ([RoleID], [PageID])
SELECT rta.[RoleID], rta.[PageID] FROM @RoleToAdds rta WHERE NOT EXISTS
(SELECT * FROM [RolePages] rp WHERE rp.PageID = rta.PageID AND rp.RoleID = rta.RoleID)
This might not work for big amounts of data but for a few rows it should work!
It works if id value and name value are different:
<input type="password" class="form-control"name="password" id="mainpassword">
password: { required: true, } ,
cpassword: {required: true, equalTo: '#mainpassword' },
I had same problem , instead @Entity I used following code for getting records
List<Map<String, Object>> list = null;
list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {
@Override
public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
query.setParameter("app", apptype);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.list();
}
});
I used following code for update
private @Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;
updateCount = incidentHibernateTemplate.execute((Session session) -> {
Query<?> query = session
.createSQLQuery("UPDATE tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
query.setParameter("apiurl", url);
query.setParameter("api", api);
query.setParameter("mode", mode);
return query.executeUpdate();
}
);
This Works for me. I have to use specially date format like this 'YY-MM-dd hh:mm' or 'YYYY-MM-dd hh:mm'
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-dd hh:mm',
defaultDate: new Date()
});
Having all the related projects in the same root directory.
This will create a empty project, with a .idea directory that will simply remember the module organisation we are about to do in the next step
The project will be imported as a new module.
Seriously... I don't understand why all solutions are that complicated! How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????
template <typename T>
void SwapEnd(T& var)
{
static_assert(std::is_pod<T>::value, "Type must be POD type for safety");
std::array<char, sizeof(T)> varArray;
std::memcpy(varArray.data(), &var, sizeof(T));
for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)
std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);
std::memcpy(&var, varArray.data(), sizeof(T));
}
It's the magic power of C and C++ together! Simply swap the original variable character by character.
Point 1: No operators: Remember that I didn't use the simple assignment operator "=" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.
Point 2: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate uint64_t
, your compiler cannot guarantee that you can access the 3rd byte of that as a uint8_t
. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no reinterpret_cast
). Notice that compilers are mostly smart enough to convert what you did back to a reinterpret_cast
if they're capable of accessing individual bytes regardless of alignment.
To use this function:
double x = 5;
SwapEnd(x);
and now x
is different in endianness.
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:
dependencies
{
...
compile 'com.android.support:support-annotations:27.1.1'
}
It worked for me perfectly
open a terminal and run this command xhost +
. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands
Also make sure in your /etc/environment file there is a line
export DISPLAY=:0.0
And then, run your tests to see if your issue is resolved.
All please note the comment from sardathrion below before using this.
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
Hey, that's mine from somewhere :).
In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
In the case of the Uploadify web, you're in a pickle, since the upload thing is no input
, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).
So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name
input. Please, make sure this assumption is true in your case, too.
If not, you could try to jump to it by pressing Alt + N, at least on Windows...
If yes, you can "blindly" type the path into it using the Robot
class. In your case, that would be something in the way of:
driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C); // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON); // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH); // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path
r.keyPress(KeyEvent.VK_ENTER); // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);
It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar()
which does similar work, but is available only from JDK7).
For Flash, the only alternative I know (from this discussion) is to use the dark technique:
First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.
Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.
This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.
If you want to overwrite only one file:
git fetch
git checkout origin/master <filepath>
If you want to overwrite all changed files:
git fetch
git reset --hard origin/master
(This assumes that you're working on master
locally and you want the changes on the origin's master
- if you're on a branch, substitute that in instead.)
Here is how to to that:
The header and footer are 30px height.
The footer is stuck to the bottom of the page.
HTML:
<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>
CSS:
#header {
height: 30px;
}
#footer {
height: 30px;
position: absolute;
bottom: 0;
}
body {
height: 100%;
margin-bottom: 30px;
}
Try it on jsfiddle: http://jsfiddle.net/Usbuw/
One possible explanation is a database trigger that fires for each DROP TABLE
statement. To find the trigger, query the _TRIGGERS
dictionary views:
select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')
disable any suspicious trigger with
alter trigger <trigger_name> disable;
and try re-running your DROP TABLE
statement
Obj-C way =):
NSString *inStr = [@(month) stringValue];
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
Value exactly equal to 123:
jQuery("#attached_docs[value='123']")
Full reference: http://api.jquery.com/category/selectors/
exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g
exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;
or use the punct at the top of your php script
#!/usr/local/bin/php
<?php ... ?>
I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:
JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");
If you statically import javax.swing.JOptionPane.showMessageDialog
using:
import static javax.swing.JOptionPane.showMessageDialog;
This further reduces to
showMessageDialog(null, "This is even shorter");
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
You can use the .ToList() method to convert the IQueryable result returned to an IList, as shown below, after the linq query.
public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
if (firstname == null && lastname != null)
{
IList<DzieckoAndOpiekun> resultV = from p in db.Dziecko
where lastname == p.Nazwisko
**select** new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko).ToList()
;
result.AddRange(resultV);
}
return result;
}
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
To continue using the iframe YouTube, you should only have to change ?autoplay=1
to ?autoplay=0
.
Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)
Edit: the YouTube JavaScript Player API is no longer supported.
<div id="howToVideo"></div>
<script type="application/javascript">
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = false;
ga.src = 'http://www.youtube.com/player_api';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('howToVideo', {
height: '390',
width: '640',
videoId: 'qUJYqhKZrwA',
playerVars: {
controls: 0,
disablekb: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
console.log('onPlayerReady', evt);
}
function onPlayerStateChange(evt) {
console.log('onPlayerStateChange', evt);
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
console.log('stopVideo');
player.stopVideo();
}
</script>
Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/
Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo()
.
The number of arguments is $#
Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
for huge size collections, you can use Bulk.insert()
var bulk = db.getSiblingDB(dbName)[targetCollectionName].initializeUnorderedBulkOp();
db.getCollection(sourceCollectionName).find().forEach(function (d) {
bulk.insert(d);
});
bulk.execute();
This will save a lot of time. In my case, I'm copying collection with 1219 documents: iter vs Bulk (67 secs vs 3 secs)
I have two points for the implicit join (The second example):
C++14
std::string great = "Hello"s + " World"; // concatenation easy!
Answer on the question:
auto fname = ""s + name + ".txt";
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
@PathVariable
used to fetch the value from URL
for example: To get some question
www.stackoverflow.com/questions/19803731
Here some question id
is passed as a parameter in URL
Now to fetch this value in controller
all you have to do is just to pass @PathVariable in the method parameter
@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
public String getQuestion(@PathVariable String questionId){
//return question details
}
In likeness of how I found this question using Google, I wanted to take it one step further.
Lets say I have a string[] states
and a db Entity
of StateCounties
and I just want the states from the list returned and not all of the StateCounties
.
I would write:
db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();
I found this within the sample of CheckBoxList
for nu-get.
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
$var = $_POST['taskOption'];
128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);
output>> c2d29867-3d0b-d497-9191-18a9d8ee7830
(works at least in 8.4)
clock_timestamp()
explanation.If you need a valid v4 UUID
SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);
* Thanks to @Denis Stafichuk @Karsten and @autronix
Also, in modern Postgres, you can simply cast:
SELECT md5(random()::text || clock_timestamp()::text)::uuid
Demo - http://codepen.io/grantex/pen/InLmJ
<div class="navigation">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Menu</a></li>
<li><a href="">Others</a></li>
</ul>
</div>
.navigation {
max-width: 700px;
margin: 0 auto;
}
.navigation ul {
list-style: none;
display: table;
width: 100%;
}
.navigation ul li {
display: table-cell;
text-align: center;
}
.navigation ul li a {
padding: 5px 10px;
width: 100%;
}
Omg so much cleaner.
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
Try using
Decimal(19,4)
this usually works with every other DB as well
For scala
import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
This works for me:
const from = '2019-01-01';_x000D_
const to = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
moment(from, 'YYYY-MM-DD')_x000D_
.startOf('day')_x000D_
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
) + 1_x000D_
);
_x000D_
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
As far as the http verb is concerned the WebRequest
might be easier. You could go for something like:
WebRequest r = WebRequest.Create("http://some.url");
r.Method = "POST";
using (var s = r.GetResponse().GetResponseStream())
{
using (var reader = new StreamReader(r, FileMode.Open))
{
var content = reader.ReadToEnd();
}
}
Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream()
and write it like a regular stream, but I hope it may be of some help.
Here's my 2 cents:
import sys
sys.path.append('/Users/John/Desktop')
import mapping #mapping.py is the name of my module file
shipit = mapping.Shipment() #Shipment is the name of the class I need to use in the mapping module
from mapping import Mapping
shipit = Shipment() #Now you don't have to use the .notation
quick performance data for the StringBuilder vs Select & Aggregate case over 3000 elements:
Unit test - Duration (seconds)
LINQ_StringBuilder - 0.0036644
LINQ_Select.Aggregate - 1.8012535
[TestMethod()]
public void LINQ_StringBuilder()
{
IList<int> ints = new List<int>();
for (int i = 0; i < 3000;i++ )
{
ints.Add(i);
}
StringBuilder idString = new StringBuilder();
foreach (int id in ints)
{
idString.Append(id + ", ");
}
}
[TestMethod()]
public void LINQ_SELECT()
{
IList<int> ints = new List<int>();
for (int i = 0; i < 3000; i++)
{
ints.Add(i);
}
string ids = ints.Select(query => query.ToString())
.Aggregate((a, b) => a + ", " + b);
}
$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
$tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
$tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));
Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/>
field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.
I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:
Hello.js
import React, { Component } from "react";
import SelectValid from "./SelectValid";
export default class Hello extends Component {
render() {
return (
<form>
<SelectValid placeholder="this one is optional" />
<SelectValid placeholder="this one is required" required />
<input
required
defaultValue="foo"
onChange={e => e.target.setCustomValidity("")}
onInvalid={e => e.target.setCustomValidity("foo")}
/>
<button>button</button>
</form>
);
}
}
SelectValid.js
import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
export default class SelectValid extends Component {
render() {
this.required = !this.props.required
? false
: this.state && this.state.value ? false : true;
let inputProps = undefined;
let onInputChange = undefined;
if (this.props.required) {
inputProps = {
onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
};
onInputChange = value => {
this.selectComponent.input.input.setCustomValidity(
value
? ""
: this.required
? "foo"
: this.selectComponent.props.value ? "" : "foo"
);
return value;
};
}
return (
<Select
onChange={value => {
this.required = !this.props.required ? false : value ? false : true;
let state = this && this.state ? this.state : { value: null };
state.value = value;
this.setState(state);
if (this.props.onChange) {
this.props.onChange();
}
}}
value={this && this.state ? this.state.value : null}
options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
placeholder={this.props.placeholder}
required={this.required}
clearable
searchable
inputProps={inputProps}
ref={input => (this.selectComponent = input)}
onInputChange={onInputChange}
/>
);
}
}
In MonoTouch:
To get the Major version use:
UIDevice.CurrentDevice.SystemVersion.Split('.')[0]
For minor version use:
UIDevice.CurrentDevice.SystemVersion.Split('.')[1]
I like visual answers.
When you click #btn
, two event handlers get called and they output what you see in the picture.
Demo here: https://jsfiddle.net/ujhe1key/
If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.
Otherwise, stick with multiple if-else statements.
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
Take a look at highlight (jQuery plugin).
There's a function for that in SciPy. It's called Euclidean.
Example:
from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)
Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
GET
/POST
/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.Python has two different ways to convert an object to a string: str()
and repr()
. Printing an object uses str()
; printing a list containing an object uses str()
for the list itself, but the implementation of list.__str__()
calls repr()
for the individual items.
So you should also overwrite __repr__()
. A simple
__repr__ = __str__
at the end of the class body will do the trick.
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).
So basically, from bottom to top
Linux
Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx
PHP-FPM + APC
ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.
Whenever you are creating objects of class you have to check the whether the object is null or not using the below code.
Example: object1 is object of class
void myFunction(object1)
{
if(object1!=null)
{
object1.value1 //If we miss the null check then here we get the Null Reference exception
}
}
You can keep the default behaviour (with gutter) and add a class to your CSS stylesheet for tasks like yours:
.no-gutter > [class*='col-'] {
padding-right:0;
padding-left:0;
}
And here’s how you can use it in your HTML:
<div class="row no-gutter">
<div class="col-md-4">
...
</div>
<div class="col-md-4">
...
</div>
<div class="col-md-4">
...
</div>
</div>
Currently this is the most up to date way reload page if the user clicks the back button.
const [entry] = performance.getEntriesByType("navigation");
// Show it in a nice table in the developer console
console.table(entry.toJSON());
if (entry["type"] === "back_forward")
location.reload();
See here for source
The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.
An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.
BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.
Hope this helps :)
When you want to show an URL of remote branches, try:
git remote -v
to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :
<script>_x000D_
function endSession() {_x000D_
// Browser or Broswer tab is closed_x000D_
// Write code here_x000D_
}_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
There are more (many) ways to Rome:
//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null
cheers!
Beware when comparing a .Net DateTime to SqlDateTime.MinValue or MaxValue. For example, the following will throw an exception:
DateTime dte = new DateTime(1000, 1, 1);
if (dte >= SqlDateTime.MinValue)
//do something
The reason is that MinValue returns a SqlDateTime, not a DateTime. So .Net tries to convert dte to a SqlDateTime for comparison and because it's outside the acceptable SqlDateTime range it throws the exception.
One solution to this is to compare your DateTime to SqlDateTime.MinValue.Value.
Use --single-branch
option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.
git clone <repo_url> --branch <tag_name> --single-branch
How did you try it? Maybe you are working with \
and omit proper escaping.
Instead of
open('\\HOST\share\path\to\file')
use either Johnsyweb's solution with the /
s, or try one of
open(r'\\HOST\share\path\to\file')
or
open('\\\\HOST\\share\\path\\to\\file')
.
This should help with the new Google Maps:
http://maps.google.com/maps/place/<name>/@<lat>,<long>,15z/data=<mode-value>
E.g.: https://www.google.com/maps/place/Lawyer/@48.8187768,2.3792362,15z/data=!3m1!1e3
References:
https://moz.com/blog/new-google-maps-url-parameters
http://dddavemaps.blogspot.in/2015/07/google-maps-url-tricks.html
As a newbie to Android Studio, in my case, I had moved an existing project from Eclipse to Android Studio and found that there was a duplicate definition of an activity within my Manifest.xml that hadn't been picked up by Eclipse was shown as a Gradle error.
I found this by going to the Gradle Console (bottom right of the screen).
You can solve this by increasing the maximum request length in your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
</configuration>
The example above is for a 100Mb limit.
Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.
Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.
Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}
You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.
You may use in several ways,
$results = User::where([
['column_name1', '=', $value1],
['column_name2', '<', $value2],
['column_name3', '>', $value3]
])->get();
You can also use like this,
$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<', $value2);
$results = $results->where('column3','>', $value3);
$results = $results->get();
Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!
You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.
For a project structure like
project_name/src/main/java/Main_File.class
in the file build.gradle
, add the following line
mainClassName = 'Main_File'
You can accomplish this using jQuery and the ajax()
method:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<script language="javascript" type="text/javascript">_x000D_
function submitform() {_x000D_
$.ajax({_x000D_
headers: { _x000D_
'Accept': 'application/json',_x000D_
'Content-Type': 'application/json' _x000D_
},_x000D_
type: "POST",_x000D_
url : "/hello.hello",_x000D_
dataType : "json",_x000D_
data : JSON.stringify({"hello_name": "hello"}),_x000D_
error: function () {_x000D_
alert('loading Ajax failure');_x000D_
},_x000D_
onFailure: function () {_x000D_
alert('Ajax Failure');_x000D_
},_x000D_
statusCode: {_x000D_
404: function() {_x000D_
alert("missing info");_x000D_
} _x000D_
},_x000D_
success : function (response) {_x000D_
alert("The server says: " + JSON.stringify(response));_x000D_
}_x000D_
})_x000D_
.done(function( data ) {_x000D_
$("#result").text(data['hello']);_x000D_
});_x000D_
};</script>
_x000D_
Check out the java.net.URI class.
Try this:
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int
main()
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return 0;
}
The code sample is taken from here.
Reason #1
There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.
Reason #2
When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars()
function is one such example. Though there are optional arguments to htmlspecialchars()
that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.
this is very old question, but since I came here while searching worth putting my answer.
SELECT DATEPART(ISO_WEEK,'2020-11-13') AS ISO_8601_WeekNr
time_t
is of type long int
on 64 bit machines, else it is long long int
.
You could verify this in these header files:
time.h
: /usr/include
types.h
and typesizes.h
: /usr/include/x86_64-linux-gnu/bits
(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)
1)In time.h
typedef __time_t time_t;
2)In types.h
# define __STD_TYPE typedef
__STD_TYPE __TIME_T_TYPE __time_t;
3)In typesizes.h
#define __TIME_T_TYPE __SYSCALL_SLONG_TYPE
#if defined __x86_64__ && defined __ILP32__
# define __SYSCALL_SLONG_TYPE __SQUAD_TYPE
#else
# define __SYSCALL_SLONG_TYPE __SLONGWORD_TYPE
#endif
4) Again in types.h
#define __SLONGWORD_TYPE long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE long int
#if __WORDSIZE == 64
typedef long int __quad_t;
#else
__extension__ typedef long long int __quad_t;
In configuration class
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
The first line of a paragraph is indented by default, thus whether or not you have \indent
there won't make a difference. \indent
and \noindent
can be used to override default behavior. You can see this by replacing your line with the following:
Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented
\noindent override default indentation (not indented)\\
asdf
As of pandas 1.0.0, you no longer need to use numpy to create null values in your dataframe. Instead you can just use pandas.NA (which is of type pandas._libs.missing.NAType), so it will be treated as null within the dataframe but will not be null outside dataframe context.
Using binary AND
with 0b1111
:
String element = "el5";
char c = element.charAt(2);
System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9
*first html page*
<form action="display.jsp" >
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>
you will get the value of the textbox on another page.
Exception
is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception
must handle or declare it.
http://ajmoore.blogspot.com/2007/11/svn-java-project-with-eclipse.html
you can Add contextual classes to every single row as follows:
<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>
You can also add them to table data same as above
You can set your table size by setting classes as table-sm and so on.
You can add custom classes and add your own styling:
<table class="table">
<thead style = "color:red;background-color:blue">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Asdf</td>
<td>qwerty</td>
</tr>
</tbody>
</table>
This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.
No, there isn't a boolean type in Oracle Database, but you can do this way:
You can put a check constraint on a column.
If your table hasn't a check column, you can add it:
ALTER TABLE table_name
ADD column_name_check char(1) DEFAULT '1';
When you add a register, by default this column get 1.
Here you put a check that limit the column value, just only put 1 or 0
ALTER TABLE table_name ADD
CONSTRAINT name_constraint
column_name_check (ONOFF in ( '1', '0' ));
You may also want to use this to detect HTML 5 audio in some cases:
http://diveintohtml5.ep.io/everything.html
HTML 5 JS Detect function
function supportsAudio()
{
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
With latest versions of docker, this is enough:
docker run -ti --privileged ubuntu bash
It will give access to all system resources (in /dev for instance)
Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.
So, if you had a script called my_shell_script:
#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
puts value
end
...make it executable (as others have mentioned):
chmod u+x my_shell_script
And call it like so:
> ./my_shell_script one two three four five
You'd get this:
I was passed:
one
two
three
four
five
The arguments work nicely with filename expansion:
./my_shell_script *
I was passed:
a_file_in_the_current_directory
another_file
my_shell_script
the_last_file
Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
No you would have to create your own solution. Like using the Observer design pattern or something.
If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!
Mike
I would do like below, where $products
is the actual array given in the problem at the very beginning.
print_r(
array_search("breville-variable-temperature-kettle-BKE820XL",
array_map(function($product){return $product["slug"];},$products))
);
When you're launching tomcat server from netbeans IDE you need to check in menu "tools->servers" on connection tab for tomcat server - there is catalina base directory. And you need to include something like:
<role rolename="manager"/>
<user username="admin" password="admin" roles="manager"/>
at file
\CATALINA_BASE\conf\tomcat-users.xml
or use username automatically generated by IDE with description already placed in this file or on connection tab
For Manager Apps : GUI access:
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
Use array_count_values()
function . Check this link http://php.net/manual/en/function.array-count-values.php
A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.
A list doesn't use a hash for indexing, so it isn't restricted to hashable items.
I came across a similar problem on my mac OSX. After a series of trial and error attempts I finally resolved it.
My ~/.bash_profile
looked like this
export M2_HOME=/Users/xyz/maven-3.x/bin
export PATH=$PATH:$M2_HOME
and when I tried to echo M2_HOME
from the terminal, it showed me the correct path but when I tried to fire any maven command like mvn clean
or mvn install
, it always gave the same problem
Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher
I solved this issue by changing my M2_HOME
to this
export M2_HOME=/Users/xyz/maven-3.x
export PATH=$PATH:$M2_HOME/bin
And voila ! It started working ! Just by moving the position of /bin
from M2_HOME to in front of the PATH
how about hidden span tags with linkable IDs that provide the height of the navbar:
#head1 {
padding-top: 60px;
height: 0px;
visibility: hidden;
}
<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>
heres the fiddle: http://jsfiddle.net/N6f2f/7
this work for me
<p align="center">
<img src="/LogoOfficial.png" width="300" >
</p>
if you run fpm under ubuntu, need to run the code below (checked on 12 and 14)
service php5-fpm reload
I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.
I improved Niels's solution
class Array
def except(*values)
self - values
end
end
Now you can use
[1, 2, 3, 4].except(3, 4) # return [1, 2]
[1, 2, 3, 4].except(4) # return [1, 2, 3]
As a python3 user,
The difference between load
and loads
methods is important especially when you read json data from file.
As stated in the docs:
json.load:
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
json.loads:
json.loads: Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
json.load method can directly read opened json document since it is able to read binary file.
with open('./recipes.json') as data:
all_recipes = json.load(data)
As a result, your json data available as in a format specified according to this conversion table:
https://docs.python.org/3.7/library/json.html#json-to-py-table
You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.
Here's an example, using Font Awesome for the search icon:
.search-box-container input {_x000D_
padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
content: "\f002";_x000D_
font-family: FontAwesome;_x000D_
margin-left: -25px;_x000D_
margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
<input type="text" placeholder="Search..." />_x000D_
</div>
_x000D_
I use life hacking like this
@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
public static final String GAMES = "GAMES";
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);
return cacheManager;
}
@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500)
public void reportCacheEvict() {
System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
You can add it to php.ini and it should work - just tested it on PHP 5.3.6.
I got this working by following code
getImgUrl(pet) {
var images = require.context('../assets/', false, /\.png$/)
return images('./' + pet + ".png")
}
and in HTML:
<div class="col-lg-2" v-for="pic in pics">
<img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>
But not sure why my earlier approach did not work.