I want to propose a solution where both flavors of a many-to-many configuration can be achieved.
The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet
.
This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.
The model:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class MemberCommentView
{
public int MemberID { get; set; }
public int CommentID { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
}
The configuration:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
public class MemberConfiguration : EntityTypeConfiguration<Member>
{
public MemberConfiguration()
{
HasKey(x => x.MemberID);
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.FirstName).HasColumnType("varchar(512)");
Property(x => x.LastName).HasColumnType("varchar(512)")
// configure many-to-many through internal EF EntitySet
HasMany(s => s.Comments)
.WithMany(c => c.Members)
.Map(cs =>
{
cs.ToTable("MemberComment");
cs.MapLeftKey("MemberID");
cs.MapRightKey("CommentID");
});
}
}
public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
public CommentConfiguration()
{
HasKey(x => x.CommentID);
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Message).HasColumnType("varchar(max)");
}
}
public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
public MemberCommentViewConfiguration()
{
ToTable("MemberCommentView");
HasKey(x => new { x.MemberID, x.CommentID });
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Something).HasColumnType("int");
Property(x => x.SomethingElse).HasColumnType("varchar(max)");
// configure one-to-many targeting the Join Table view
// making all of its properties available
HasRequired(a => a.Member).WithMany(b => b.MemberComments);
HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
}
}
The context:
using System.Data.Entity;
public class MyContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<MemberCommentView> MemberComments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MemberConfiguration());
modelBuilder.Configurations.Add(new CommentConfiguration());
modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());
OnModelCreatingPartial(modelBuilder);
}
}
From Saluma's (@Saluma) answer
If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:
This still works...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
...but could now also be...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.Comments)
.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:
This still works...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
...but could now also be...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
m.Comments
})
.ToList();
If you want to remove a comment from a member
var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith
member.Comments.Remove(comment);
If you want to Include()
a member's comments
var member = context.Members
.Where(m => m.FirstName == "John", m.LastName == "Smith")
.Include(m => m.Comments);
This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.
In terms of entities (or objects) you have a Class
object which has a collection of Students
and a Student
object that has a collection of Classes
. Since your StudentClass
table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.
Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the Class
object, the Student
objects, add the students to the class Students
collection add the Class
object to the context and call SaveChanges
:
using (var context = new YourContext())
{
var mathClass = new Class { Name = "Math" };
mathClass.Students.Add(new Student { Name = "Alice" });
mathClass.Students.Add(new Student { Name = "Bob" });
context.AddToClasses(mathClass);
context.SaveChanges();
}
This will create an entry in the Class
table, two entries in the Student
table and two entries in the StudentClass
table linking them together.
You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call SaveChanges
. Check this similar question for details.
Edit:
According to your comment, you need to insert a new Class
and add two existing Students
to it:
using (var context = new YourContext())
{
var mathClass= new Class { Name = "Math" };
Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");
mathClass.Students.Add(student1);
mathClass.Students.Add(student2);
context.AddToClasses(mathClass);
context.SaveChanges();
}
Since both students are already in the database, they won't be inserted, but since they are now in the Students
collection of the Class
, two entries will be inserted into the StudentClass
table.
The essentials of your question are as follows.
Since you have Map
and User
models and you have defined ManyToManyField
in Map model, if you want to get access to members of the Map then you have the option of map_instance.members.all()
since you have defined members field.
However, say you want to access all maps a user is a part of then what option do you have.
By default, Django provided you with user_instance.modelname_set.all()
and this will translate to the user.map_set.all()
in this case.
maps is much better than map_set.
related_name provides you an ability to let Django know how you are going to access Map from User model or in general how you can access reverse models which is the whole point in creating ManyToMany fields and using ORM in that sense.
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).
Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.
What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!
All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.
As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
EDIT 2017-04-29: As pointed to by some of the commenters, the JoinTable
example does not need the mappedBy
annotation attribute. In fact, recent versions of Hibernate refuse to start up by printing the following error:
org.hibernate.AnnotationException:
Associations marked as mappedBy must not define database mappings
like @JoinTable or @JoinColumn
Let's pretend that you have an entity named Project
and another entity named Task
and each project can have many tasks.
You can design the database schema for this scenario in two ways.
The first solution is to create a table named Project
and another table named Task
and add a foreign key column to the task table named project_id
:
Project Task
------- ----
id id
name name
project_id
This way, it will be possible to determine the project for each row in the task table. If you use this approach, in your entity classes you won't need a join table:
@Entity
public class Project {
@OneToMany(mappedBy = "project")
private Collection<Task> tasks;
}
@Entity
public class Task {
@ManyToOne
private Project project;
}
The other solution is to use a third table, e.g. Project_Tasks
, and store the relationship between projects and tasks in that table:
Project Task Project_Tasks
------- ---- -------------
id id project_id
name name task_id
The Project_Tasks
table is called a "Join Table". To implement this second solution in JPA you need to use the @JoinTable
annotation. For example, in order to implement a uni-directional one-to-many association, we can define our entities as such:
Project
entity:
@Entity
public class Project {
@Id
@GeneratedValue
private Long pid;
private String name;
@JoinTable
@OneToMany
private List<Task> tasks;
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
}
Task
entity:
@Entity
public class Task {
@Id
@GeneratedValue
private Long tid;
private String name;
public Long getTid() {
return tid;
}
public void setTid(Long tid) {
this.tid = tid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This will create the following database structure:
The @JoinTable
annotation also lets you customize various aspects of the join table. For example, had we annotated the tasks
property like this:
@JoinTable(
name = "MY_JT",
joinColumns = @JoinColumn(
name = "PROJ_ID",
referencedColumnName = "PID"
),
inverseJoinColumns = @JoinColumn(
name = "TASK_ID",
referencedColumnName = "TID"
)
)
@OneToMany
private List<Task> tasks;
The resulting database would have become:
Finally, if you want to create a schema for a many-to-many association, using a join table is the only available solution.
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.
Also, this is the same in a slightly smaller footprint:
if(borrar() !== !1)
Try the following (note that there should not be a space between the VAR
, =
, and GREG
).
SET VAR=GREG
ECHO %VAR%
PAUSE
Use "$@"
to represent all the arguments:
for var in "$@"
do
echo "$var"
done
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';
Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)
Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.
It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.
You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.
So go with what your data structures book said!
Edit:
Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.
This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)
For attributes whose type is an immutable value class that conforms to the NSCopying
protocol, you almost always should specify copy
in your @property
declaration. Specifying retain
is something you almost never want in such a situation.
Here's why you want to do that:
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
Person *p = [[[Person alloc] init] autorelease];
p.name = someName;
[someName setString:@"Debajit"];
The current value of the Person.name
property will be different depending on whether the property is declared retain
or copy
— it will be @"Debajit"
if the property is marked retain
, but @"Chris"
if the property is marked copy
.
Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy
. (And if you write the setter yourself instead of using @synthesize
you should remember to actually use copy
instead of retain
in it.)
If you want to change Title of activity when you change activity by clicking on the Button. Declare the necessary variables in MainActivity:
private static final String TITLE_SIGN = "title_sign";
ImageButton mAriesButton;
Add onClickListener in onCreate() and make new intent for another activity:
mTitleButton = (ImageButton) findViewById(R.id.title_button);
mTitleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
SignActivity.class);
String title_act = getText(R.string.simple_text).toString();
intent.putExtra("title_act", title_act);
startActivity(intent);
finish();
}
});
SecondActivity code in onCreate():
String txtTitle = getIntent().getStringExtra("title_act");
this.setTitle(txtTitle);
Given what you've tried and the error messages, I'd say this was more to do with the exact cipher algorithm used rather than the TLS/SSL version. Are you using a non-Sun JRE by any chance, or a different vendor's security implementation? Try a different JRE/OS to test your server if you can. Failing that you might just be able to see what's going on with Wireshark (with a filter of 'tcp.port == 443').
For Kotlin users
TO SHOW
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
TO HIDE
activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.
The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.
Commons-net surely. :) Most open source projects use it these days.
yc
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
There are some use cases suitable to UDP transport and others suitable to TCP transport.
The use case also dictates encoding settings for the video. When broadcasting soccer match focus is on quality and for video conference focus is on latency.
When using multicast to deliver video to your customers then UDP is used.
Requirement for multicast is expensive networking hardware between broadcasting server and customer. In practice this means if your company owns network infrastructure you can use UDP and multicast for live video streaming. Even then quality-of-service is also implemented to mark video packets and prioritize them so no packet loss happens.
Multicast will simplify broadcasting software because network hardware will handle distributing packets to customers. Customers subscribe to multicast channels and network will reconfigure to route packets to new subscriber. By default all channels are available to all customers and can be optimally routed.
This workflow places dificulty on authorization process. Network hardware does not differentiate subscribed users from other users. Solution to authorization is in encrypting video content and enabling decryption in player software when subscription is valid.
Unicast (TCP) workflow allows server to check client's credentials and only allow valid subscriptions. Even allow only certain number of simultaneous connections.
Multicast is not enabled over internet.
For delivering video over internet TCP must be used. When UDP is used developers end up re-implementing packet re-transmission, for eg. Bittorrent p2p live protocol.
"If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events".
This buffer must exist in some form. Same is true for jitter buffer on player side. It is called "socket buffer" and server software can know when this buffer is full and discard proper video frames for live streams. It is better to use unicast/TCP method because server software can implement proper frame dropping logic. Random missing packets in UDP case will just create bad user experience. like in this video: http://tinypic.com/r/2qn89xz/9
"IP multicast significantly reduces video bandwidth requirements for large audiences"
This is true for private networks, Multicast is not enabled over internet.
"Note that if TCP loses too many packets, the connection dies; thus, UDP gives you much more control for this application since UDP doesn't care about network transport layer drops."
UDP also doesn't care about dropping entire frames or group-of-frames so it does not give any more control over user experience.
"Usually a video stream is somewhat fault tolerant"
Encoded video is not fault tolerant. When transmitted over unreliable transport then forward error correction is added to video container. Good example is MPEG-TS container used in satellite video broadcast that carry several audio, video, EPG, etc. streams. This is necessary as satellite link is not duplex communication, meaning receiver can't request re-transmission of lost packets.
When you have duplex communication available it is always better to re-transmit data only to clients having packet loss then to include overhead of forward-error-correction in stream sent to all clients.
In any case lost packets are unacceptable. Dropped frames are ok in exceptional cases when bandwidth is hindered.
The result of missing packets are artifacts like this one:
Some decoders can break on streams missing packets in critical places.
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
I've never heard of such a function, but it would be trivial enough to implement...
def die(msg)
puts msg
exit
end
Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)
If you are transferring a lot data permanently, i.e not populating a temp table, I would recommend using SQL Server Import/Export Data for table-to-table mappings.
Import/Export tool is usually better than straight SQL when you have type conversions and possible value truncation in your mapping. Generally, the more complex your mapping, the more productive you are using an ETL tool like Integration Services (SSIS) instead of direct SQL.
Import/Export tool is actually an SSIS wizard, and you can save your work as a dtsx package.
Please think first of open/closed principle. The default methods in interfaces DO VIOLATE it. This is a bad feature in Java. It encourages bad design, bad architecture, low software quality. I would suggest to avoid using default methods completely.
Ask yourself a few questions: Why can't you put your methods to the abstract class? Would you need then more than one abstract class? Then think about what is your class responsible for. Are you sure all methods you are going to put to the single class really fulfill the same purpose? May be you will distinguish several purposes and will then split your class into several classes, for each purpose its own class.
Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.
Example of parsing using indexOf
to calculate the position of a string in another string:
String s="What a Beautiful day!";
int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8
paresInt
essentially converts a String
to a Integer
.
String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);
Output:
Constructor method: 9876543 parseInt() method: 9876543
Brian beat me too it, but since I already have the transcript:
aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth
Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup
.. or the normal boring way:
aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 71460 100 71460 0 0 84034 0 --:--:-- --:--:-- --:--:-- 111k
aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc
aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/
aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>
I think except for disk space issuse, you should check the log in /var/log/mongodb
to know the details for why mongodb start failed.
cat /var/log/mongodb/mongod.log
2016-06-26T15:26:26.642+0800 I CONTROL [main] ***** SERVER RESTARTED *****
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] MongoDB starting : pid=8130 port=27017 dbpath=/var/lib/mongodb 64-bit host=hadoop-master
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] db version v3.2.7
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] git version: 4249c1d2b5999ebbf1fdf3bc0e0e3b3ff5c0aaf2
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] allocator: tcmalloc
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] modules: none
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] build environment:
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] distmod: ubuntu1404
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] distarch: x86_64
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] target_arch: x86_64
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1,192.168.3.10", port: 27017 }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2016-06-26T15:26:26.678+0800 E NETWORK [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock errno:1 Operation not permitted
2016-06-26T15:26:26.678+0800 I - [initandlisten] Fatal Assertion 28578
2016-06-26T15:26:26.678+0800 I - [initandlisten]
***aborting after fassert() failure
So, here I need to rm all the files in the /tmp
. That works fine for me.
private static bool IsValidEmail(string emailAddress)
{
const string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return new Regex(validEmailPattern, RegexOptions.IgnoreCase).IsMatch(emailAddress);
}
If you want to remove the glow from buttons in Bootstrap (which is not necessarily bad UX in my opinion), you'll need the following code:
.btn:focus, .btn:active:focus, .btn.active:focus{
outline-color: transparent;
outline-style: none;
}
If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.
$data = json_decode($json, TRUE);
String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);
You can use the Oracle Data Modeler to create auto incrementing surrogate keys.
Step 1. - Create a Relational Diagram
You can first create a Logical Diagram and Engineer to create the Relational Diagram or you can straightaway create the Relational Diagram.
Add the entity (table) that required to have auto incremented PK, select the type of the PK as Integer.
Step 2. - Edit PK Column Property
Get the properties of the PK column. You can double click the name of the column or click on the 'Properties' button.
Column Properties dialog box appears.
Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.
Step 3. - Additional Information
Additional information relating to the auto increment can be specified by selecting the 'Auto Increment' tab.
It is usually a good idea to mention the sequence name, so that it will be useful in PL/SQL.
Click OK (Apply) to the Column Properties dialog box.
Click OK (Apply) to the Table Properties dialog box.
Table appears in the Relational Diagram.
This worked for me:
ActiveWorkbook.refreshall
ActiveWorkbook.Save
When you save the workbook it's necessary to complete the refresh.
May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.
Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.
In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation
on runtime library choose /MTd
for debug mode and /MT
for release mode.
This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.
I disagree with the most voted answer. Use screen
and not window
if(screen.innerHeight > screen.innerWidth){
alert("Please use Landscape!");
}
Is the proper way to do it. If you calculate with window.height
, you ll have trouble on Android. When keyboard is open, window shrinks. So use screen instead of window.
The screen.orientation.type
is a good answer but with IE.
https://caniuse.com/#search=screen.orientation
You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[]
in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer
(expecting Serializable
, and using ObjectOutputStream
). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.
I guess you can copy the entire package and make use of it.
instanceof
test should pass in order for the assignment to go through.
In your example it results
Object[] a = new Object[1];
boolean isIntegerArr = a instanceof Integer[]
sysout
of the above line, it would return false;
(Arrays.asList(a)).toArray(c);
It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use "#" with a "return false;
" to prevent the default action (scroll to top of the page) as others have mentioned.
Googling for "javascript:void(0)
" provides a lot of information on this topic. Some of them, like this one mention reasons to NOT use void(0).
git init
in the solution folder. That is the proper way to create a repository folder..gitignore
file, so you don't commit unnecessary stuff.git add
git commit
git remote add origin <proper URL>
git push
your codeAlternatively, there are detailed guides here using the Visual Studio integration.
Today 2020.03.06 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
for-in
(A,B) are fast (or fastest) for all browsers for big and small objectsfor-of
(H) solution is fast on chrome for small and big objectsi
(J,K) are quite fast on all browsers for small objects (for firefox also fast for big ojbects but medium fast on other browsers)Performance tests was performed for
Below snippets presents used solutions
function A(obj,s='') {_x000D_
for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function B(obj,s='') {_x000D_
for (let key in obj) s+=key+'->'+obj[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function C(obj,s='') {_x000D_
const map = new Map(Object.entries(obj));_x000D_
for (let [key,value] of map) s+=key+'->'+value + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function D(obj,s='') {_x000D_
let o = { _x000D_
...obj,_x000D_
*[Symbol.iterator]() {_x000D_
for (const i of Object.keys(this)) yield [i, this[i]]; _x000D_
}_x000D_
}_x000D_
for (let [key,value] of o) s+=key+'->'+value + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function E(obj,s='') {_x000D_
let o = { _x000D_
...obj,_x000D_
*[Symbol.iterator]() {yield *Object.keys(this)}_x000D_
}_x000D_
for (let key of o) s+=key+'->'+o[key] + ' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function F(obj,s='') {_x000D_
for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function G(obj,s='') {_x000D_
for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function H(obj,s='') {_x000D_
for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function I(obj,s='') {_x000D_
for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
return s;_x000D_
}_x000D_
_x000D_
function J(obj,s='') {_x000D_
let keys = Object.keys(obj);_x000D_
for(let i = 0; i < keys.length; i++){_x000D_
let key = keys[i];_x000D_
s+=key+'->'+obj[key]+' ';_x000D_
}_x000D_
return s;_x000D_
}_x000D_
_x000D_
function K(obj,s='') {_x000D_
var keys = Object.keys(obj), len = keys.length, i = 0;_x000D_
while (i < len) {_x000D_
let key = keys[i];_x000D_
s+=key+'->'+obj[key]+' ';_x000D_
i += 1;_x000D_
}_x000D_
return s;_x000D_
}_x000D_
_x000D_
function L(obj,s='') {_x000D_
Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
return s;_x000D_
}_x000D_
_x000D_
function M(obj,s='') {_x000D_
Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');_x000D_
return s;_x000D_
}_x000D_
_x000D_
function N(obj,s='') {_x000D_
Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');_x000D_
return s;_x000D_
}_x000D_
_x000D_
function O(obj,s='') {_x000D_
Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
return s;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
let log = (name,f) => console.log(`${name} ${f(p)}`)_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('F',F);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);_x000D_
log('O',O);
_x000D_
This snippet only presents choosen solutions
_x000D_
And here are result for small objects on chrome
NOTE: Despite (or rather, because of) succinctness and apparent elegance, this algorithm is by no means a high-quality one in terms of randomness. Look for e.g. those listed in this answer for better results.
(Originally adapted from a clever idea presented in a comment to another answer.)
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
You can set seed
to be any number, just avoid zero (or any multiple of Math.PI).
The elegance of this solution, in my opinion, comes from the lack of any "magic" numbers (besides 10000, which represents about the minimum amount of digits you must throw away to avoid odd patterns - see results with values 10, 100, 1000). Brevity is also nice.
It's a bit slower than Math.random() (by a factor of 2 or 3), but I believe it's about as fast as any other solution written in JavaScript.
In simpler terms:
SYNCHRONOUS
You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you.
ASYNCHRONOUS
You are in a restaurant with many other people. You order your food. Other people can also order their food, they don't have to wait for your food to be cooked and served to you before they can order. In the kitchen restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked.
Ronal, to answer your question in the comment in my answer above:
function wasClicked(str)
{
return str+' def';
}
Yes, assignment is supported for structs. However, there are problems:
struct S {
char * p;
};
struct S s1, s2;
s1.p = malloc(100);
s2 = s1;
Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.
I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.
First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )
I was getting a nil reference to cell.detailTextLabel.text
- After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.
var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).
So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.
Im guesssing your label should always be there?
So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.
Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1
I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match
Start phpsh, put some content into a variable, match on word.
el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1
, $content2
and $content3
with the (\w)+
pattern.
$content1 and $content2 contain at least one word, $content3 does not.
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
Variables gun1
and gun2
contain the string dart
or fart
which is correct, but gun3 contains darty
and still matches, that is the problem. So onto the next example.
Word Boundaries can be force matched with \b
, see:
Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
The \b
asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.
Some options without REGEXMATCH
, since you might want to be case insensitive and not want say blast
or ablative
to trigger a YES
. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:
First very similar to @user1598086's answer:
=FIND("bla",A1)
Is case sensitive but returns #VALUE! rather than NO
and a number rather than YES
(both of which can however be changed to NO/YES respectively).
=SEARCH("bla",A1)
Case insensitive, so treats Black
and black
equally. Returns as above.
The former (for the latter equivalent) to indicate whether bla
present after the first three characters in A1:
=FIND("bla",A1,4)
Returns a number for blazer, black
but #VALUE!
for blazer, blue
.
To find Bla
only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):
=SEARCH(" Bla ",A1)
Since the return in all cases above is either a number ("found", so YES
preferred) or #VALUE!
we can use ISERROR to test for #VALUE!
within an IF formula, for instance taking the first example above:
=if(iserror(FIND("bla",A1)),"NO","YES")
Longer than the regexmatch
but the components are easily adjustable.
In SQL Server 2016 (or newer) you can use this:
CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...
In older versions of SQL server you have to use something like
DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';
IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN EXEC('CREATE ' + @script) END
ELSE
BEGIN EXEC('ALTER ' + @script) END
Or, if there are no dependencies on the view, you can just drop it and recreate:
IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN
DROP VIEW [VW_NAMEOFVIEW];
END
CREATE VIEW [VW_NAMEOFVIEW] AS ...
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
Try following
SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;
If you want to use std::string
reliably, you must #include <string>
.
I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p=>p.Category)
.Distinct();
Use 'as' declaration:
const data = JSON.parse(response.data) as MyClass;
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
You have #include "fun.cpp"
in mainfile.cpp
so compiling with:
g++ -o hw1 mainfile.cpp
will work, however if you compile by linking these together like
g++ -g -std=c++11 -Wall -pedantic -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic -c -o mainfile.o mainfile.cpp
As they mention above, adding #include "fun.hpp"
will need to be done or it won't work. However, your case with the funct()
function is slightly different than my problem.
I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.
If you simply want to set/use default profile at the time of making build through maven then, pass the argument
-Dspring.profiles.active=test
Just like
mvn clean install -Dspring.profiles.active=dev
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
i had the same problem and i found that Microsoft has a systable that shows dependencies.
SELECT
referenced_id
, referenced_entity_name AS table_name
, referenced_minor_name as column_name
, is_all_columns_found
FROM sys.dm_sql_referenced_entities ('dbo.Proc1', 'OBJECT');
And this works with both Views
and Triggers
.
i use jquery code for this. (Alternative solution)
$(document).ready(function() {
var margin = $(".topmenu-design").width()-$("#topmenu").width();
$("#topmenu").css('margin-left',margin/2);
});
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
t = setTimeout(function() { rotate(++degree); },65);
and clearTimeout
to stop
clearTimeout(t);
I use this with AJAX
success:function(){ clearTimeout(t); }
If you simply want to add it without creating a new class try this:
// WPF
<ComboBox Name="language" Loaded="language_Loaded" />
// C# code
private void language_Loaded(object sender, RoutedEventArgs e)
{
List<String> language= new List<string>();
language.Add("English");
language.Add("Spanish");
language.Add("ect");
this.chartReviewComboxBox.ItemsSource = language;
}
I suggest an xml file with all your languages that you will support that way you do not have to be dependent on c# I would definitly create a class for languge like the above programmer suggest.
We can create method for it. Simply use it.
public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
self.layer.borderWidth = width
self.layer.cornerRadius = radius
self.layer.shouldRasterize = false
self.layer.rasterizationScale = 2
self.clipsToBounds = true
self.layer.masksToBounds = true
let cgColor: CGColor = color.cgColor
self.layer.borderColor = cgColor
}
For IE > 9 you can use the following solution:
@font-face {
font-family: OpenSansRegular;
src: url('OpenSansRegular.ttf'), url('OpenSansRegular.eot');
}
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
I am very late but if some one working on SLIM to make rest api and getting same error can solve this problem by adding below line as:
<?php
// DbConnect.php file
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
mysqli_set_charset($this->con, "utf8"); // add this line
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly
should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.
If you specify readOnly
as true
, the flush mode will be set as FlushMode.NEVER
in the current Hibernate Session preventing the session from committing the transaction.
Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER
, but it's stronger since you cannot even flush manually.
Now let's see how transaction propagation works.
If you don't explicitly set readOnly
to true
, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW
), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.
OK, we're almost there. Let's see what brings readOnly
into this scenario.
If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.
Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.
In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).
Why do you want to enforce that only a single thread can access the DB at any one time?
It is the job of the database driver to implement any necessary locking, assuming a Connection
is only used by one thread at a time!
Most likely, your database is perfectly capable of handling multiple, parallel access
on Mojave, this did the trick :
sudo chmod go-w /usr/local/share
There is solution for you :)
You must run your script after window loaded
if you use jQuery, you can use simple way:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
status : true,
version : 'v2.5'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<script>
$(window).load(function() {
var comment_callback = function(response) {
console.log("comment_callback");
console.log(response);
}
FB.Event.subscribe('comment.create', comment_callback);
FB.Event.subscribe('comment.remove', comment_callback);
});
</script>
You should use the to_date
function (oracle/functions/to_date.php
)
SELECT * FROM MYTABLE WHERE MYTABLE.DATEIN = TO_DATE('23/04/49', 'DD/MM/YY');
Apply 100%
width and height to your image:
<div style="height:42px;width:42px">
<img src="http://someimage.jpg" style="width:100%; height:100%">
</div>
This way it will same size of its parent.
In bash:
#!/bin/bash
echo before comment
: <<'END'
bla bla
blurfl
END
echo after comment
The '
and '
around the END
delimiter are important, otherwise things inside the block like for example $(command)
will be parsed and executed.
Recently, I had a program batch processing files, I have certainly closed each file in the loop, but the error still there.
And later, I resolved this problem by garbage collect eagerly every hundreds of files:
int index;
while () {
try {
// do with outputStream...
} finally {
out.close();
}
if (index++ % 100 = 0)
System.gc();
}
I had the same problem but was resolved. I realized branch name is case sensitive. The main branch in GitHub is 'master', while in my gitbash command it's 'Master'. I renamed Master in local repository to master and it worked!
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
i dont think that we can use where clause in insert statement
Based on Tabare's Answer, I had to add one more day at the end, since the cycle is cut before
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
alert(start);
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
How about something like this.
Test the live example: http://jsfiddle.net/6hBZU/1/
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
Here is the java code,
max(Node root, int k) - to find kth largest
min(Node root, int k) - to find kth Smallest
static int count(Node root){
if(root == null)
return 0;
else
return count(root.left) + count(root.right) +1;
}
static int max(Node root, int k) {
if(root == null)
return -1;
int right= count(root.right);
if(k == right+1)
return root.data;
else if(right < k)
return max(root.left, k-right-1);
else return max(root.right, k);
}
static int min(Node root, int k) {
if (root==null)
return -1;
int left= count(root.left);
if(k == left+1)
return root.data;
else if (left < k)
return min(root.right, k-left-1);
else
return min(root.left, k);
}
JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.
You can use exec.java
.
Radio button set checked through jquery:
<div id="somediv" >
<input type="radio" name="enddate" value="1" />
<input type="radio" name="enddate" value="2" />
<input type="radio" name="enddate" value="3" />
</div>
jquery code:
$('div#somediv input:radio:nth(0)').attr("checked","checked");
My solution: I opened the references folder in Solution Explorer (showing all files), and for each assembly that the installation complained about (the name of the assembly may not be exactly the same as the filename of the assembly - within object explorer, but easy enough to figure out), I changed the Copy Local to True. I ended up needing to do that with each Microsoft Office/COM-related assembly.
if (MessageBox.Show("Please confirm before proceed" + "\n" + "Do you want to Continue ?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//do something if YES
}
else
{
//do something if NO
}
Set the property of your DataGridView:
Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill
To make the edited value of path persists in the next sessions
cd ~/
touch .bash_profile
open .bash_profile
That will open the .bash_profile in editor, write inside the following after adding what you want to the path separating each value by column.
export PATH=$PATH:/usr/local/git/bin:/usr/local/bin:
Save, exit, restart your terminal and enjoy
I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.
For checking an array empty() is better than sizeof().
If the array contains huge amount of data. It will takes more times for counting the size of the array. But checking empty is always easy.
//for empty
if(!empty($array))
echo 'Data exist';
else
echo 'No data';
//for sizeof
if(sizeof($array)>1)
echo 'Data exist';
else
echo 'No data';
I was having difficulty getting the answer by @fernando-aguirre using WindowChrome
to work. It was not working in my case because I was overriding OnSourceInitialized
in the MainWindow
and not calling the base class method.
protected override void OnSourceInitialized(EventArgs e)
{
ViewModel.Initialize(this);
base.OnSourceInitialized(e); // <== Need to call this!
}
This stumped me for a very long time.
If it is a string
then use the built in float
on it to do the conversion for instance:
print( "%.5f" % float("1.43572e-03"))
answer:0.00143572
In C++, you define your strings as
std::string MyString;
instead of
char MyString[20];
.
While writing C++ code, you encounter some C functions which require C string as parameter.
Like below:
void IAmACFunction(int abc, float bcd, const char * cstring);
Now there is a problem. You are working with C++ and you are using std::string
string variables. But this C function is asking for a C string. How do you convert your std::string
to a standard C string?
Like this:
std::string MyString;
// ...
MyString = "Hello world!";
// ...
IAmACFunction(5, 2.45f, MyString.c_str());
This is what c_str()
is for.
Note that, for std::wstring
strings, c_str()
returns a const w_char *
.
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
i have recently start visual studio code and have this issue and just write the exact path of executable git solve the issue .... here is the code ...
"git.path": "C:\Program Files\Git\bin\git.exe",
in python sorted
works like you want with integers:
>>> sorted([10,3,2])
[2, 3, 10]
it looks like you have a problem because you are using strings:
>>> sorted(['10','3','2'])
['10', '2', '3']
(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int
>>> sorted(['10','3','2'], key=int)
['2', '3', '10']
which converts the values to integers during the sort (it is called as a function - int('10')
returns the integer 10
)
and as suggested in the comments, you can also sort the list itself, rather than generating a new one:
>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']
but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).
and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ...
to the sql command:
select temperature from temperatures order by temperature;
For those who still stumble upon this like I did, it's worth checking to make sure the attempted GRANT
does not already exist:
SHOW GRANTS FOR username;
In my case, the error was not actually because there was a permission error, but because the GRANT
already existed.
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
I would recommend start using Lyx, with that you can use Latex just as easy as OOO-Writer. It gives you the possibility to step into Latex deeper by manually adding Latex-Code to your Document. PDF is just one klick away after installatioin. Lyx is cross-plattform.
You have to create a symlink to your mysql installation if it is not the most recent version of mysql.
$ brew link --force [email protected]
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
Why use jQuery for this?
str = "123-4";
alert(str.substring(0,str.length - 1));
Of course if you must:
Substr w/ jQuery:
//example test element
$(document.createElement('div'))
.addClass('test')
.text('123-4')
.appendTo('body');
//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
Here is my own version that handles many validations and relative pathing from user's current location option. Feel free to refactor from here :)
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing
/// the full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string GetAbsoluteUrl(string relativeUrl)
{
//VALIDATE INPUT
if (String.IsNullOrEmpty(relativeUrl))
return String.Empty;
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return relativeUrl;
//VALIDATE CONTEXT
if (HttpContext.Current == null)
return relativeUrl;
//GET CONTEXT OF CURRENT USER
HttpContext context = HttpContext.Current;
//FIX ROOT PATH TO APP ROOT PATH
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
//GET RELATIVE PATH
Page page = context.Handler as Page;
if (page != null)
{
//USE PAGE IN CASE RELATIVE TO USER'S CURRENT LOCATION IS NEEDED
relativeUrl = page.ResolveUrl(relativeUrl);
}
else //OTHERWISE ASSUME WE WANT ROOT PATH
{
//PREPARE TO USE IN VIRTUAL PATH UTILITY
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);
}
var url = context.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
//BUILD AND RETURN ABSOLUTE URL
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, relativeUrl);
}
Why do you need a span in this case? If you want to style the height could you just use a div? You might try a div with display: inline
, although that might have the same issue since you'd in effect be doing the same thing as a span.
A .sql file is a set of commands that can be executed against the SQL server.
Sometimes the .sql file will specify the database, other times you may need to specify this.
You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.
See the other answers if you want to plunge ahead.
Like this:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
Reference: Ruby's Hidden do {} while () Loop
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.
git rm
will only remove the file on this branch from now on, but it remains in history and git will remember it.
The right way to do it is with git filter-branch
, as others have mentioned here. It will rewrite every commit in the history of the branch to delete that file.
But, even after doing that, git can remember it because there can be references to it in reflog, remotes, tags and such.
If you want to completely obliterate it in one step, I recommend you to use git forget-blob
It is easy, just do git forget-blob file1.txt
.
This will remove every reference, do git filter-branch
, and finally run the git garbage collector git gc
to completely get rid of this file in your repo.
You can find a lot of historical data here: https://www.quandl.com/data/BCHARTS-Bitcoin-Charts-Exchange-Rate-Data
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Now I return Object
. I don't know better solution, but it works.
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject Entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
Create/Open ~/.bashrc
file $vim ~/.bashrc
Add JAVA_HOME and PATH as refering to your JDK path
export JAVA_HOME=/usr/java/<your version of java>
export PATH=${PATH}:${JAVA_HOME}/bin
Save file
Now type java - version it should display what you set in .bashrc file. This will persisted over session as wel.
Example :
My understanding is that you actually use script tags with JSONP, sooo...
The first step is to create your function that will handle the JSON:
function hooray(json) {
// dealin wit teh jsonz
}
Make sure that this function is accessible on a global level.
Next, add a script element to the DOM:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
The script will load the JavaScript that the API provider builds, and execute it.
Swift 4 and Constraints
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
You can also do (Get-Service -Name "what ever" - ComputerName RemoteHost).Status = "Stopped"
data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });
(on Windows OS without Service) Spring Boot start/stop sample.
run.bat
@ECHO OFF
IF "%1"=="start" (
ECHO start your app name
start "yourappname" java -jar -Dspring.profiles.active=prod yourappname-0.0.1.jar
) ELSE IF "%1"=="stop" (
ECHO stop your app name
TASKKILL /FI "WINDOWTITLE eq yourappname"
) ELSE (
ECHO please, use "run.bat start" or "run.bat stop"
)
pause
start.bat
@ECHO OFF
call run.bat start
stop.bat:
@ECHO OFF
call run.bat stop
Change your default controller which is in config file.
i.e : config/routes.php
$route['default_controller'] = "Your controller name";
Hope this will help.
It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.
wmic useraccount get name,sid
You can also export this information to CSV:
wmic useraccount get name,sid /format:csv > output.csv
I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.
A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.
tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }
or
tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}
Easily generate random passwords with the help of this JavaScript code. For demo click: How to generate random passwords using JavaScript
JavaScript code:
<script>
const input = document.querySelector("input");
const button = document.querySelector("#passgen");
function GeneratePassword(length = 8) {
const cwb =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$!%^&*()_+=-";
let password = "";
for (let i = 0; i < length; ++i) {
let at = Math.floor(Math.random() * (cwb.length + 1));
password += cwb.charAt(at);
}
return password;
}
button.addEventListener("click", () => {
input.value = GeneratePassword(8);
});
</script>
You can watch your container element using the useRef
hook.
Note that you need to watch the ref
's current
value specifically, otherwise it won't work.
Example:
const containerRef = useRef();
const { current } = containerRef;
useEffect(setLinksData, [current]);
return (
<div ref={containerRef}>
// your child elements...
</div>
)
$($("li").get().reverse()).each(function() { /* ... */ });
Here's my awesome script, it creates a new terminal window if needed and switches to the directory Finder is in if Finder is frontmost. It has all the machinery you need to run commands.
on run
-- Figure out if we want to do the cd (doIt)
-- Figure out what the path is and quote it (myPath)
try
tell application "Finder" to set doIt to frontmost
set myPath to finder_path()
if myPath is equal to "" then
set doIt to false
else
set myPath to quote_for_bash(myPath)
end if
on error
set doIt to false
end try
-- Figure out if we need to open a window
-- If Terminal was not running, one will be opened automatically
tell application "System Events" to set isRunning to (exists process "Terminal")
tell application "Terminal"
-- Open a new window
if isRunning then do script ""
activate
-- cd to the path
if doIt then
-- We need to delay, terminal ignores the second do script otherwise
delay 0.3
do script " cd " & myPath in front window
end if
end tell
end run
on finder_path()
try
tell application "Finder" to set the source_folder to (folder of the front window) as alias
set thePath to (POSIX path of the source_folder as string)
on error -- no open folder windows
set thePath to ""
end try
return thePath
end finder_path
-- This simply quotes all occurrences of ' and puts the whole thing between 's
on quote_for_bash(theString)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to "'"
set the parsedList to every text item of theString
set AppleScript's text item delimiters to "'\\''"
set theString to the parsedList as string
set AppleScript's text item delimiters to oldDelims
return "'" & theString & "'"
end quote_for_bash
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
The V1 git man page had a reference about un-applying a stash. The excerpt is below.
The newer V2 git man page doesn't include any reference to un-applying a stash but the below still works well
Un-applying a Stash In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash. Git does not provide such a stash un-apply command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse:
$ git stash show -p stash@{0} | git apply -R
Again, if you don’t specify a stash, Git assumes the most recent stash:
$ git stash show -p | git apply -R
You may want to create an alias and effectively add a stash-unapply command to your Git. For example:
$ git config --global alias.stash-unapply '!git stash show -p | git apply -R'
$ git stash apply
$ #... work work work
$ git stash-unapply
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null
, as that may cause unexpected behaviour.
var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
Or if you prefer, you can make it a function:
function clearOptions(id)
{
var select = document.getElementById(id);
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
}
clearOptions("myselect");
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120)
Normally you can't refer to field aliases in the WHERE
clause. (Think of it as the entire SELECT
including aliases, is applied after the WHERE
clause.)
But, as mentioned in other answers, you can force SQL to treat SELECT
to be handled before the WHERE
clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):
Parenthesis/Subselect:
SELECT
*
FROM
(
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
) as innerTable
WHERE daysdiff > 120
Or see Adam's answer for a CTE version of the same.
You want to use intvalue = Color.parseColor("#" + colorobject);
system
The system
method calls a system program. You have to provide the command as a string argument to this method. For example:
>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true
The invoked program will use the current STDIN
, STDOUT
and STDERR
objects of your Ruby program. In fact, the actual return value is either true
, false
or nil
. In the example the date was printed through the IO object of STDIN
. The method will return true
if the process exited with a zero status, false
if the process exited with a non-zero status and nil
if the execution failed.
As of Ruby 2.6, passing exception: true
will raise an exception instead of returning false
or nil
:
>> system('invalid')
=> nil
>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)
Another side effect is that the global variable $?
is set to a Process::Status
object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.
>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>
Backticks
Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.
>> `date`
=> Wed Sep 4 22:22:51 CEST 2013
The global variable $?
is set through the backticks, too. With backticks you can also make use string interpolation.
%x()
Using %x
is an alternative to the backticks style. It will return the output, too. Like its relatives %w
and %q
(among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date)
, %x{date}
and %x-date-
are all synonyms. Like backticks %x
can make use of string interpolation.
exec
By using Kernel#exec
the current process (your Ruby script) is replaced with the process invoked through exec
. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.
Open3.popen3
Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3
comes in handy:
require 'open3'
Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
pid = thread.pid
puts stdout.read.chomp
end
You can also use the Get-Counter cmdlet (PowerShell 2.0):
Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'
To get a list of memory counters:
Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter
This is for version 1.4.4
<div data-role="header" >
<h1>CHANGE HOUSE ANIMATION</h1>
<a href="#" data-rel="back" class="ui-btn-left ui-btn ui-icon-back ui-btn-icon-notext ui-shadow ui-corner-all" data-role="button" role="button">Back</a>
</div>
@ViewChild('keywords-input') keywordsInput;
doesn't match id="keywords-input"
id="keywords-input"
should be instead a template variable:
#keywordsInput
Note that camel case should be used, since -
is not allowed in template reference names.
@ViewChild()
supports names of template variables as string:
@ViewChild('keywordsInput') keywordsInput;
or component or directive types:
@ViewChild(MyKeywordsInputComponent) keywordsInput;
See also https://stackoverflow.com/a/35209681/217408
Hint:
keywordsInput
is not set before ngAfterViewInit()
is called
Screen Recording can be done in C# using VLC API. I have done a sample program to demonstrate this. It uses LibVLCSharp and VideoLAN.LibVLC.Windows libraries. You could achieve many more features related to video rendering using this cross platform API.
For API documentation see: LibVLCSharp API Github
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using LibVLCSharp.Shared;
namespace ScreenRecorderNetApp
{
class Program
{
static void Main(string[] args)
{
Core.Initialize();
using (var libVlc = new LibVLC())
using (var mediaPlayer = new MediaPlayer(libVlc))
{
var media = new Media(libVlc, "screen://", FromType.FromLocation);
media.AddOption(":screen-fps=24");
media.AddOption(":sout=#transcode{vcodec=h264,vb=0,scale=0,acodec=mp4a,ab=128,channels=2,samplerate=44100}:file{dst=testvlc.mp4}");
media.AddOption(":sout-keep");
mediaPlayer.Play(media);
Thread.Sleep(10*1000);
mediaPlayer.Stop();
}
}
}
}
I am looking for this kind of solution for my self as well. I found reference in terms aggregation.
So, according to that following is the proper solution.
{
"aggs" : {
"langs" : {
"terms" : { "field" : "language",
"size" : 500 }
}
}}
But if you ran into following error:
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
}
]}
In that case, you have to add "KEYWORD" in the request, like following:
{
"aggs" : {
"langs" : {
"terms" : { "field" : "language.keyword",
"size" : 500 }
}
}}
There is no equivalent in VB.NET that I could find. For this piece of code you are probably going to want to open it in Reflector and change the output type to VB to get the exact copy of the code that you need. For instance when I put the following in to Reflector:
switch (args[0])
{
case "UserID":
Console.Write("UserID");
break;
case "PackageID":
Console.Write("PackageID");
break;
case "MVRType":
if (args[1] == "None")
Console.Write("None");
else
goto default;
break;
default:
Console.Write("Default");
break;
}
it gave me the following VB.NET output.
Dim CS$4$0000 As String = args(0)
If (Not CS$4$0000 Is Nothing) Then
If (CS$4$0000 = "UserID") Then
Console.Write("UserID")
Return
End If
If (CS$4$0000 = "PackageID") Then
Console.Write("PackageID")
Return
End If
If ((CS$4$0000 = "MVRType") AndAlso (args(1) = "None")) Then
Console.Write("None")
Return
End If
End If
Console.Write("Default")
As you can see you can accomplish the same switch case statement with If statements. Usually I don't recommend this because it makes it harder to understand, but VB.NET doesn't seem to support the same functionality, and using Reflector might be the best way to get the code you need to get it working with out a lot of pain.
Update:
Just confirmed you cannot do the exact same thing in VB.NET, but it does support some other useful things. Looks like the IF statement conversion is your best bet, or maybe some refactoring. Here is the definition for Select...Case
There is a new feature on ES6+ that you can check it like below:
if (x?.y)
Actually, the interpretor checks the existence of x
and then call the y
and because of putting inside if
parentheses the coercion happens and x?.y
converted to boolean.
This is a better code that will help you through.
With your database, but rather, I have used mysql not mysqli
Enjoy it.
<body>
<form action="" method="post">
<input name="search" type="search" autofocus><input type="submit" name="button">
</form>
<table>
<tr><td><b>First Name</td><td></td><td><b>Last Name</td></tr>
<?php
$con=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('employee');
if(isset($_POST['button'])){ //trigger button click
$search=$_POST['search'];
$query=mysql_query("select * from employees where first_name like '%{$search}%' || last_name like '%{$search}%' ");
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
}
}else{
echo "No employee Found<br><br>";
}
}else{ //while not in use of search returns all the values
$query=mysql_query("select * from employees");
while ($row = mysql_fetch_array($query)) {
echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
}
}
mysql_close();
?>
If there are two elements element 1 and element 2. Element 2 is inside element 1 and we attach an event handler with both the elements lets say onClick. Now when we click on element 2 then eventHandler for both the elements will be executed. Now here the question is in which order the event will execute. If the event attached with element 1 executes first it is called event capturing and if the event attached with element 2 executes first this is called event bubbling. As per W3C the event will start in the capturing phase until it reaches the target comes back to the element and then it starts bubbling
The capturing and bubbling states are known by the useCapture parameter of addEventListener method
eventTarget.addEventListener(type,listener,[,useCapture]);
By Default useCapture is false. It means it is in the bubbling phase.
var div1 = document.querySelector("#div1");_x000D_
var div2 = document.querySelector("#div2");_x000D_
_x000D_
div1.addEventListener("click", function (event) {_x000D_
alert("you clicked on div 1");_x000D_
}, true);_x000D_
_x000D_
div2.addEventListener("click", function (event) {_x000D_
alert("you clicked on div 2");_x000D_
}, false);
_x000D_
#div1{_x000D_
background-color:red;_x000D_
padding: 24px;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
background-color:green;_x000D_
}
_x000D_
<div id="div1">_x000D_
div 1_x000D_
<div id="div2">_x000D_
div 2_x000D_
</div>_x000D_
</div>
_x000D_
Please try with changing true and false.
None of the above answers worked for me. I kept getting this error:
Copy-Item : Access is denied
+ CategoryInfo : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
So this did it for me:
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes
Then from my host my machine in the Run box I just did this:
\\{IP address of nanoserver}\C$
I have been looking at the answers all impressive. I think He should provide the code that is giving him a problem. Given the example below, If you have a script to link to jquery in page.php then you get that notice.
$().ready(function () {
$.ajax({url: "page.php",
type: 'GET',
success: function (result) {
$("#page").html(result);
}});
});
A one-liner using ES6 arrow function and ternary operator:
Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});
Or use short-circuit evaluation instead of ternary: (@Matt Langlois, thanks for the info!)
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])
Same example using if statement:
Object.keys(obj).forEach(key => {
if (obj[key] === undefined) {
delete obj[key];
}
});
If you want to remove the items from nested objects as well, you can use a recursive function:
const removeEmpty = (obj) => {
let newObj = {};
Object.keys(obj).forEach((key) => {
if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
else if (obj[key] !== undefined) newObj[key] = obj[key];
});
return newObj;
};
string.replaceAll() doesn't correctly work with locale different from predefined. At least in jdk7u10.
This example creates a word dictionary from textfile with windows cyrillic charset CP1251
public static void main (String[] args) {
String fileName = "Tolstoy_VoinaMir.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.forName("CP1251"));
Set<String> words = new TreeSet<>();
for (String s: lines ) {
for (String w : s.split("\\s+")) {
w = w.replaceAll("\\p{Punct}","");
words.add(w);
}
}
for (String w: words) {
System.out.println(w);
}
} catch (Exception e) {
e.printStackTrace();
}
May be I'm too late here. But I hope this would help someone. First separate those two elements.
renderLogout(){
<div>
<LogoutButton onClick={this.handleLogoutClick} />
<div>
}
renderLogin(){
<div>
<LoginButton onClick={this.handleLoginClick} />
<div>
}
Then you can call these functions from render function using if else statement.
render(){
if(this.state.result){
return this.renderResult();
}else{
return this.renderQuiz();
}}
This works for me. :)
public static T Runner<T>(Func<T> funcToRun)
{
//Do stuff before running function as normal
return funcToRun();
}
Usage:
var ReturnValue = Runner(() => GetUser(99));
The problem is that you have a circular import: in app.py
from mod_login import mod_login
in mod_login.py
from app import app
This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
Here is what I write to get the timestamp in millionseconds.
#include<sys/time.h>
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
If none of the above solutions are working, try manually adding "http://" to the beginning of the url.
Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).
How about pdf2tiff? http://python.net/~gherman/pdf2tiff.html
SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.
Go to (Menu) VIEW -> Dbms_output to invoke the pane.
Click on the Green Plus sign to enable output for your connection and then run the code.
EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.
script(nonce="some-nonce").
console.log("test");
//- Workaround
<script nonce="some-nonce">console.log("test");</script>
Try converting to a string and then use "%4.4s" as the format specifier. This makes it a fixed width format.
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.
Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:
RepeatingOperation = function(op, yieldEveryIteration) {
//keeps count of how many times we have run heavytask()
//before we need to temporally check back with the browser.
var count = 0;
this.step = function() {
//Each time we run heavytask(), increment the count. When count
//is bigger than the yieldEveryIteration limit, pass control back
//to browser and instruct the browser to immediately call op() so
//we can pick up where we left off. Repeat until we are done.
if (++count >= yieldEveryIteration) {
count = 0;
//pass control back to the browser, and in 1 millisecond,
//have the browser call the op() function.
setTimeout(function() { op(); }, 1, [])
//The following return statement halts this thread, it gives
//the browser a sigh of relief, your long-running javascript
//loop has ended (even though technically we havn't yet).
//The browser decides there is no need to alarm the user of
//an unresponsive javascript process.
return;
}
op();
};
};
Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:
process10000HeavyTasks = function() {
var len = 10000;
for (var i = len - 1; i >= 0; i--) {
heavytask(); //heavytask() can be run about 20 times before
//an 'unresponsive script' dialog appears.
//If heavytask() is run more than 20 times in one
//javascript thread, the browser informs the user that
//an unresponsive script needs to be dealt with.
//This is where we need to terminate this long running
//thread, instruct the browser not to panic on an unresponsive
//script, and tell it to call us right back to pick up
//where we left off.
}
}
Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()
process10000HeavyTasks = function() {
var global_i = 10000; //initialize your 'for loop stepper' (i) here.
var repeater = new this.RepeatingOperation(function() {
heavytask();
if (--global_i >= 0){ //Your for loop conditional goes here.
repeater.step(); //while we still have items to process,
//run the next iteration of the loop.
}
else {
alert("we are done"); //when this line runs, the for loop is complete.
}
}, 10); //10 means process 10 heavytask(), then
//yield back to the browser, and have the
//browser call us right back.
repeater.step(); //this command kicks off the recursive closure.
};
Adapted from this source:
Here's what I initially did, which does work, however it seems rather long-winded and ugly (global static anything is never good)
1: App.xaml.cs
public partial class App : Application
{
// create a new global custom WPF Command
public static readonly RoutedUICommand LoggedIn = new RoutedUICommand();
}
2: LoginForm.xaml
// bind the global command to a local eventhandler
<CommandBinding Command="client:App.LoggedIn" Executed="OnLoggedIn" />
3: LoginForm.xaml.cs
// implement the local eventhandler in codebehind
private void OnLoggedIn( object sender, ExecutedRoutedEventArgs e )
{
DialogResult = true;
Close();
}
4: LoginFormViewModel.cs
// fire the global command from the viewmodel
private void OnRemoteServerReturnedSuccess()
{
App.LoggedIn.Execute(this, null);
}
I later on then removed all this code, and just had the LoginFormViewModel
call the Close method on it's view. It ended up being much nicer and easier to follow. IMHO the point of patterns is to give people an easier way to understand what your app is doing, and in this case, MVVM was making it far harder to understand than if I hadn't used it, and was now an anti-pattern.
the awk answer
awk -v n=8 -v s="Project_Name=sowstest" 'NR == n {print s} {print}' file > file.new
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
Interfaces are a way to make your code more flexible. What you do is this:
Ibox myBox=new Rectangle();
Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:
Ibox myBox=new OtherKindOfBox();
Once you get used to it, you'll find it's a great (actually essential) way to work.
Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:
myBox.close()
(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.
h1 {
font-weight: bold;
color: #fff;
font-size: 32px;
}
h2 {
font-weight: bold;
color: #fff;
font-size: 24px;
}
Note that after color you can use a word (e.g. white
), a hex code (e.g. #fff
) or RGB (e.g. rgb(255,255,255)
) or RGBA (e.g. rgba(255,255,255,0.3)
).
<Program files>\Android\Android-sdk\platforms\<platform SDK's>
On a 32bit machine:
"<Program files>
" will be \Program Files\
On a 64bit machine:
If you installed the 32bit ADT, "<Program files>
" will be \Program Files (x86)\
If you installed the 64bit ADT, "<Program files>
" will be \Program Files\
No.
You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
I solved the rowlock problem in a completely different way. I realized that sql server was not able to manage such a lock in a satisfying way. I choosed to solve this from a programatically point of view by the use of a mutex... waitForLock... releaseLock...
Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.
This question explicitly mentions Bash, but if you happen to have ZSH available it is pretty simple:
zmv '(*).*' '$1.txt'
If you get zsh: command not found: zmv
then simply run:
autoload -U zmv
And then try again.
Thanks to this original article for the tip about zmv.
Yes, just a syntax problem. Try this instead:
if (reader["usr.ursrdaystime"] != DBNull.Value)
.Equals()
is checking to see if two Object instances are the same.
There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...
Manual initialisation of all elements in loop
int* p = new int[10];
for (int i = 0; i < 10; i++)
p[i] = 0;
Using std::memset
function from <cstring>
int* p = new int[10];
std::memset(p, 0, sizeof *p * 10);
Using std::fill_n
algorithm from <algorithm>
int* p = new int[10];
std::fill_n(p, 10, 0);
Using std::vector
container
std::vector<int> v(10); // elements zero'ed
If C++11 is available, using initializer list features
int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime
The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1
Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%
If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
If you want to print the array like you print a 2D list in Python:
#include <stdio.h>
int main()
{
int i, j;
int my_array[3][3] = {{10, 23, 42}, {1, 654, 0}, {40652, 22, 0}};
for(i = 0; i < 3; i++)
{
if (i == 0) {
printf("[");
}
printf("[");
for(j = 0; j < 3; j++)
{
printf("%d", my_array[i][j]);
if (j < 2) {
printf(", ");
}
}
printf("]");
if (i == 2) {
printf("]");
}
if (i < 2) {
printf(", ");
}
}
return 0;
}
Output will be:
[[10, 23, 42], [1, 654, 0], [40652, 22, 0]]
To generate a random number between min and max, use:
int randNum = rand()%(max-min + 1) + min;
(Includes max and min)
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
Try the DocumentCompleted Event
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser.Document.GetElementById("product").SetAttribute("value", product);
webBrowser.Document.GetElementById("version").SetAttribute("value", version);
webBrowser.Document.GetElementById("commit").InvokeMember("click");
}
Yes! And another solution. My solution differs in the keys that are being checked.
In all other solutions we only look at the keys in dict_b
. But here we look in the union of both dictionaries.
Do with it as you please
def update_nested(dict_a, dict_b):
set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
for k in set_keys:
v = dict_a.get(k)
if isinstance(v, dict):
new_dict = dict_b.get(k, None)
if new_dict:
update_nested(v, new_dict)
else:
new_value = dict_b.get(k, None)
if new_value:
dict_a[k] = new_value
FLAG_ACTIVITY_NEW_TASK is the problem here which initiates a new task .Just remove it & you are done.
Well I recommend you to read what every Flag does before working with them
Read this & Intent Flags here
To edit text in the file non-interactively, you need in-place text editor such as vim.
Here is simple example how to use it from the command line:
vim -esnc '%s/foo/bar/g|:wq' file.txt
This is equivalent to @slim answer of ex editor which is basically the same thing.
Here are few ex
practical examples.
Replacing text foo
with bar
in the file:
ex -s +%s/foo/bar/ge -cwq file.txt
Removing trailing whitespaces for multiple files:
ex +'bufdo!%s/\s\+$//e' -cxa *.txt
Troubleshooting (when terminal is stuck):
-V1
param to show verbose messages.-cwq!
.See also:
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
select * from information_schema.columns
could get you started.
My solution in this listing:
List<HolderEntry> result ....
List<HolderEntry> dto3s = new ArrayList<>(result.stream().collect(toMap(
HolderEntry::getId,
holder -> holder, //or Function.identity() if you want
(holder1, holder2) -> holder1
)).values());
In my situation i want to find distinct values and put their in List.
I had a similar problem, but the accepted answer did not resolve it - I was not using a virtual environment. This is what I had to do:
sudo python -m pip install boto3
I do not know why this behaved differently from sudo pip install boto3
.
As other people have commented, because the return type of your method is String
Spring won't feel need to do anything with the result.
If you change your signature so that the return type is something that needs marshalling, that should help:
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> bar() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("test", "jsonRestExample");
return map;
}
A much simpler solution, without all the inside form-group
elements
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<input type="text" class="form-control" placeholder="year" style="width:70px;"/>
<input type="text" class="form-control" placeholder="month" style="width:80px;"/>
<input type="text" class="form-control" placeholder="day" style="width:100px;"/>
</div>
</div>
</div>
... and it will look like this,
Cheers!
This should work
<option *ngFor="let title of titleArray"
[value]="title.Value"
[attr.selected]="passenger.Title==title.Text ? true : null">
{{title.Text}}
</option>
I'm not sure the attr.
part is necessary.
Let's say you have two models, one named Person and another one named Companies.
By definition, one person can create more than one company.
Considering a company can have one and only one person, we want that when a person is deleted that all the companies associated with that person also be deleted.
So, we start by creating a Person model, like this
class Person(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
def __str__(self):
return self.id+self.name
Then, the Companies model can look like this
class Companies(models.Model):
title = models.CharField(max_length=20)
description=models.CharField(max_length=10)
person= models.ForeignKey(Person,related_name='persons',on_delete=models.CASCADE)
Notice the usage of on_delete=models.CASCADE
in the model Companies. That is to delete all companies when the person that owns it (instance of class Person) is deleted.
Why don't use the require resolve...
const packageJson = path.dirname(require.resolve('package-name')) + '/package.json';
const { version } = require(packageJson);
console.log('version', version)
With this approach work for all sub paths :)
wmic
can call an uninstaller. I haven't tried this, but I think it might work.
wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall
If you don't know exactly what the program calls itself, do
wmic product get name | sort
and look for it. You can also uninstall using SQL-ish wildcards.
wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall
... for example would perform a case-insensitive search for *j2se*
and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se%
is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%
.)
If wmic prompts for y/n
confirmation before completing the uninstall, try this:
echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall
... to pass a y
to it before it even asks.
I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.
The logic is not flawed. The statement
if x is y then x==y is also True
should never be read to mean
if x==y then x is y
It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)
If you'd want to generate multiple numbers using one seed you can do something like this:
public double[] GenerateNumbers(long seed, int amount) {
double[] randomList = new double[amount];
for (int i=0;i<amount;i++) {
Random generator = new Random(seed);
randomList[i] = Math.abs((double) (generator.nextLong() % 0.001) * 10000);
seed--;
}
return randomList;
}
It will display the same list if you use the same seed.
One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML
literal to the SELECT
clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet.
example
SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;
you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.
Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:
why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.
Solution:
check write permissions on registers
a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it
b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log
c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"
d. run the following command netsh int ipv6 reset reset.log
and repeat step c)
unistall all not-working miniports
a. go to device managers (windows+x -> device manager)
b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)
c. unistall these not working devices
d. reboot your computer
e. Repeat steps a) - d) until you will not see any yellow mark on miniports
delete your vpn connection and create a new one.
that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)
references:
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
I cribbed this and added the 'px'; Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;
If you have a list of column names in data.table, you want to change the class of do:
convert_to_character <- c("Quarter", "value")
dt[, convert_to_character] <- dt[, lapply(.SD, as.character), .SDcols = convert_to_character]