In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
This should work for your case;
assert not my_var.called, 'method should not have been called'
Sample;
>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
Because the compiled JavaScript has all the type information erased, you can't use T
to new up an object.
You can do this in a non-generic way by passing the type into the constructor.
class TestOne {
hi() {
alert('Hi');
}
}
class TestTwo {
constructor(private testType) {
}
getNew() {
return new this.testType();
}
}
var test = new TestTwo(TestOne);
var example = test.getNew();
example.hi();
You could extend this example using generics to tighten up the types:
class TestBase {
hi() {
alert('Hi from base');
}
}
class TestSub extends TestBase {
hi() {
alert('Hi from sub');
}
}
class TestTwo<T extends TestBase> {
constructor(private testType: new () => T) {
}
getNew() : T {
return new this.testType();
}
}
//var test = new TestTwo<TestBase>(TestBase);
var test = new TestTwo<TestSub>(TestSub);
var example = test.getNew();
example.hi();
From my article on Automating Docker Deployments:
In Dockerland, there are images and there are containers. The two are closely related, but distinct. For me, grasping this dichotomy has clarified Docker immensely.
An image is an inert, immutable, file that's essentially a snapshot of a container. Images are created with the build command, and they'll produce a container when started with run. Images are stored in a Docker registry such as registry.hub.docker.com. Because they can become quite large, images are designed to be composed of layers of other images, allowing a minimal amount of data to be sent when transferring images over the network.
Local images can be listed by running docker images
:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
ubuntu 13.10 5e019ab7bf6d 2 months ago 180 MB
ubuntu 14.04 99ec81b80c55 2 months ago 266 MB
ubuntu latest 99ec81b80c55 2 months ago 266 MB
ubuntu trusty 99ec81b80c55 2 months ago 266 MB
<none> <none> 4ab0d9120985 3 months ago 486.5 MB
Some things to note:
-t
flag of the docker build
command, or from docker tag
-ing an existing image. You're free to tag images using a nomenclature that makes sense to you, but know that docker will use the tag as the registry location in a docker push
or docker pull
.[REGISTRYHOST/][USERNAME/]NAME[:TAG]
. For ubuntu
above, REGISTRYHOST is inferred to be registry.hub.docker.com
. So if you plan on storing your image called my-application
in a registry at docker.example.com
, you should tag that image docker.example.com/my-application
.latest
tag is not magical, it's simply the default tag when you don't specify a tag.<none>
TAG and REPOSITORY. It's easy to forget about them.More information on images is available from the Docker documentation and glossary.
To use a programming metaphor, if an image is a class, then a container is an instance of a class—a runtime object. Containers are hopefully why you're using Docker; they're lightweight and portable encapsulations of an environment in which to run applications.
View local running containers with docker ps
:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f2ff1af05450 samalba/docker-registry:latest /bin/sh -c 'exec doc 4 months ago Up 12 weeks 0.0.0.0:5000->5000/tcp docker-registry
Here I'm running a dockerized version of the docker registry, so that I have a private place to store my images. Again, some things to note:
docker ps
only outputs running containers. You can view all containers (running or stopped) with docker ps -a
.--name
flag.One of my early frustrations with Docker was the seemingly constant buildup of untagged images and stopped containers. On a handful of occasions this buildup resulted in maxed out hard drives slowing down my laptop or halting my automated build pipeline. Talk about "containers everywhere"!
We can remove all untagged images by combining docker rmi
with the recent dangling=true
query:
docker images -q --filter "dangling=true" | xargs docker rmi
Docker won't be able to remove images that are behind existing containers, so you may have to remove stopped containers with docker rm
first:
docker rm `docker ps --no-trunc -aq`
These are known pain points with Docker and may be addressed in future releases. However, with a clear understanding of images and containers, these situations can be avoided with a couple of practices:
docker rm [CONTAINER_ID]
.docker rmi [IMAGE_ID]
.Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.
Also the language attribute is Deprecated.
See Scripts:
18.2.1 The SCRIPT element
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
Edit
Try changing
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" />
to
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>
In terms of WCF, we can communicate with the server and client through messages. For transferring messages, and from a security prospective, we need to make a data/message in a serialized format.
For serializing data we use [datacontract] and [datamember] attributes.
In your case if you are using datacontract
WCF uses DataContractSerializer
else WCF uses XmlSerializer
which is the default serialization technique.
Let me explain in detail:
basically WCF supports 3 types of serialization:
XmlSerializer :- Default order is Same as class
DataContractSerializer/NetDataContractSerializer :- Default order is Alphabetical
XmlSerializer :- XML Schema is Extensive
DataContractSerializer/NetDataContractSerializer :- XML Schema is Constrained
XmlSerializer :- Versioning support not possible
DataContractSerializer/NetDataContractSerializer :- Versioning support is possible
XmlSerializer :- Compatibility with ASMX
DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting
XmlSerializer :- Attribute not required in XmlSerializer
DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing
so what you use depends on your requirements...
I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l
the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a
.
If you want something slightly more general, you can use the arguments variable like so:
function tryMe (param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester (callback) {
callback (arguments[1], arguments[2]);
}
callbackTester (tryMe, "hello", "goodbye");
But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
As mentioned in the above answer, by updating the bashrc file you can run the pycharm.sh from anywhere on the linux terminal.
But if you love the icon and wants the Desktop shortcuts for the Pycharm on Ubuntu OS then follow the Below steps,
Quick way to create Pycharm launcher.
1. Start Pycharm using the pycharm.sh cmd from anywhere on the terminal or start the pycharm.sh located under bin folder of the pycharm artifact.
2. Once the Pycharm application loads, navigate to tools menu and select “Create Desktop Entry..”
3. Check the box if you want the launcher for all users.
4. If you Check the box i.e “Create entry for all users”, you will be asked for your password.
5. A message should appear informing you that it was successful.
6. Now Restart Pycharm application and you will find Pycharm in Unity dash and Application launcher.."
Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it
CASE
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
Try this:
select distinct a.FirstName, a.LastName, v.District
from AddTbl a
inner join ValTbl v
on a.LastName = v.LastName
order by a.FirstName;
Or this (it does the same, but the syntax is different):
select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;
pg_hba.conf
entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf
in order to get proper help.
Change this line:
host all all <my-ip-address>/32 md5
To reflect your local network settings. So, if your IP is 192.168.16.78
(class C) with a mask of 255.255.255.0
, then put this:
host all all 192.168.16.0/24 md5
Make sure your WINDOWS MACHINE is in that network 192.168.16.0
and try again.
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
I had the same error and could not figure it out with the other answers. I found that we can "Consolidate" NuGet packages.
Here it is:
rfc2616#section-10.4.1 - 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
rfc7231#section-6.5.1 - 6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Refers to malformed (not wellformed) cases!
rfc4918 - 11.2. 422 Unprocessable Entity
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Conclusion
Rule of thumb: [_]00 covers the most general case and cases that are not covered by designated code.
422 fits best object validation error (precisely my recommendation:)
As for semantically erroneous - Think of something like "This username already exists" validation.
400 is incorrectly used for object validation
I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.
Search your Start Menu for "powershell", and find the entry that ends in "(x86)":
Here is what I experience between the two different versions:
This is just debugging message. You can switch that off by right clicking into the output window and uncheck Thread Exit Messages
.
http://msdn.microsoft.com/en-us/library/bs4c1wda.aspx
In addition to program out from your application, the Output window can display the information about:
Modules the debugger has loaded or unloaded.
Exceptions that are thrown.
Processes that exit.
Threads that exit.
/^[a-zA-Z]*$/
Change the *
to +
if you don't want to allow empty matches.
Character classes ([...]
), Anchors (^
and $
), Repetition (+
, *
)
The /
are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
The following (C#) code should do the trick
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Using executeUpdate()
on the Query
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");
Here is my code based off the code offered by @Ahmed ALaa
Features:
*
character (DEC: 42 ; HEX: 0x2A)
instead of the input characterDemerits:
The function secure_password_input()
returns the password as a string
when called. It accepts a Password Prompt string, which will be displayed to the user to type the password
def secure_password_input(prompt=''):
p_s = ''
proxy_string = [' '] * 64
while True:
sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
c = msvcrt.getch()
if c == b'\r':
break
elif c == b'\x08':
p_s = p_s[:-1]
proxy_string[len(p_s)] = " "
else:
proxy_string[len(p_s)] = "*"
p_s += c.decode()
sys.stdout.write('\n')
return p_s
The API changed since this commit, using version 1.4.1 it's now
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
The bellow link contains the code that read a piece of file easily:
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
I've got a similar error when installing FCL that needs CCD lib(libccd) like this:
/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC
I find that there is two different files named "libccd.a" :
I solved the problem by removing the first file.
Proper and Cleanest way
After checking the answers below, it seems that they're kind of hacks that rely on editing the login button view to make it more suitable for your need.
Being in the same position, I've succeeded to customize the facebook login button efficiently.
<mehdi.sakout.fancybuttons.FancyButton
android:id="@+id/facebook_login"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:fb_radius="2dp"
app:fb_iconPosition="left"
app:fb_fontIconSize="20sp"
app:fb_iconPaddingRight="10dp"
app:fb_textSize="16sp"
app:fb_text="Facebook Connect"
app:fb_textColor="#ffffff"
app:fb_defaultColor="#39579B"
app:fb_focusColor="#6183d2"
app:fb_fontIconResource=""
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
and implement the onClickListener like so
FacebookLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (AccessToken.getCurrentAccessToken() != null){
mLoginManager.logOut();
} else {
mAccessTokenTracker.startTracking();
mLoginManager.logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));
}
}
});
You could find the whole source code on: http://medyo.github.io/customize-the-android-facebook-login-on-android
.parent {
display: table;
table-layout: fixed;
}
.child {
display:table-cell;
vertical-align:middle;
text-align:center;
}
table-layout: fixed
prevents breaking the functionality of the col-* classes.
If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions that get called by array.filter() is messy and less maintainable than the alternative.
Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:
// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
db = fdb.db('myTestDatabase'),
coll;
// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});
// Insert our records into the collection
coll.insert([
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]);
// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
name: /my nam/i
});
console.log(searchResultArray);
/* Outputs
[
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]
*/
Disclaimer: I am the developer of ForerunnerDB.
The thing about margins is that you don't need to worry about the element's width.
Like when you give something {padding: 10px;}
, you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.
So I generally start off by using paddings to get everything 'packed
' and then use margins for minor tweaks.
Another thing to be aware of is that paddings are more consistent on different browsers and IE doesn't treat negative margins very well.
index.html (index.html should be in templates folder)
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>
</html>
test.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"
if __name__ == '__main__':
app.run()
public static void Main(string[] args)
{
Int[] array = {10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};
List<int> doneNumbers = new List<int>();
for (int i = 0; i < array.Length - 1; i++)
{
if(!doneNumbers.Contains(array[i]))
{
int currentNumber = array[i];
int count = 0;
for (int j = i; j < array.Length; j++)
{
if(currentNumber == array[j])
{
count++;
}
}
Console.WriteLine("\t\n " + currentNumber +" "+ " occurs " + " "+count + " "+" times");
doneNumbers.Add(currentNumber);
Console.ReadKey();
}
}
}
}
}
if you want the original style of your Ui to remain and the title bar to be removed with no effect on that, you have to remove the title bar in your activity rather than the manifest. leave the original theme style that you had in the manifest and in each activity that you want no title bar use this.requestWindowFeature(Window.FEATURE_NO_TITLE);
in the oncreate()
method before setcontentview()
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_signup);
...
}
The problem with your conditional is in this part sshkey_result.rc == 1
, because sshkey_result
does not contain rc
attribute and entire conditional fails.
If you want to check if file exists check exists
attribute.
Here you can read more about stat module and how to use it.
An idea would be that display:flex;
with flex-direction: row;
is filling the container
div with .flex-1
and .flex-2
, but that does not mean that .flex-2
has a default height:100%;
, even if it is extended to full height.
And to have a child element (.flex-2-child
) with height:100%;
, you'll need to set the parent to height:100%;
or use display:flex;
with flex-direction: row;
on the .flex-2
div too.
From what I know, display:flex
will not extend all your child elements height to 100%.
A small demo, removed the height from .flex-2-child
and used display:flex;
on .flex-2
:
http://jsfiddle.net/2ZDuE/3/
The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:
IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }
and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:
modelBuilder.Entity<TUserRole>()
.HasKey(r => new {r.UserId, r.RoleId})
.ToTable("AspNetUserRoles");
modelBuilder.Entity<TUserLogin>()
.HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
.ToTable("AspNetUserLogins");
and as your DXContext doesn't derive from it, those keys don't get defined.
If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework
, you will understand everything.
I came across this situation some time ago, and I found three possible solutions (maybe there are more):
Option 1: See update the bottom.
Option 2: You will end up with a DbContext like this one:
public class DXContext : IdentityDbContext<User, Role,
int, UserLogin, UserRole, UserClaim>//: DbContext
{
public DXContext()
: base("name=DXContext")
{
Database.SetInitializer<DXContext>(null);// Remove default initializer
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public static DXContext Create()
{
return new DXContext();
}
//Identity and Authorization
public DbSet<UserLogin> UserLogins { get; set; }
public DbSet<UserClaim> UserClaims { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
// ... your custom DbSets
public DbSet<RoleOperation> RoleOperations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// Configure Asp Net Identity Tables
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);
modelBuilder.Entity<Role>().ToTable("Role");
modelBuilder.Entity<UserRole>().ToTable("UserRole");
modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
}
}
Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:
public class DXContext : DbContext
{
public DXContext()
: base("name=DXContext") // connection string in the application configuration file.
{
Database.SetInitializer<DXContext>(null); // Remove default initializer
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
// Domain Model
public DbSet<User> Users { get; set; }
// ... other custom DbSets
public static DXContext Create()
{
return new DXContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
modelBuilder.Entity<User>().ToTable("User");
}
public DbQuery<T> Query<T>() where T : class
{
return Set<T>().AsNoTracking();
}
}
where User is:
public class User
{
public int Id { get; set; }
[Required, StringLength(100)]
public string Name { get; set; }
[Required, StringLength(128)]
public string SomeOtherColumn { get; set; }
}
With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.
Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts
You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:
//CreateTable(
// "dbo.User",
// c => new
// {
// Id = c.Int(nullable: false, identity: true),
// Name = c.String(nullable: false, maxLength: 100),
// SomeOtherColumn = c.String(nullable: false, maxLength: 128),
// })
// .PrimaryKey(t => t.Id);
AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));
and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:
public static class DXDatabaseMigrator
{
public static string ExecuteMigrations()
{
return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
ExecuteDXMigrations());
}
private static string ExecuteIdentityMigrations()
{
IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
return RunMigrations(configuration);
}
private static string ExecuteDXMigrations()
{
DXMigrationConfiguration configuration = new DXMigrationConfiguration();
return RunMigrations(configuration);
}
private static string RunMigrations(DbMigrationsConfiguration configuration)
{
List<string> pendingMigrations;
try
{
DbMigrator migrator = new DbMigrator(configuration);
pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed
if (pendingMigrations.Any())
migrator.Update();
}
catch (Exception e)
{
ExceptionManager.LogException(e);
return e.Message;
}
return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
}
}
This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.
Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.
UPDATE: Expand Option 1
For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:
public class AppUser : TrackableEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
// This Id is equal to the Id in the AspNetUser table and it's manually set.
public override int Id { get; set; }
(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)
I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:
IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);
if (!identityResult.Succeeded)
throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));
AppUser appUser;
try
{
appUser = RegisterInAppUserTable(model, aspNetUser);
}
catch (Exception)
{
// Roll back
UserManager.Delete(aspNetUser);
throw;
}
(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)
The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):
public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
public IdentityMigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(IdentityContext context)
{
}
}
This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.
Use collectl
which has extensive process I/O monitoring including monitoring threads.
Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl
reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html
Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?
You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
EDIT: You can also get and set query parameters with the $location service (available in ng
), particularly its search
method: $location.search().
$routeParams are less useful after the controller's initial load; $location.search()
can be called anytime.
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
you can use this method : https://stackoverflow.com/a/31804061/3343174 it's converting perfectly any hexadecimal number (presented as a string) to a decimal number
With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string
literal operator.
using namespace std::string_literals;
auto const x = "\0" "0"s;
Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char>
constructor approach, but it at least gets rid of the '
and ,
characters.
Assuming that your branch is called master
both here and remotely, and that your remote is called origin
you could do:
git reset --hard <commit-hash>
git push -f origin master
However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.
Here is another simple solution using sed.
$ sed -i 's/all.*/& anotherthing/g' filename.txt
Explanation:
all.* means all lines started with 'all'.
& represent the match (ie the complete line that starts with 'all')
then sed replace the former with the later and appends the ' anotherthing' word
Repeat >> reads in loop.
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
Result:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
If you know exactly, how many elements there are in a file, you can chain >> operator:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
Edit: In response to your comments in main question.
You have two options.
Edit: How to skip values in file
To choose the 1234th value, use the following code:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
So if you had an enum named mood it would look like this:
enum Mood
{
Angry,
Happy,
Sad
}
// ...
Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
Console.WriteLine("My mood is: {0}", m.ToString());
You could try the following in your root directory:
// initialize git for your project, add the changes and perform a commit
git init
git add .
git commit -m "first commit"
// create heroku app and push to heroku
heroku create
git push heroku master
Not sure where you are in the process. You also don't need github to deploy on heroku, just git. Hope this helps!
If you are using Restangular (which is awesome) you can create an animation during api calls. Here is my solution. Add a response interceptor and a request interceptor that sends out a rootscope broadcast. Then create a directive to listen for that response and request.:
angular.module('mean.system')
.factory('myRestangular',['Restangular','$rootScope', function(Restangular,$rootScope) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost:3000/api');
RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === 'getList') {
// .. and handle the data and meta data
extractedData = data.data;
extractedData.meta = data.meta;
} else {
extractedData = data.data;
}
$rootScope.$broadcast('apiResponse');
return extractedData;
});
RestangularConfigurer.setRequestInterceptor(function (elem, operation) {
if (operation === 'remove') {
return null;
}
return (elem && angular.isObject(elem.data)) ? elem : {data: elem};
});
RestangularConfigurer.setRestangularFields({
id: '_id'
});
RestangularConfigurer.addRequestInterceptor(function(element, operation, what, url) {
$rootScope.$broadcast('apiRequest');
return element;
});
});
}]);
Here is the directive:
angular.module('mean.system')
.directive('smartLoadingIndicator', function($rootScope) {
return {
restrict: 'AE',
template: '<div ng-show="isAPICalling"><p><i class="fa fa-gear fa-4x fa-spin"></i> Loading</p></div>',
replace: true,
link: function(scope, elem, attrs) {
scope.isAPICalling = false;
$rootScope.$on('apiRequest', function() {
scope.isAPICalling = true;
});
$rootScope.$on('apiResponse', function() {
scope.isAPICalling = false;
});
}
};
})
;
Have a read of Geo Distance Search with MySQL, a solution based on implementation of Haversine Formula to MySQL. This is a complete solution description with theory, implementation and further performance optimization. Although the spatial optimization part didn't work correctly in my case.
I noticed two mistakes in this:
the use of abs
in the select statement on p8. I just omitted abs
and it worked.
the spatial search distance function on p27 does not convert to radians or multiply longitude by cos(latitude)
, unless his spatial data is loaded with this in consideration (cannot tell from context of article), but his example on p26 indicates that his spatial data POINT
is not loaded with radians or degrees.
Using .innerText
should work.
document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
The question does not make clear what exactly you want to achieve.
List has the append
method, which appends its argument to the list:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
There's also the extend
method, which appends items from the list you pass as an argument:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
And of course, there's the insert
method which acts similarly to append
but allows you to specify the insertion point:
>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
import ConfigParser
import os
class Parser(object):
"""attributes may need additional manipulation"""
def __init__(self, section):
"""section to retun all options on, formatted as an object
transforms all comma-delimited options to lists
comma-delimited lists with colons are transformed to dicts
dicts will have values expressed as lists, no matter the length
"""
c = ConfigParser.RawConfigParser()
c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))
self.section_name = section
self.__dict__.update({k:v for k, v in c.items(section)})
#transform all ',' into lists, all ':' into dicts
for key, value in self.__dict__.items():
if value.find(':') > 0:
#dict
vals = value.split(',')
dicts = [{k:v} for k, v in [d.split(':') for d in vals]]
merged = {}
for d in dicts:
for k, v in d.items():
merged.setdefault(k, []).append(v)
self.__dict__[key] = merged
elif value.find(',') > 0:
#list
self.__dict__[key] = value.split(',')
So now my config.cfg
file, which could look like this:
[server]
credentials=username:admin,password:$3<r3t
loggingdirs=/tmp/logs,~/logs,/var/lib/www/logs
timeoutwait=15
Can be parsed into fine-grained-enough objects for my small project.
>>> import config
>>> my_server = config.Parser('server')
>>> my_server.credentials
{'username': ['admin'], 'password', ['$3<r3t']}
>>> my_server.loggingdirs:
['/tmp/logs', '~/logs', '/var/lib/www/logs']
>>> my_server.timeoutwait
'15'
This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from Parser
, or re-doing the parsing job accomplished by the Parser class elsewhere.
I had the same problem and found out Folding can be enabled or disabled, and in my case got disabled somehow.
To solve it, simply right click on the line numbers/breakpoint section (vertical bar in the left of the editor), then under the 'Folding' section chose 'Enable folding'.
ctrlshift/ should be working fine after.
Make sure the path to scripts folder for the python version is added to the path environment/system variable in order to use pip command directly without the whole path to pip.exe which is inside the scripts folder.
The scripts folder would be inside the python folder for the version that you are using, which by default would be inside c drive or in c:/program files or c:/program files (x86).
Then use commands as mentioned below. You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator
.
python -m pip install packagename
python -m pip uninstall packagename
python -m pip install --upgrade packagename
In case you have more than one version of python. You may replace python
with py -versionnumber
for example py -2
for python 2 or you may replace it with the path to the corresponding python.exe file. For example "c:\python27\python"
.
To make a new list retaining the order of first elements of duplicates in L
newlist=[ii for n,ii in enumerate(L) if ii not in L[:n]]
for example if L=[1, 2, 2, 3, 4, 2, 4, 3, 5]
then newlist
will be [1,2,3,4,5]
This checks each new element has not appeared previously in the list before adding it. Also it does not need imports.
You can fix this issue using the binding from How to generate @XmlRootElement Classes for Base Types in XSD?.
Here is an example with Maven
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3.1</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<packageName>com.mycompany.schemas</packageName>
<bindingFiles>bindings.xjb</bindingFiles>
<extension>true</extension>
</configuration>
</plugin>
Here is the binding.xjb
file content
<?xml version="1.0"?>
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc= "http://java.sun.com/xml/ns/jaxb/xjc"
jxb:extensionBindingPrefixes="xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="path/to/myschema.xsd" node="/xs:schema">
<jxb:globalBindings>
<xjc:simple/>
</jxb:globalBindings>
</jxb:bindings>
</jxb:bindings>
Here is another alternative for adding leading to 0s to strings such as CUSIPs which can sometimes look like a number and which many applications such as Excel will corrupt and remove the leading 0s or convert them to scientific notation.
When I tried the answer provided by @metasequoia the vector returned had leading spaces and not 0
s. This was the same problem mentioned by @user1816679 -- and removing the quotes around the 0
or changing from %d
to %s
did not make a difference either. FYI, I am using RStudio Server running on an Ubuntu Server. This little two-step solution worked for me:
gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))
using the %>%
pipe function from the magrittr
package it could look like this:
sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)
I'd prefer a one-function solution, but it works.
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )
It is Summer 2015, and with so much turmoil surrounding Flash I thought I'd add a new answer to this question that avoids its use altogether.
clipboard.js is a nice utility that allows copying of text or html data to the clipboard. It's very easy to use, just include the .js and use something like this:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
clipboard.js is also on GitHub
In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):
int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0
void foo() {
struct { int a, b; } bar; // undefined
static struct { int c, d; } quux; // 0, 0
}
I did solve this error by setting
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME
yes, not only $ORACLE_HOME/lib but $ORACLE_HOME too.
This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.
Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.
The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.
Breaking up a loop with timers is relatively straightforward:
var i=0;
(function () {
for (; i < 6000000; i++) {
/*
Normal processing here
*/
// Every 100,000 iterations, take a break
if ( i > 0 && i % 100000 == 0) {
// Manually increment `i` because we break
i++;
// Set a timer for the next iteration
window.setTimeout(arguments.callee);
break;
}
}
})();
My understanding is that this is actually very simple:
So, to work through some of your examples:
function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
Example 2:
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"
This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python's path, it won't be doing you much good anyway.
import sys;
print [f for f in sys.path if f.endswith('packages')]
Output (Ubuntu installation):
['/home/username/.local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
This works for me on OSX:
pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\ '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n'
It returns the list one per line:
1.1.0rc1
1.1.0rc2
1.1.0
1.2.0rc1
1.2.0rc2
1.2.0rc3
1.2.0rc4
1.2.0
1.3.0rc1
1.3.0rc2
1.3.0rc3
1.3.0
1.3.1
1.3.2
1.3.3
1.4.0rc1
1.4.0rc2
1.4.0rc3
1.4.0
1.4.1
1.4.2
1.5.0rc1
1.5.0rc2
1.5.0rc3
1.5.0
1.5.1
1.5.2
1.6.0rc1
1.6.0
1.6.1
1.6.2
1.7.0rc1
1.7.0rc2
1.7.0
1.7.1
1.8.0rc1
1.8.0rc2
1.8.0
1.8.1
1.9.0rc1
1.9.0rc2
1.9.0rc3
1.9.0rc4
1.9.0
1.10.0rc1
1.10.0rc2
1.10.0
Or to get the latest version available:
pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\ '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n' \
| gsort -r -V \
| head -1
1.10.0rc2
Keep in mind gsort
has to be installed (on OSX) to parse the versions. You can install it with brew install coreutils
You can do it in just one line:
DateTime::createFromFormat('!m', $salary->month)->format('F'); //April
CTL + M + A collapses all
works for me, whereas
CTL + M + O
does not
You could use a colormap such as HSV to generate a set of colors. For example:
cc=hsv(12);
figure;
hold on;
for i=1:12
plot([0 1],[0 i],'color',cc(i,:));
end
MATLAB has 13 different named colormaps ('doc colormap' lists them all).
Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){
declare("MyWidget", [_WidgetBase], {
field1: [],
field2: "",
function1: function(),
function2: function()
});
});
I found that when the fields are initialised with []
then it would be shared by all Model objects. Making changes to one affects all others.
This doesn't happen initialising them with new Array()
. Same for the initialisation of Objects ({}
vs new Object()
)
TBH I am not sure if its a problem with the framework we were using (Dojo)
Have you tried jQuery.contents() ?
Even after 9 years of the original post, this helped me.
If you are receiving these types of errors without any clue, there should be a trigger, function related to the table, and obviously it should end up with an SP, or function with selecting/filtering data NOT USING Primary Unique column. If you are searching/filtering using the Primary Unique column there won't be any multiple results. Especially when you are assigning value for a declared variable. The SP never gives you en error but only an runtime error.
"System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated."
In my case obviously there was no clue, but only this error message. There was a trigger connected to the table and the table updating by the trigger also had another trigger likewise it ended up with two triggers and in the end with an SP. The SP was having a select clause which was resulting in multiple rows.
SET @Variable1 =(
SELECT column_gonna_asign
FROM dbo.your_db
WHERE Non_primary_non_unique_key= @Variable2
If this returns multiple rows, you are in trouble.
In my IE11, works normally. Version: 11.306.10586.0
We can test if ActiveX works at IE, in this site: http://www.pcpitstop.com/testax.asp
<html>
<head>
<script>
var a="Hello";
</script>
</head>
<body>
<?php
echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
?>
</body>
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
I gathered insights from a bunch of answers here and I present a comprehensive solution:
So, if you setup nginx with php5-fpm and log a message using error_log()
you can see it in /var/log/nginx/error.log
by default.
A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));
. If an array is large enough, it seems that nginx
will truncate your log entry.
To get around this you can configure fpm
(php.net fpm config) to manage logs. Here are the steps to do so.
Open /etc/php5/fpm/pool.d/www.conf
:
$ sudo nano /etc/php5/fpm/pool.d/www.conf
Uncomment the following two lines by removing ;
at the beginning of the line: (error_log is defined here: php.net)
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
Create /var/log/fpm-php.www.log
:
$ sudo touch /var/log/fpm-php.www.log;
Change ownership of /var/log/fpm-php.www.log
so that php5-fpm can edit it:
$ sudo chown vagrant /var/log/fpm-php.www.log
Note: vagrant
is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www
and looking at first column.
Restart php5-fpm:
$ sudo service php5-fpm restart
Now your logs will be in /var/log/fpm-php.www.log
.
This is the error you get (emphasis mine):
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
So, how can you avoid the error? By specifying TOP, would be one possibility, I guess.
SELECT (
SELECT TOP 100 PERCENT
COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
GROUP BY refKlinik_id
ORDER BY refKlinik_id
) as dorduncuay
Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll()
when you click on a label, right?
Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label
<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
Select All
</label>
By dynamically allocating a Movie object with new Movie()
, you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as
std::vector<Movie *> movies
But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9})
import collections
d = {}
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
The above error in my case was actually due to the wrong username and password. Solving the issue: 1. Go to the line DriverManager.getConnection("jdbc:mysql://localhost:3306/?useSSL=false", "username", "password"); The fields username and password might be wrong. Enter the username and password which you use to start your mysql client. The username is generally root and password is the string which you enter when a screen similar to this appears Startup screen of mysql
Note: The portname 3306 might be different in your case.
As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.
Edit the document or wiki page, and use the - [ ]
and - [x]
syntax to update your task list. Furthermore you can refer to this link.
Here is a function that works for any floating-point type, not just double
, and also puts the stream back the way it was found afterwards. Unfortunately it won't interact well with threads, but that's the nature of iostreams. You'll need these includes at the start of your file:
#include <limits>
#include <iostream>
Here's the function, you could it in a header file if you use it a lot:
template <class T>
void printVal(std::ostream& os, T val)
{
auto oldFlags = os.flags();
auto oldPrecision = os.precision();
os.flags(oldFlags & ~std::ios_base::floatfield);
os.precision(std::numeric_limits<T>::digits10);
os << val;
os.flags(oldFlags);
os.precision(oldPrecision);
}
Use it like this:
double d = foo();
float f = bar();
printVal(std::cout, d);
printVal(std::cout, f);
If you want to be able to use the normal insertion <<
operator, you can use this extra wrapper code:
template <class T>
struct PrintValWrapper { T val; };
template <class T>
std::ostream& operator<<(std::ostream& os, PrintValWrapper<T> pvw) {
printVal(os, pvw.val);
return os;
}
template <class T>
PrintValWrapper<T> printIt(T val) {
return PrintValWrapper<T>{val};
}
Now you can use it like this:
double d = foo();
float f = bar();
std::cout << "The values are: " << printIt(d) << ", " << printIt(f) << '\n';
Better to use a vbs as you indicated
vbs
, which is a text file with a .vbs extension (see sample code below)vbs
vbs
to open the workbook
at the scheduled time and then either:
Private Sub Workbook_Open()
event in the ThisWorkbook
module to run code when the file is openedApplication.Run
in the vbs
to run the macroSee this example of the later approach at Running Excel on Windows Task Scheduler
sample vbs
Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run
ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing
There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:
Sub new1()
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)
If Err.Number <> 0 Then
''error appeared
MsgBox "currName not found" ''optional, no need to do anything
End If
On Error GoTo 0 ''no error, coming back to default conditions
End Sub
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
You can bind to dom directly
<div dangerouslySetInnerHTML={{__html: '<p>First · Second</p>'}}></div>
Try to keep your files closer to the file system root. More details : for technical reasons, Git for Windows cannot create files or directories when the absolute path is longer than 260 characters.
The answer by EdChum provides you with a lot of flexibility but if you just want to concateate strings into a column of list objects you can also:
output_series = df.groupby(['name','month'])['text'].apply(list)
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.
In Javascript, or more specifically jQuery, for example, you can specify a callback argument to be called when an animation has finished.
In PHP, the preg_replace_callback()
function allows you to provide a function that will be called when the regular expression is matched, passing the string(s) matched as arguments.
here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)
Option explicit
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
Dim nFirst As Long
Dim nLast As Long
Dim nOldFirstUBound As Long
Dim nOldLastUBound As Long
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = UBound(aArrayToPreserve, 1)
nOldLastUBound = UBound(aArrayToPreserve, 2)
'loop through first
For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
I found "gradle 1.11 com.android.tools.build:gradle:0.9.+" supports pre-build ndk now, you can just put the *.so in the dir src/main/jniLibs. when building gradle will package the ndk to the right place.
here is my project
Project: |--src |--|--main |--|--|--java |--|--|--jniLibs |--|--|--|--armeabi |--|--|--|--|--.so files |--libs |--|--other.jar
Not really. Internally, passing by reference is performed by essentially passing the address of the referenced object. So, there really aren't any efficiency gains to be had by passing a pointer.
Passing by reference does have one benefit, however. You are guaranteed to have an instance of whatever object/type that is being passed in. If you pass in a pointer, then you run the risk of receiving a NULL pointer. By using pass-by-reference, you are pushing an implicit NULL-check up one level to the caller of your function.
I was just looking for a solution to this, and the answers above didn't work in my case (and I have insufficient reputation to comment on them). It turns out that, at least for my use-case and the browser I was using (Chrome on OSX), the only thing that seemed to prevent caching was:
Cache-Control = 'no-store'
For completeness i'm now using all 3 of 'no-cache, no-store, must-revalidate'
So in my case (serving dynamically generated images out of Flask in Python), I had to do the following to hopefully work in as many browsers as possible...
def make_uncached_response(inFile):
response = make_response(inFile)
response.headers['Pragma-Directive'] = 'no-cache'
response.headers['Cache-Directive'] = 'no-cache'
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.
Express currently treats app.get("/foo*")
as app.get(/\/foo(.*)/)
, removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "*
in a path is replaced with .+
".
Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.
We can set the response headers in Python Flask application using Flask application context using flask.g
This way of setting response headers in Flask application context using flask.g
is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g
is global & valid for that request thread only.
Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.
Sample Code: file: helper.py
import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession
def _extract_response_header(response)
"""
extracts response headers from response object
and stores that required response header in flask.g app context
"""
headers = CIMultiDict(response.headers)
if 'my_response_header' not in g:
g.my_response_header= {}
g.my_response_header['x-custom-header'] = headers['x-custom-header']
async def call_post_api(post_body):
"""
sample method to make post api call using aiohttp clientsession
"""
try:
async with ClientSession() as session:
async with session.post(uri, headers=_headers, json=post_body) as response:
responseResult = await response.read()
_extract_headers(response, responseResult)
response_text = await response.text()
except (HttpTimeout, ConnectionError) as ex:
raise HttpTimeout(exception_message)
file: middleware.py
import flask
from flask import request, g
class SimpleMiddleWare(object):
"""
Simple WSGI middleware
"""
def __init__(self, app):
self.app = app
self._header_name = "any_request_header"
def __call__(self, environ, start_response):
"""
middleware to capture request header from incoming http request
"""
request_id_header = environ.get(self._header_name)
environ[self._header_name] = request_id_header
def new_start_response(status, response_headers, exc_info=None):
"""
set custom response headers
"""
# set the request header as response header
response_headers.append((self._header_name, request_id_header))
# this is trying to access flask.g values set in helper class & set that as response header
values = g.get(my_response_header, {})
if values.get('x-custom-header'):
response_headers.append(('x-custom-header', values.get('x-custom-header')))
return start_response(status, response_headers, exc_info)
return self.app(environ, new_start_response)
Calling the middleware from main class
file : main.py
from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare
app = Flask(__name__)
app.wsgi_app = SimpleMiddleWare(app.wsgi_app)
(Similar to Azder's answer, but a slightly different tact.)
I don't believe there is a predefined protocol handler for content from the classpath. (The so-called classpath:
protocol).
However, Java does allow you to add your own protocols. This is done through providing concrete implementations java.net.URLStreamHandler
and java.net.URLConnection
.
This article describes how a custom stream handler can be implemented: http://java.sun.com/developer/onlineTraining/protocolhandlers/.
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n
for a new line, or \t
for a tab.
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
If you are used to the compiler catching abstract instantiation violations in other languages, then the Objective-C behavior is disappointing.
As a late binding language it is clear that Objective-C cannot make static decisions on whether a class truly is abstract or not (you might be adding functions at runtime...), but for typical use cases this seems like a shortcoming. I would prefer the compiler flat-out prevented instantiations of abstract classes instead of throwing an error at runtime.
Here is a pattern we are using to get this type of static checking using a couple of techniques to hide initializers:
//
// Base.h
#define UNAVAILABLE __attribute__((unavailable("Default initializer not available.")));
@protocol MyProtocol <NSObject>
-(void) dependentFunction;
@end
@interface Base : NSObject {
@protected
__weak id<MyProtocol> _protocolHelper; // Weak to prevent retain cycles!
}
- (instancetype) init UNAVAILABLE; // Prevent the user from calling this
- (void) doStuffUsingDependentFunction;
@end
//
// Base.m
#import "Base.h"
// We know that Base has a hidden initializer method.
// Declare it here for readability.
@interface Base (Private)
- (instancetype)initFromDerived;
@end
@implementation Base
- (instancetype)initFromDerived {
// It is unlikely that this becomes incorrect, but assert
// just in case.
NSAssert(![self isMemberOfClass:[Base class]],
@"To be called only from derived classes!");
self = [super init];
return self;
}
- (void) doStuffUsingDependentFunction {
[_protocolHelper dependentFunction]; // Use it
}
@end
//
// Derived.h
#import "Base.h"
@interface Derived : Base
-(instancetype) initDerived; // We cannot use init here :(
@end
//
// Derived.m
#import "Derived.h"
// We know that Base has a hidden initializer method.
// Declare it here.
@interface Base (Private)
- (instancetype) initFromDerived;
@end
// Privately inherit protocol
@interface Derived () <MyProtocol>
@end
@implementation Derived
-(instancetype) initDerived {
self= [super initFromDerived];
if (self) {
self->_protocolHelper= self;
}
return self;
}
// Implement the missing function
-(void)dependentFunction {
}
@end
You can save the struct into a map by matching the struct Key
and Value
components to their fictive key and value parts on the map:
mapConfig := map[string]string{}
for _, v := range myconfig {
mapConfig[v.Key] = v.Value
}
Then using the golang comma ok idiom you can test for the key presence:
if v, ok := mapConfig["key1"]; ok {
fmt.Printf("%s exists", v)
}
Adding this in project gradle worked for me
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com" // specifically this worked
}
}}
Yes, if you use the proper generic type signature for the outer hashmap.
HashMap<String, HashMap<String, Foo>> hm = new HashMap<String, HashMap<String, Foobar>>();
// populate the map
hm.get("keyname").get("nestedkeyname");
If you're not using generics, you'd have to do a cast to convert the object retrieved from the outer hash map to a HashMap
(or at least a Map
) before you could call its get()
method. But you should be using generics ;-)
Include your IP address in your host file (C:\Windows\System32\drivers\etc\host) for the respective server:
Sample Entry:
10.100.101.102 server1.us.vijay.com Vijay's Server
The accepted answer should be the following which was unmultimedio's comment to one of the answers above:
Cmd+K will work, you just need to set again in the Keyboard Shortcuts the workbench.action.terminal.clear to Cmd+K, so it shows as Source: User instead of Source: Default – unmultimedio Mar 12 '19 at 1:13
Plase check application pool. if it is stoped. restart it.
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Ok, I figured it out. The issue was that I didn't have the correct permissions set for myrepo.git and the parent directory git.
As root I logged into the server and used:
$ chown username /home/username/git
This then returns drwxrwxr-x 4 username root 4096 2012-10-30 15:51 /home/username/git with the following:
$ ls -ld /home/username/git
I then make a new directory for myrepo.git inside git:
$ mkdir myrepo.git
$ ls -ld myrepo.git/
drwxr-xr-x 2 root root 4096 2012-10-30 18:41 myrepo.git/
but it has the user set to root, so I change it to username the same way as before.
$ chown username myrepo.git/
$ ls -ld myrepo.git/
drwxr-xr-x 2 username root 4096 2012-10-30 18:41 myrepo.git/
I then sign out of root and sign into server as username:
Inside git directory:
$ cd myrepo.git/
$ git --bare init
Initialized empty Git repository in /home/username/git/myrepo.git/
On local machine:
$ git remote add origin
ssh://[email protected]/home/username/git/myrepo.git
$ git push origin master
SUCCESS!
Hopefully this comes in handy for anyone else that runs into the same issue in the future!
Resources
If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt()
or Double.parseDouble()
as others have explained below.
As a side note, it's generally considered bad practice to compare boolean values to true
or false
. Just use if (condition)
or if (!condition)
.
There is no implicit (automatic) cast from text
or varchar
to integer
(i.e. you cannot pass a varchar
to a function expecting integer
or assign a varchar
field to an integer
one), so you must specify an explicit cast using ALTER TABLE ... ALTER COLUMN ... TYPE ... USING:
ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (col_name::integer);
Note that you may have whitespace in your text fields; in that case, use:
ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (trim(col_name)::integer);
to strip white space before converting.
This shoud've been obvious from an error message if the command was run in psql
, but it's possible PgAdmin-III isn't showing you the full error. Here's what happens if I test it in psql
on PostgreSQL 9.2:
=> CREATE TABLE test( x varchar );
CREATE TABLE
=> insert into test(x) values ('14'), (' 42 ');
INSERT 0 2
=> ALTER TABLE test ALTER COLUMN x TYPE integer;
ERROR: column "x" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
=> ALTER TABLE test ALTER COLUMN x TYPE integer USING (trim(x)::integer);
ALTER TABLE
Thanks @muistooshort for adding the USING
link.
See also this related question; it's about Rails migrations, but the underlying cause is the same and the answer applies.
If the error still occurs, then it may be related not to column values, but indexes over this column or column default values might fail typecast. Indexes need to be dropped before ALTER COLUMN and recreated after. Default values should be changed appropriately.
By.CLASS_NAME was not yet mentioned:
from selenium.webdriver.common.by import By
driver.find_element(By.CLASS_NAME, "content")
This is the list of attributes which can be used as locators in By:
CLASS_NAME
CSS_SELECTOR
ID
LINK_TEXT
NAME
PARTIAL_LINK_TEXT
TAG_NAME
XPATH
>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
Just as Diodeus said, you're comparing an Image
to a HTMLDomObject
. Instead compare their .src
attribute:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
Swift 4
I think, there are two ways.
1. NSRange(range, in: )
2. NSRange(location:, length: )
Sample code:
let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])
// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample") {
attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}
// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}
You can use String.Join for this if you are using .NET framework> 4.0.
var result= String.Join(",", yourList);
I have used:
let originY: CGFloat = self.navigationController!.navigationBar.frame.maxY
Working great if you want to get the navigation bar height AND its Y origin.
The reason why it is throwing the error is the object is disposed and after that we are trying to access the table values through the object, but object is disposed.Better to convert that into ToList() so that we can have values
Maybe it isn't actually getting the data until you use it (it is lazy loading), so dataContext doesn't exist when you are trying to do the work. I bet if you did the ToList() in scope it would be ok.
try
{
IQueryable<User> users;
var ret = null;
using (var dataContext = new dataContext())
{
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
if(users.Any())
{
ret = users.Select(x => x.ToInfo()).ToList();
}
}
Return ret;
}
catch (Exception ex)
{
...
}
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
Nice...
Try this to remove an specific cron job (tested).
<?php $output = shell_exec('crontab -l'); ?>
<?php $cron_file = "/tmp/crontab.txt"; ?>
<!-- Execute script when form is submitted -->
<?php if(isset($_POST['add_cron'])) { ?>
<!-- Add new cron job -->
<?php if(!empty($_POST['add_cron'])) { ?>
<?php file_put_contents($cron_file, $output.$_POST['add_cron'].PHP_EOL); ?>
<?php } ?>
<!-- Remove cron job -->
<?php if(!empty($_POST['remove_cron'])) { ?>
<?php $remove_cron = str_replace($_POST['remove_cron']."\n", "", $output); ?>
<?php file_put_contents($cron_file, $remove_cron.PHP_EOL); ?>
<?php } ?>
<!-- Remove all cron jobs -->
<?php if(isset($_POST['remove_all_cron'])) { ?>
<?php echo exec("crontab -r"); ?>
<?php } else { ?>
<?php echo exec("crontab $cron_file"); ?>
<?php } ?>
<!-- Reload page to get updated cron jobs -->
<?php $uri = $_SERVER['REQUEST_URI']; ?>
<?php header("Location: $uri"); ?>
<?php exit; ?>
<?php } ?>
<b>Current Cron Jobs:</b><br>
<?php echo nl2br($output); ?>
<h2>Add or Remove Cron Job</h2>
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
<b>Add New Cron Job:</b><br>
<input type="text" name="add_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<b>Remove Cron Job:</b><br>
<input type="text" name="remove_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<input type="checkbox" name="remove_all_cron" value="1"> Remove all cron jobs?<br>
<input type="submit"><br>
</form>
$('#signup').on("submit", function(event) {
$form = $(this); //wrap this in jQuery
alert('the action is: ' + $form.attr('action'));
});
As previously answered here, String
instances are immutable. StringBuffer
and StringBuilder
are mutable and suitable for such a purpose whether you need to be thread safe or not.
There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char
array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).
public static void main(String[] args) {
String text = "This is a test";
try {
//String.value is the array of char (char[])
//that contains the text of the String
Field valueField = String.class.getDeclaredField("value");
//String.value is a private variable so it must be set as accessible
//to read and/or to modify its value
valueField.setAccessible(true);
//now we get the array the String instance is actually using
char[] value = (char[])valueField.get(text);
//The 13rd character is the "s" of the word "Test"
value[12]='x';
//We display the string which should be "This is a text"
System.out.println(text);
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
It's the "Import existing project into workspace" option under Import->General.
Multiple parameters:
bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
'<b>' + response[i].driver_name + '</b><br>' +
'<b>' + moment(response[i].updated_at).fromNow() + '</b>
<button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
This should do it:
<StackPanel>
<TextBox x:Name="TheTextBox" />
<Button Content="Click Me">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
.
The point is that you have to call Invoke()
of the Dispatcher
of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher
. So instead you should use YourControl.Dispatcher.Invoke()
to be safe. I was banging my head for a couple of hours before I realized this.
For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.
Swift 3 version
extension UIView {
enum ViewSide {
case Top, Bottom, Left, Right
}
func addBorder(toSide side: ViewSide, withColor color: UIColor, andThickness thickness: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
switch side {
case .Top:
border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
case .Bottom:
border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
case .Left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
case .Right:
border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
}
layer.addSublayer(border)
}
}
In order to set corresponding border you should override viewDidLayoutSubviews() method:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourView.addBorder(toSide: UIView.ViewSide.Top, withColor: UIColor.lightGray, andThickness: 1)
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:
<projectDescription>
<name>Project-Name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
2- Now instead of "Project-Name", write your project name, maybe current directory name
3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )
4- Now go to Eclips and open project and add your files to it.
This article describes how to render text in OpenGL using various techniques.
With only using opengl, there are several ways:
function getNiceFileSize($file, $digits = 2){
if (is_file($file)) {
$filePath = $file;
if (!realpath($filePath)) {
$filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
}
$fileSize = filesize($filePath);
$sizes = array("TB", "GB", "MB", "KB", "B");
$total = count($sizes);
while ($total-- && $fileSize > 1024) {
$fileSize /= 1024;
}
return round($fileSize, $digits) . " " . $sizes[$total];
}
return false;
}
I had a problem with sending a request with multiple parameters.
I've solved it by sending a class, with the old parameters as properties.
<form action="http://localhost:12345/api/controller/method" method="post">
<input type="hidden" name="name1" value="value1" />
<input type="hidden" name="name2" value="value2" />
<input type="submit" name="submit" value="Submit" />
</form>
Model class:
public class Model {
public string Name1 { get; set; }
public string Name2 { get; set; }
}
Controller:
public void method(Model m) {
string name = m.Name1;
}
Posting a new answer since it is 2019.
TLDR: AMD is now supported on both Windows and Linux via WHPX and yes, Genymotion is faster as it is using x86 architecture virtualization.
From the Android docs (January 2019):
Though we recommend using HAXM on Windows, it is possible to use Windows Hypervisor Platform (WHPX) with the emulator. You should use WHPX with the emulator if you are using an AMD CPU or if you need to use Hyper-V at the same time.
To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.
Additionally, the following changes must be made in the BIOS settings:
Intel CPU: VT-x must be enabled. AMD CPU: Virtualization or SVM must be enabled.
Diff from 2016:
Virtualization extension requirements
Before attempting to use acceleration, you should first determine if your CPU supports one of the following virtualization extensions technologies:
- Intel Virtualization Technology (VT, VT-x, vmx) extensions
- AMD Virtualization (AMD-V, SVM) extensions
(only supported for Linux)Most modern computers do. If you use an older computer and you're not sure, consult the specifications from the manufacturer of your CPU to determine if it supports virtualization extensions. If your CPU doesn't support one of these virtualization technologies, then you can't use VM acceleration.
Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi
You can sort the dataFrame by count and then remove duplicates. I think it's easier:
df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
Go to the below site and tryout. http://www.counter12.com/
From the above link I have selected the one design that I liked to have in my site accepted terms and it has given me a div that I have pasted in my html page.
It did awesomely worked.
I am not answering to your problem on JQuery, but giving you an alternate solution for your problem.
Not my code, but a good example i think
source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
using System;
using System.Data;
using System.Data.SqlClient;
class OutputParams
{
[STAThread]
static void Main(string[] args)
{
using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
{
SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
cmd.CommandType=CommandType.StoredProcedure ;
SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ;
parm.Value="ALFKI";
parm.Direction =ParameterDirection.Input ;
cmd.Parameters.Add(parm);
SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar);
parm2.Size=50;
parm2.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm2);
SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int);
parm3.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm3);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(cmd.Parameters["@ProductName"].Value);
Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
Console.ReadLine();
}
}
VS 2012/13 Win 7 64 bit gacutil.exe is located in
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools
If you don't want duplicates in a Collection
, you should consider why you're using a Collection
that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set
(which will not allow duplicates) and then add the Set
back to the ArrayList
:
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList
.
You can't. All you can do is to make that image as small as possible and set some cache invalidation headers (Expires
, Cache-Control
) far in the future. Here's what Yahoo! has to say about favicon.ico requests.
You can simply use
int numberOfLetters = yourWord.Length;
or to be cool and trendy, use LINQ like this :
int numberOfLetters = yourWord.ToCharArray().Count();
and if you hate both Properties and LINQ, you can go old school with a loop :
int numberOfLetters = 0;
foreach (char letter in yourWord)
{
numberOfLetters++;
}
Sure you can. Eg.
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
Output
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
Have fun.
Without looping it can be achived like below.
private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
FormatRow(dgEvents.Rows[e.RowIndex]);
}
private void FormatRow(DataGridViewRow myrow)
{
try
{
if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
{
myrow.DefaultCellStyle.BackColor = Color.Red;
}
else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
{
myrow.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
{
myrow.DefaultCellStyle.BackColor = Color.LightGreen;
}
}
catch (Exception exception)
{
onLogs?.Invoke(exception.Message, EventArgs.Empty);
}
}
Java is compiled to bytecode, which then goes into the Java VM, which interprets it.
To get sequence id use
SELECT pg_get_serial_sequence('tableName', 'ColumnName');
This will gives you sequesce id as tableName_ColumnName_seq
To Get Last seed number use
select currval(pg_get_serial_sequence('tableName', 'ColumnName'));
or if you know sequence id already use it directly.
select currval(tableName_ColumnName_seq);
It will gives you last seed number
To Reset seed number use
ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45
The best way is ssh -t user@server "sudo <scriptname>"
, for example ssh -t user@server "sudo reboot"
.
It will prompt for password for user first and then root(since we are running the script or command with root privilege.
I hope it helped and cleared your doubt.
Note: If you just want to stop MySQL server, this might be helpful.
In my case, it kept on restarting as soon as I killed the process using PID. Also brew stop
command didn't work as I installed without using homebrew. Then I went to mac system preferences and we have MySQL installed there. Just open it and stop the MySQL server and you're done. Here in the screenshot, you can find MySQL in bottom of system preferences.
I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:
https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:
yourRecord.FieldName = Request.Form["FieldNameInModel"];
As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.
No, I did not dig down to see how th4e magic works under the covers. I just know it works...
I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.
ruby on rails notes has a very nice blogpost about commenting in erb-files
the short version is
to comment a single line use
<%# commented line %>
to comment a whole block use a if false
to surrond your code like this
<% if false %>
code to comment
<% end %>
As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.
Stored procedures are for executing by an outside program, or on a timed interval.
The answers here will explain it better than I can:
tl;dr: Generic Pattern Counter
// THIS IS WHAT YOU NEED
const count = (str) => {
const re = /YOUR_PATTERN_HERE/g
return ((str || '').match(re) || []).length
}
For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:
/*_x000D_
* Example_x000D_
*/_x000D_
_x000D_
const count = (str) => {_x000D_
const re = /[a-z]{3}/g_x000D_
return ((str || '').match(re) || []).length_x000D_
}_x000D_
_x000D_
const str1 = 'abc, def, ghi'_x000D_
const str2 = 'ABC, DEF, GHI'_x000D_
_x000D_
console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)_x000D_
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)
_x000D_
Original Answer
The problem with your initial code is that you are missing the global identifier:
>>> 'hi there how are you'.match(/\s/g).length;
4
Without the g
part of the regex it will only match the first occurrence and stop there.
Also note that your regex will count successive spaces twice:
>>> 'hi there'.match(/\s/g).length;
2
If that is not desirable, you could do this:
>>> 'hi there'.match(/\s+/g).length;
1
$(document).ready(function() {
var CookieSet = $.cookie('cookietitle', 'yourvalue');
if (CookieSet == null) {
// Do Nothing
}
if (jQuery.cookie('cookietitle')) {
// Reactions
}
});
Compiling and running a Java application on Mac OSX, or any major operating system, is very easy. Apple includes a fully-functional Java runtime and development environment out-of-the-box with OSX, so all you have to do is write a Java program and use the built-in tools to compile and run it.
The first step is writing a simple Java program. Open up a text editor (the built-in TextEdit app works fine), type in the following code, and save the file as "HelloWorld.java" in your home directory.
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World!");
}
}
For example, if your username is David, save it as "/Users/David/HelloWorld.java". This simple program declares a single class called HelloWorld
, with a single method called main
. The main
method is special in Java, because it is the method the Java runtime will attempt to call when you tell it to execute your program. Think of it as a starting point for your program. The System.out.println()
method will print a line of text to the screen, "Hello World!" in this example.
Now that you have written a simple Java program, you need to compile it. Run the Terminal app, which is located in "Applications/Utilities/Terminal.app". Type the following commands into the terminal:
cd ~
javac HelloWorld.java
You just compiled your first Java application, albeit a simple one, on OSX. The process of compiling will produce a single file, called "HelloWorld.class". This file contains Java byte codes, which are the instructions that the Java Virtual Machine understands.
To run the program, type the following command in the terminal.
java HelloWorld
This command will start a Java Virtual Machine and attempt to load the class called HelloWorld
. Once it loads that class, it will execute the main
method I mentioned earlier. You should see "Hello World!" printed in the terminal window. That's all there is to it.
As a side note, TextWrangler is just a text editor for OSX and has no bearing on this situation. You can use it as your text editor in this example, but it is certainly not necessary.
You need to drop the table and then recreate it and then load it again
You should use substring, not jQuery, to do this.
Try something like this:
member.substring(member.length - 2, member.length)
W3Schools (not official, but occasionally helpful): http://www.w3schools.com/jsref/jsref_substring.asp
Adding MDN link as requested by commenter: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring
The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT
packageData: (data) => {
const form = new FormData()
for ( const key in data ) {
form.append(key, data[key]);
}
return form
}
Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following
packageData: (obj, form, namespace) => {
for(const property in obj) {
// if form is passed in through recursion assign otherwise create new
const formData = form || new FormData()
let formKey
if(obj.hasOwnProperty(property)) {
if(namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File, use recursion.
if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
packageData(obj[property], formData, property);
} else {
// if it's a string or a File
formData.append(formKey, obj[property]);
}
}
}
return formData;
}
Try setting contentPadding
ListTile(
contentPadding: EdgeInsets.all(0.0),
...
)
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER
command, which seems to do what I need. See ALTER TABLE.
Use System.DateTime.DaysInMonth, from code sample:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
I also just changed the "Start in" setting of the shortcut icon to: %HOMEDRIVE%/xampp/htdocs/
Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.
That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.
So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.
Clear? :-)
I don’t know Node. But where does the c.query come from?
If you like C++ better than C, you can try this:
#include <ios>
#include <iostream>
bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;
For something simple that work for arrays , strings , and objects I builed this function:
function console_testing($var){
$var = json_encode($var,JSON_UNESCAPED_UNICODE);
$output = <<<EOT
<script>
console.log($var);
</script>
EOT;
echo $output;
}
You could just do it like this
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
foreach($result_select as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
}
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
I have used this URL to obtain multiple currency market quotes.
http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X
"USD",1.0000
"CAD",1.2458
"EUR",0.8396
They can be parsed in PHP like this:
$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');
$quote = array_map( 'str_getcsv', file($url) );
foreach ($quote as $key => $symb) {
$symbol = $quote[$key][0];
$value = $quote[$key][1];
}
Old style string formatting:
In [3]: "%02x" % 127
Out[3]: '7f'
New style
In [7]: '{:x}'.format(127)
Out[7]: '7f'
Using capital letters as format characters yields uppercase hexadecimal
In [8]: '{:X}'.format(127)
Out[8]: '7F'
Docs are here.
var x = from row in table
where row.ID == 0
select row
Supposing you have a DataTable that knows about the rows, other wise you'll need to use the row index:
where row[rowNumber] == 0
In this instance you'd also want to use the select to place the row data into an anonymous class or a preprepared class (if you want to pass it to another method)
Update from 2014, from Bootstrap docs:
Grids and full-width layouts Folks looking to create fully fluid layouts (meaning your site stretches the entire width of the viewport) must wrap their grid content in a containing element with padding: 0 15px; to offset the margin: 0 -15px; used on .rows.
To get min/max value in array, you can use:
var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1
In short, it happens when the application which writes to the sqlite database does not have write permission.
This can be solved in three ways:
db.sqlite3
file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3
)sudo -i
before you run gunicorn
or django runserver
)chmod 777 db.sqlite3
(Dangerous option)Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.
Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.
If you have Python:
python -c "import sys; print(sys.stdout.encoding)"
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
case when first_condition
then first_condition_result_true
else
case when second_condition
then second_condition_result_true
else
second_condition_result_false
end
end
end as qty
The code is
document.title = 'test'
This is because your device, on which you are running your application is not selected with your provisioning profile.
So just go through Certificates, Identifiers & Profiles select your iOS Provisioning Profiles
click on edit then select your Device
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
Programmatically, you can do this:
btn.BorderBrush = new SolidColorBrush(Colors.Transparent);
data.table::setcolorder(table, c("Out", "in", "files"))
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
I used mvn eclipse:eclipse -Dwtpversion=2.0
in command line in the folder where I had my pom.xml. Then I refreshed the project in eclipse IDE. After that I was able to add my project.
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
I met this issue.
I refused to apply the style from 'http://m.b2b-v2-pre1.jcloudec.com/mobile-dynamic-load-component-view/resource/js/resource/js/need/layer.css?2.0' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Changing the path could solve this issue.
You can use Collections
for to sort data:
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
This works for me permanently:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27","User")