The required
property is boolean
:
$('form#register').find('input').each(function(){
if(!$(this).prop('required')){
console.log("NR");
} else {
console.log("IR");
}
});
Reference: HTMLInputElement
Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.
It seems that when we do:
marker.on('click', function(e) {...
The e
points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this
object which strangely, requires us to use this.options
to get to the options
object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid
then within the function above, we can get the value by invoking: this.options.objid
You can use my cookie ES module for get/set/remove cookie.
In your head tag, include the following code:
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>
or
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.min.js"></script>
Now you can use window.cookie for store user information in web pages.
Is the cookie enabled in your web browser?
returns {boolean} true if cookie enabled.
Example
if ( cookie.isEnabled() )
console.log('cookie is enabled on your browser');
else
console.error('cookie is disabled on your browser');
Set a cookie.
name: cookie name.
value: cookie value.
Example
cookie.set('age', 25);
get a cookie.
name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
Example
var age = cookie.get('age', 25);
Remove cookie.
name: cookie name.
Example
cookie.remove( 'age' );
If the blob is instantiated with data from an F4M manifest (check the Network Tab in Chrome's Developer Tools), you can download the video file using the php script posted here: https://n1njahacks.wordpress.com/2015/01/29/how-to-save-hds-flash-streams-from-any-web-page/
By putting:
if ($manifest == '')
$manifest = $_GET['manifest'];
before:
if ($manifest)
you could even run it on a webserver, using requests with the query string: ?manifest=[manifest url]
.
Note that you'll probably want to use an FTP client to retrieve the downloaded video file and clean up after the script (it leaves all the downloaded video parts).
Using awk.
i starts at 0, i++
will increment the value of i, but return the original value that i held before being incremented.
awk '{print i++ "," $0}' file
Those who are new to MySQL & Mac users; Note that, Connection is different than Database.
Steps to create a database.
Step 1: Create connection and click to go inside
Step 2: Click on database icon
Step 3: Name your database schema
Step 4: Apply query
Step 5: Your DB created, enjoy...
Update: This answer may be incorrect or out of date. Please see comments for details.
I switched from @Inject
to @EJB
because @EJB
allows circular injection whereas @Inject
pukes on it.
Details: I needed @PostConstruct
to call an @Asynchronous
method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject
failed for this task whereas @EJB
worked.
use directly where you want controller or web.php
Request::getHost();
this code works and dont throw any exception:
Session.Abandon();
Session["tempKey1"] = "tempValue1";
One thing to note here that Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request. That simply means that suppose you tried to access value in code just after the session.abandon command was executed, it will be still there. So do not get confused if your code is just not working even after issuing session.abandon command and immediately doing some logic with the session.
One reason to use object
over iframe
is that object re-sizes the embedded content to fit the object dimensions. most notable on safari in iPhone 4s where screen width is 320px
and the html from the embedded URL may set dimensions greater.
I would like to add, that yes. While using the NAT adapter settings in Vmware and turning off windows firewall I was able to ping other guest machines in my test environment.
Sidenote: Best practice would be to implement a hardware firewall in larger environments and turn off windows firewall on the Domain Controller.
The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example: bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code: bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about. So simple solution is to change either the variable name or the id or class name.
function getPost()
{
if(!empty($_POST))
{
// when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request
// NOTE: if this is the case and $_POST is empty, check the variables_order in php.ini! - it must contain the letter P
return $_POST;
}
// when using application/json as the HTTP Content-Type in the request
$post = json_decode(file_get_contents('php://input'), true);
if(json_last_error() == JSON_ERROR_NONE)
{
return $post;
}
return [];
}
print_r(getPost());
WebElement p= driver.findElement(By.id("your id name"));
p.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
If the strings you are concatenating are literals, use String literal concatenation
re.compile(
"[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
This is useful if you want to comment on part of a string (as above) or if you want to use raw strings or triple quotes for part of a literal but not all.
Since this happens at the syntax layer it uses zero concatenation operators.
String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.
In C# Core DataSource does not exist, but this work fine:
listbox.ItemsSource = null;
listbox.Items.Clear();
The dict literal might be a tiny bit faster as its bytecode is shorter:
In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()
In [4]: dis.dis(a)
1 0 BUILD_MAP 0
3 RETURN_VALUE
In [5]: dis.dis(b)
1 0 LOAD_GLOBAL 0 (dict)
3 CALL_FUNCTION 0
6 RETURN_VALUE
Same applies to the list
vs []
This is the syntax you need:
CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END
Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it.
SharePoint uses a lot of different logging mechanisms. Most importantly you can configure the location of the logs through Central Admin. To give you an understanding of the logs involved, here is a quote from http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/
All file based logs can be read by text editors and can be parsed by using popular log parsing tools (Log Parser 2.2 from Microsoft or Funnel Web). It will also be a good idea to read the IIS Logs which are generally saved at (System Drive):\WINDOWS\system32\LogFiles
a) Diagnostics Logs
· Event Throttling Logs – These end up going to the Windows Event Log and can be viewed in the Event Viewer. They show Errors and Warnings.
· Trace Logs – These show detailed line by line tracing infomration emitted during a web request or service execution. They end up being stored at a known location on the front-end server. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\LOGS\
b) Audit Logs - They end up in the associated Content Database tables and can be viewed at Site Collection Level as well as Site Level using the web browser. WSS 3.0 and MOSS 2007 use different pages to show Audit Log Reports.
c) Usage Logs – They get stored locally on the front-end servers and get processed both locally and at farm level via SSP (this is based on the setup as I understand the results from the local processing are merged by SSP) and can be viewed at both the Site Level and Site Collection Level. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Logs
d) Search\Query Logs – These are saved in the associated SSP database but can be viewed at SSP level via the Web Browser and in MOSS at Site Collection Level by going to the settings page.
e) Information Management Logs – Stored in the associated Content Database and can be can be viewed at the Site Collection Level.
f) Content and Structure Logs – This option is only available after one enables the publication feature. This store is saved in the Content Database associated with the Site Collection and can be viewed at Site Collection level by going to the settings page.
Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)
File eclipse.ini needs the vm
argument to point to your JDK location.
Edit the eclipse.ini
file to point to your JDK home, something as follows -
-vm
C:\Program Files\Java\jdk1.6.0_06
This ensures that Eclipse would be running off the JDK and not any default JRE on your machine.
In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte
data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:
module tb;
byte b [4];
initial begin
foreach (b[i]) b[i] = 1 << i;
foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
$finish;
end
endmodule
This prints out:
Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000
This is similar in concept to Marty's reg [7:0] a [0:3];
. However, byte
is a 2-state data type (0 and 1), but reg
is 4-state (01xz). Using byte
also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i])
loop syntax.
The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.
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.
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
A float isn't have 0
or 0.00
: those are different string representations of the internal (IEEE754) binary format but the float is the same.
If you want to express your float as "0.00", you need to format it in a string, using number_format :
$numberAsString = number_format($numberAsFloat, 2);
The confusion arises from the level of indirection (abstraction) that comes about from using NULL.
Going back to the "what's under the Christmas tree" analogy, "Unknown" describes the state of knowledge about what is in Box A.
So if you don't know what's in Box A, you say it's "Unknown", but that doesn't mean that "Unknown" is inside the box. Something other than unknown is in the box, possibly some kind of object, or possibly nothing is in the box.
Similarly, if you don't know what's in Box B, you can label your state of knowledge about the contents as being "Unknown".
So here's the kicker: Your state of knowledge about Box A is equal to your state of knowledge about Box B. (Your state of knowledge in both cases is "Unknown" or "I don't know what's in the Box".) But the contents of the boxes may or may not be equal.
Going back to SQL, ideally you should only be able to compare values when you know what they are. Unfortunately, the label that describes a lack of knowledge is stored in the cell itself, so we're tempted to use it as a value. But we should not use that as a value, because it would lead to "the content of Box A equals the content of Box B when we don't know what's in Box A and/or we don't know what's in Box B. (Logically, the implication "if I don't know what's in Box A and if I don't know what's in Box B, then what's in Box A = What's in Box B" is false.)
Yay, Dead Horse.
One liner for Python based on scai's answer, but a) takes stdin, b) makes the result repeatable with seed, c) picks out only 200 of all lines.
$ cat file | python -c "import random, sys;
random.seed(100); print ''.join(random.sample(sys.stdin.readlines(), 200))," \
> 200lines.txt
If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.
function getMaxColCount($table) {
var maxCol = 0;
$table.find('tr').each(function(i,o) {
var colCount = 0;
$(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
var cc = Number($(oo).attr('colspan'));
if (cc) {
colCount += cc;
} else {
colCount += 1;
}
});
if(colCount > maxCol) { maxCol = colCount };
});
return maxCol;
}
To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:
$('td.maxcols, th.maxcols').each(function(i,o) {
$t = $($(o).parents('table')[0]); $(o).attr('colspan', getMaxColCount($t));
});
If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.
I'm on Mac OS 10.6.8
The easiest solution works for me is simply put in
$ export JAVA_HOME=$(/usr/libexec/java_home)
To test whether it works, put in
$ echo $JAVA_HOME
it shows
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
you can also test
$ which java
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name
of "test" (i.e.: <input type="checkbox" name="test">
, you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You could use git-sizer
. In the --verbose
setting, the example output is (below). Look for the Total size of files
line.
$ git-sizer --verbose Processing blobs: 1652370 Processing trees: 3396199 Processing commits: 722647 Matching commits to trees: 722647 Processing annotated tags: 534 Processing references: 539 | Name | Value | Level of concern | | ---------------------------- | --------- | ------------------------------ | | Overall repository size | | | | * Commits | | | | * Count | 723 k | * | | * Total size | 525 MiB | ** | | * Trees | | | | * Count | 3.40 M | ** | | * Total size | 9.00 GiB | **** | | * Total tree entries | 264 M | ***** | | * Blobs | | | | * Count | 1.65 M | * | | * Total size | 55.8 GiB | ***** | | * Annotated tags | | | | * Count | 534 | | | * References | | | | * Count | 539 | | | | | | | Biggest objects | | | | * Commits | | | | * Maximum size [1] | 72.7 KiB | * | | * Maximum parents [2] | 66 | ****** | | * Trees | | | | * Maximum entries [3] | 1.68 k | * | | * Blobs | | | | * Maximum size [4] | 13.5 MiB | * | | | | | | History structure | | | | * Maximum history depth | 136 k | | | * Maximum tag depth [5] | 1 | | | | | | | Biggest checkouts | | | | * Number of directories [6] | 4.38 k | ** | | * Maximum path depth [7] | 13 | * | | * Maximum path length [8] | 134 B | * | | * Number of files [9] | 62.3 k | * | | * Total size of files [9] | 747 MiB | | | * Number of symlinks [10] | 40 | | | * Number of submodules | 0 | | [1] 91cc53b0c78596a73fa708cceb7313e7168bb146 [2] 2cde51fbd0f310c8a2c5f977e665c0ac3945b46d [3] 4f86eed5893207aca2c2da86b35b38f2e1ec1fc8 (refs/heads/master:arch/arm/boot/dts) [4] a02b6794337286bc12c907c33d5d75537c240bd0 (refs/heads/master:drivers/gpu/drm/amd/include/asic_reg/vega10/NBIO/nbio_6_1_sh_mask.h) [5] 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c (refs/tags/v2.6.11) [6] 1459754b9d9acc2ffac8525bed6691e15913c6e2 (589b754df3f37ca0a1f96fccde7f91c59266f38a^{tree}) [7] 78a269635e76ed927e17d7883f2d90313570fdbc (dae09011115133666e47c35673c0564b0a702db7^{tree}) [8] ce5f2e31d3bdc1186041fdfd27a5ac96e728f2c5 (refs/heads/master^{tree}) [9] 532bdadc08402b7a72a4b45a2e02e5c710b7d626 (e9ef1fe312b533592e39cddc1327463c30b0ed8d^{tree}) [10] f29a5ea76884ac37e1197bef1941f62fda3f7b99 (f5308d1b83eba20e69df5e0926ba7257c8dd9074^{tree})
The class below should do the trick. Just create an instance, call the "multiply" method, and provide the source input stream and the amount of duplicates you need.
Important: you must consume all cloned streams simultaneously in separate threads.
package foo.bar;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InputStreamMultiplier {
protected static final int BUFFER_SIZE = 1024;
private ExecutorService executorService = Executors.newCachedThreadPool();
public InputStream[] multiply(final InputStream source, int count) throws IOException {
PipedInputStream[] ins = new PipedInputStream[count];
final PipedOutputStream[] outs = new PipedOutputStream[count];
for (int i = 0; i < count; i++)
{
ins[i] = new PipedInputStream();
outs[i] = new PipedOutputStream(ins[i]);
}
executorService.execute(new Runnable() {
public void run() {
try {
copy(source, outs);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return ins;
}
protected void copy(final InputStream source, final PipedOutputStream[] outs) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int n = 0;
try {
while (-1 != (n = source.read(buffer))) {
//write each chunk to all output streams
for (PipedOutputStream out : outs) {
out.write(buffer, 0, n);
}
}
} finally {
//close all output streams
for (PipedOutputStream out : outs) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@Html.TextAreaFor(model => model.Text)
As none of the answers above are straight forward:
Backslash escape \ is what you need:
myscript \"test\"
This is thrown when
... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.
Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.
The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts
file and trust it using keytool
which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.
OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.
You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword
to pass the password YourPassword
from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.
I used this videocast to set up my GoDaddy domain with Heroku, and it worked perfectly. Very clear and well explained.
Note: Skip the part about CNAME yourdomain.com.
(note the .
) and the heroku addons:add "custom domains"
http://blog.heroku.com/archives/2009/10/7/heroku_casts_setting_up_custom_domains/
To summarize the video:
1) on GoDaddy and create a CNAME with
Alias Name: www
Host Name: proxy.heroku.com
2) check that your domain has propagated by typing host www.yourdomain.com
on the command line
3) run heroku domains:add www.yourdomain.com
4) run heroku domains:add yourdomain.com
It worked for me after these steps. Hope it works for you too!
UPDATE: things have changed, check out this post Heroku/GoDaddy: send naked domain to www
Go to src/enviroments/enviroments.ts
and enable the production mode
export const environment = {
production: true
};
for Angular 2
In general,
variable=$(command)
or
variable=`command`
The latter one is the old syntax, prefer $(command)
.
Note: variable = ....
means execute the command variable
with the first argument =
, the second ....
How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?
You can undo changes to tracked files with:
git reset HEAD --hard
You can remove untracked files with:
git clean -f
You can remove untracked files and directories with:
git clean -fd
but you can't undo change to untracked files.
You can remove ignored and untracked files and directories
git clean -fdx
but you can't undo change to ignored files.
You can also set clean.requireForce
to false
:
git config --global --add clean.requireForce false
to avoid using -f
(--force
) when you use git clean
.
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
You will need to check both parts of the path (directory and filename) and create each if it does not exist.
Use File.Exists
and Directory.Exists
to find out whether they exist. Directory.CreateDirectory
will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.
In adition to Ian Boyd's answer:
Also CultureInfo
implements this interface and can be used in your case. So you could parse a French date string for example; you could use
var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);
You can use the parseInt() function to convert the string to a number, e.g:
parseInt($('#elem').css('top'));
Update: (as suggested by Ben): You should give the radix too:
parseInt($('#elem').css('top'), 10);
Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).
You should use UNION if you want to combine different resultsets. Try the following:
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A)
UNION
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)
Combination from itertools
import itertools
col_names = ["aa","bb", "cc", "dd"]
all_combinations = itertools.chain(*[itertools.combinations(col_names,i+1) for i,_ in enumerate(col_names)])
print(list(all_combinations))
if you want include Id
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = querySnapshot.docs.map((doc) => {
return { id: doc.id, ...doc.data() }
})
console.log(tempDoc)
})
}
Same way with array
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = []
querySnapshot.forEach((doc) => {
tempDoc.push({ id: doc.id, ...doc.data() })
})
console.log(tempDoc)
})
}
It's as easy as using select:
Get-Content file.txt | Select -Index (line - 1)
E.g. to get line 5
Get-Content file.txt | Select -Index 4
Or you can use:
(Get-Content file.txt)[4]
Here is a php4/php5 class that will sort one or more fields:
// a sorter class
// php4 and php5 compatible
class Sorter {
var $sort_fields;
var $backwards = false;
var $numeric = false;
function sort() {
$args = func_get_args();
$array = $args[0];
if (!$array) return array();
$this->sort_fields = array_slice($args, 1);
if (!$this->sort_fields) return $array();
if ($this->numeric) {
usort($array, array($this, 'numericCompare'));
} else {
usort($array, array($this, 'stringCompare'));
}
return $array;
}
function numericCompare($a, $b) {
foreach($this->sort_fields as $sort_field) {
if ($a[$sort_field] == $b[$sort_field]) {
continue;
}
return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
}
return 0;
}
function stringCompare($a, $b) {
foreach($this->sort_fields as $sort_field) {
$cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
if ($cmp_result == 0) continue;
return ($this->backwards ? -$cmp_result : $cmp_result);
}
return 0;
}
}
/////////////////////
// usage examples
// some starting data
$start_data = array(
array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),
);
// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));
// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));
// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;
print_r($sorter->sort($start_data, 'last_name', 'first_name'));
// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));
It worked for me-
Just added 2> null
after the $(mysql_command)
, and it will suppress the Errors and Warning messages only.
you can try with this way
android:background="@color/white"
Or simply export VERBOSE environment variable on the shell like this:
export VERBOSE=1
I've found the solution :
You have to add the html5=1
in the src attribute of the iframe :
<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>
The video will be displayed as HTML5 if available, or fallback into flash player.
There are some great answers already, but none of them address a complete list of what the __future__
statement currently supports.
Put simply, the __future__
statement forces Python interpreters to use newer features of the language.
The features that it currently supports are the following:
nested_scopes
Prior to Python 2.1, the following code would raise a NameError:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The from __future__ import nested_scopes
directive will allow for this feature to be enabled.
generators
Introduced generator functions such as the one below to save state between successive function calls:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
division
Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y
, whereas floor division is specified by x//y
.
The from __future__ import division
directive forces the use of Python 3.0 style division.
absolute_import
Allows for parenthesis to enclose multiple import
statements. For example:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
LEFT, DISABLED, NORMAL, RIDGE, END)
Instead of:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
Or:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END
with_statement
Adds the statement with
as a keyword in Python to eliminate the need for try/finally
statements. Common uses of this are when doing file I/O such as:
with open('workfile', 'r') as f:
read_data = f.read()
print_function
:
Forces the use of Python 3 parenthesis-style print()
function call instead of the print MESSAGE
style statement.
unicode_literals
Introduces the literal syntax for the bytes
object. Meaning that statements such as bytes('Hello world', 'ascii')
can be simply expressed as b'Hello world'
.
generator_stop
Replaces the use of the StopIteration
exception used inside generator functions with the RuntimeError
exception.
One other use not mentioned above is that the __future__
statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.
The selected answer doesn't work in Rails 3.1+ as the error handler was moved to a middleware (see github issue).
Here's the solution I found which I'm pretty happy with.
In ApplicationController
:
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :handle_exception
end
def not_found
raise ActionController::RoutingError.new('Not Found')
end
def handle_exception(exception=nil)
if exception
logger = Logger.new(STDOUT)
logger.debug "Exception Message: #{exception.message} \n"
logger.debug "Exception Class: #{exception.class} \n"
logger.debug "Exception Backtrace: \n"
logger.debug exception.backtrace.join("\n")
if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
return render_404
else
return render_500
end
end
end
def render_404
respond_to do |format|
format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def render_500
respond_to do |format|
format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
and in application.rb
:
config.after_initialize do |app|
app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end
And in my resources (show, edit, update, delete):
@resource = Resource.find(params[:id]) or not_found
This could certainly be improved, but at least, I have different views for not_found and internal_error without overriding core Rails functions.
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.
Here is information about all of the isolation levels at your disposal, as well as table hints.
There is no difference between moving and renaming; you should simply call Directory.Move
.
In general, if you're only doing a single operation, you should use the static
methods in the File
and Directory
classes instead of creating FileInfo
and DirectoryInfo
objects.
For more advice when working with files and directories, see here.
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
For the last few hours, I was scratching my head why my CSS wasn't working! I was trying to show row-resize
as cursor but it was showing the default cursor but for s-resize
browser was showing the correct cursor. I tried changing z-index
but that also didn't solve my problem.
So after trying few more solutions from the internet, I called one of my co-workers and shared my screen via Google meet and he told me that he was seeing the row-resize icon when I was seeing the default icon!!! He even sent me the screenshot of my screencast.
So after further investigation, I found out the as I was using Remote Desktop Connection to connect to my office PC, for some reason RDC doesn't show some type of cursors.
Here is the list of cursor's I couldn't see on my remote PC,
none, cell, crosshair, text, vertical-text, alias, copy, col-resize, row-resize,
Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap
HashMap<String, MyObject>
class MyObject {
public String value1;
public int value2;
public List<String> value3;
}
To revert modified files:
sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'
Django has method_decorator
which is a decorator that turns any decorator into a method decorator, you can see how it's implemented in django.utils.decorators
:
https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class
Older versions of Python would only allow a single simple statement after for ...:
if ...:
or similar block introductory statements.
I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:
for i in range(3): print "Here's i:"; print i
... but, on the other hand, we can't:
for i in range(3): if i % 2: print "That's odd!"
We can:
x=10
while x > 0: print x; x-=1
... but we can't:
x=10; while x > 0: print x; x-=1
... and so on.
In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.
It's marginally acceptable to combine multiple statements on a line in some cases. For example:
x=0; y=1
... or even:
if some_condition(): break
... for simple break
continue
and even return
statements or assigments.
In particular if one needs to use a series of elif
one might use something like:
if keystroke == 'q': break
elif keystroke == 'c': action='continue'
elif keystroke == 'd': action='delete'
# ...
else: action='ask again'
... then you might not irk your colleagues too much. (However, chains of elif
like that scream to be refactored into a dispatch table ... a dictionary that might look more like:
dispatch = {
'q': foo.break,
'c': foo.continue,
'd': foo.delete
}
# ...
while True:
key = SomeGetKey()
dispatch.get(key, foo.try_again)()
This code works
BufferedReader bR = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while((line = bR.readLine()) != null){
responseStrBuilder.append(line);
}
inputStream.close();
JSONObject result= new JSONObject(responseStrBuilder.toString());
If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED
Intent. Android systems broadcasts that intent once boot is completed.
Once you receive that intent you can launch a Service that can do whatever you want to do.
Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.
HashMap<String, String> jsonToMap(String JsonDetectionString) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
Gson gson = new Gson();
map = (HashMap<String, String>) gson.fromJson(JsonDetectionString, map.getClass());
return map;
}
Taken from: http://avenshteinohad.blogspot.com/2016/01/redis-jedis-quickstart.html
If you use windows, use MSOpenTech version from:
You also might find this post useful to get started with basic commands.
In php.ini set :
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
FFTW is the 'fastest fourier transform in the west', and has some Java wrappers:
Hope that helps!
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
This will be used to change the Html content inside the span
$('#abc span').html('goes inside the span');
if you want to change the text inside the span, you can use:
$('#abc span').text('goes inside the span');
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
For H2, you can start a web server within your code during a debugging session if you have a database connection object. You could add this line to your code, or as a 'watch expression' (dynamically):
org.h2.tools.Server.startWebServer(conn);
The server tool will start a web browser locally that allows you to access the database.
A nice abstraction on top of Jsch is Apache commons-vfs which offers a virtual filesystem API that makes accessing and writing SFTP files almost transparent. Worked well for us.
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
//Do it like---
function dragStart(this_,event) {
var row=$(this_).attr('whatever');
event.dataTransfer.setData("Text", row);
}
There are several ways to simulate optional parameters in Java:
Method overloading.
void foo(String a, Integer b) {
//...
}
void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
}
foo("a", 2);
foo("a");
One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.
Varargs.
a) All optional parameters are of the same type:
void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
b) Types of optional parameters may be different:
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.
Nulls. To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:
void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
//...
}
foo("a", null, 2);
Now all arguments values must be provided, but the default ones may be null.
Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:
void foo(String a, Optional<Integer> bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
//...
}
foo("a", Optional.of(2));
foo("a", Optional.<Integer>absent());
Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.
Update: Java 8 includes the class java.util.Optional
out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.
Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:
class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
//...
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();
Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:
void foo(Map<String, Object> parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
}
a = (Integer)parameters.get("a");
}
if (parameters.containsKey("b")) {
//...
}
//...
}
foo(ImmutableMap.<String, Object>of(
"a", "a",
"b", 2,
"d", "value"));
In Java 9, this approach became easier:
@SuppressWarnings("unchecked")
static <T> T getParm(Map<String, Object> map, String key, T defaultValue)
{
return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
}
void foo(Map<String, Object> parameters) {
String a = getParm(parameters, "a", "");
int b = getParm(parameters, "b", 0);
// d = ...
}
foo(Map.of("a","a", "b",2, "d","value"));
Please note that you can combine any of these approaches to achieve a desirable result.
I've seen this error when you have a circular dependency.
class A extends B {}
class B extends C {}
class C extends A {}
First please follow the two lines of codes to update the action bar items before that you should set a condition in oncreateOptionMenu(). For example:
Boolean mISQuizItemSelected = false;
/**
* Called to inflate the action bar menus
*
* @param menu
* the menu
*
* @return true, if successful
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
inflater.inflate(R.menu.menu_demo, menu);
//condition to hide the menus
if (mISQuizItemSelected) {
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(false);
}
}
return super.onCreateOptionsMenu(menu);
}
/**
* Called when the item on the action bar being selected.
*
* @param item
* menuitem being selected
*
* @return true if the menuitem id being selected is matched
* false if none of the menuitems id are matched
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getId() == R.id.action_quiz) {
//to navigate based on the usertype either learner or leo
mISQuizItemSelected = true;
ActionBar actionBar = getActionBar();
invalidateOptionMenu();
}
}
I had a same issue recently with Anaconda with Python 3.7.
I solved this problem by downgrading python version to 3.6:
conda install python=3.6
and then by updating all the packages:
conda update --all
For finding objects which are meaningfully equal, you need to override equals
and hashcode
methods for the class. You can find a good tutorial here.
http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/
This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.
bash-4.4# gem list -d
Output::
aasm (5.0.6)
Authors: Thorsten Boettger, Anil Maurya
Homepage: https://github.com/aasm/aasm
License: MIT
Installed at: /usr/local/bundle
State machine mixin for Ruby objects
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
An eclipse specific alternative limited to the java.library.path JVM parameter allows to set it for a specific source folder rather than for the whole jdk as proposed in another response:
For those interested on detail on why maven argline tag should be preferred to the systemProperties one, look, for example:
If this error appears suddenly, it means the project is missing some frameworks. Libraries and dependent projects can require frameworks, so if you've added one recently then that can cause this error.
To add frameworks, right click on the project name in the project view, select Add, then select Existing frameworks from the list. Then find the framework with the symbols you're missing.
The other thing is if you added any classes in the compiled resources and removed that classes from the project then the error appears. The best thing to do is remove the classes from the compile resources(Build settings--> compile sources) which have removed from the project.
In my case i have added the admob classes in the project and compiled the project. In a later case i dont want to include admobs in my project so i deleted the references of the admob classes from my project. When this error occurred i deleted the .m class of my admob from compile resources solved this problem.
The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.
Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""
Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Ikariam Autologin</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="s666.en.ikariam.com" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="PlayersName" class="" />
<input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.
Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:
You can use this code to see the last modified date of a file.
DateTime dt = File.GetLastWriteTime(path);
And this code to see the creation time.
DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
The recommended approach for a singleton service for Angular 6 and beyond is :
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
In fact the CLI --module
switch doesn't even exist any more for registering a service at the app
level because it doesn't need to modify app.module.ts
anymore.
This will create the above code, without needing to specify a module.
ng g s services/user
So if you don't want your service to be a singleton you must remove the providedIn
code yourself - and then add it manually to providers
for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root'
part so you need to manually remove it.
Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.
Sam's answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow delegation from one constructor to another, thereby removing the need for defaults.
It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:
C:\Windows\Microsoft.NET\Framework\v4.0.30319
and it should install your 32-bit application just fine.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if(Context.Session!= null)
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
}
As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.
var ID_COLUMN=0
var URL_COLUMN=1
findings.sort(compareByColumnIndex(URL_COLUMN))
function compareByColumnIndex(index) {
return function(a,b){
if (a[index] === b[index]) {
return 0;
}
else {
return (a[index] < b[index]) ? -1 : 1;
}
}
}
Nowadays, in 90% of case if you working with URL in Python you probably use python-requests. Hence the question here - why not reuse URL validation from requests?
from requests.models import PreparedRequest
import requests.exceptions
def check_url(url):
prepared_request = PreparedRequest()
try:
prepared_request.prepare_url(url, None)
return prepared_request.url
except requests.exceptions.MissingSchema, e:
raise SomeException
Features:
Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.
you can find more info it you look in android/app
or com\android\internal\policy\impl
Good Luck !
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
Solution for yml file:
1.Copy yml to in same directory that jar application
2.Run command, example for xxx.yml
:
java -jar app.jar --spring.config.location=xxx.yml
It's works fine, but in startup logger is INFO:
No active profile set .........
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:
dockstop() {
docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}
Then in your command line, simply do dockstop myImageName
and it will stop and remove all containers that were started from an image called myImageName.
May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?
Why your code didn't work
You code for i in range (100, 0)
is fine, except
the third parameter (step
) is by default +1
. So you have to specify 3rd parameter to range() as -1
to step backwards.
for i in range(100, -1, -1):
print(i)
NOTE: This includes 100 & 0 in the output.
There are multiple ways.
Better Way
For pythonic way, check PEP 0322.
This is Python3 pythonic example to print from 100 to 0 (including 100 & 0).
for i in reversed(range(101)):
print(i)
There are many ways to rename the branch, but I am going to focus on the bigger problem: "how to allow clients to fast-forward and not have to mess with their branches locally".
This is something actually easy to do; but don't abuse it. The whole idea hinges on merge commits; as they allow fast-forward, and link histories of a branch with another.
# rename the branch "master" to "master-old"
# this works even if you are on branch "master"
git branch -m master master-old
# create master from new starting point
git branch master <new-master-start-point>
# now we've got to fix the new branch...
git checkout master
# ... by doing a merge commit that obsoletes
# "master-old" hence the "ours" strategy.
git merge -s ours master-old
git push origin master
This works because creating a merge
commit allows fast-forwarding the branch to a new revision.
renamed branch "master" to "master-old" and use commit ba2f9cc as new "master"
-- this is done by doing a merge commit with "ours" strategy which obsoletes
the branch.
these are the steps I did:
git branch -m master master-old
git branch master ba2f9cc
git checkout master
git merge -s ours master-old
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
A clustered index actually describes the order in which records are physically stored on the disk, hence the reason you can only have one.
A Non-Clustered Index defines a logical order that does not match the physical order on disk.
I would prefer to store the image in a directory, then store a reference to the image file in the database.
However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.
You can read more about using filegroups here http://msdn.microsoft.com/en-us/library/ms179316.aspx.
here is mine too! (a bit late in the game though)
https://github.com/backuity/clist
As opposed to scopt
it is entirely mutable... but wait! That gives us a pretty nice syntax:
class Cat extends Command(description = "concatenate files and print on the standard output") {
// type-safety: members are typed! so showAll is a Boolean
var showAll = opt[Boolean](abbrev = "A", description = "equivalent to -vET")
var numberNonblank = opt[Boolean](abbrev = "b", description = "number nonempty output lines, overrides -n")
// files is a Seq[File]
var files = args[Seq[File]](description = "files to concat")
}
And a simple way to run it:
Cli.parse(args).withCommand(new Cat) { case cat =>
println(cat.files)
}
You can do a lot more of course (multi-commands, many configuration options, ...) and has no dependency.
I'll finish with a kind of distinctive feature, the default usage (quite often neglected for multi commands):
Might not solve all the problems in the original question, but since this seems to be the de facto post on how mercurial can amend to previous commit, I'll add my 2 cents worth of information.
If you are like me, and only wish to modify the previous commit message (fix a typo etc) without adding any files, this will work
hg commit -X 'glob:**' --amend
Without any include or exclude patterns hg commit
will by default include all files in working directory. Applying pattern -X 'glob:**'
will exclude all possible files, allowing only to modify the commit message.
Functionally it is same as git commit --amend
when there are no files in index/stage.
I've SSL on Apache2.4.4 and executing this code at first, did the trick:
set OPENSSL_CONF=C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf
then execute the rest codes..
So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case
I have what i think is a better solution, since it is scalable to more levels, as many as wanted, not only two or three.
I use borders, but it can also be done with whateever style wanted, like background-color.
With the border, the idea is to:
You can test it at: http://jsbin.com/ubiyo3/13
And here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Hierarchie Borders MarkUp</title>
<style>
.parent { display: block; position: relative; z-index: 0;
height: auto; width: auto; padding: 25px;
}
.parent-bg { display: block; height: 100%; width: 100%;
position: absolute; top: 0px; left: 0px;
border: 1px solid white; z-index: 0;
}
.parent-bg:hover { border: 1px solid red; }
.child { display: block; position: relative; z-index: 1;
height: auto; width: auto; padding: 25px;
}
.child-bg { display: block; height: 100%; width: 100%;
position: absolute; top: 0px; left: 0px;
border: 1px solid white; z-index: 0;
}
.child-bg:hover { border: 1px solid red; }
.grandson { display: block; position: relative; z-index: 2;
height: auto; width: auto; padding: 25px;
}
.grandson-bg { display: block; height: 100%; width: 100%;
position: absolute; top: 0px; left: 0px;
border: 1px solid white; z-index: 0;
}
.grandson-bg:hover { border: 1px solid red; }
</style>
</head>
<body>
<div class="parent">
Parent
<div class="child">
Child
<div class="grandson">
Grandson
<div class="grandson-bg"></div>
</div>
<div class="child-bg"></div>
</div>
<div class="parent-bg"></div>
</div>
</body>
</html>
By omitting all parts of the head, the loop can also become infinite:
for (;;) {}
If you just want to embed an OSM map on a webpage, the easiest way is to get the iframe code directly from the OSM website:
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" _x000D_
src="https://www.openstreetmap.org/export/embed.html?bbox=-62.04673002474011%2C16.95487694424327%2C-61.60521696321666%2C17.196751341562923&layer=mapnik" _x000D_
style="border: 1px solid black"></iframe>_x000D_
<br/><small><a href="https://www.openstreetmap.org/#map=12/17.0759/-61.8260">View Larger Map</a></small>
_x000D_
If you want to do something more elaborate, see OSM wiki "Deploying your own Slippy Map".
$('#title').keyup(function () {
var replaceSpace = $(this).val();
var result = replaceSpace.replace(/\s/g, ";");
$("#keyword").val(result);
});
Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.
Stealing from Philip Roberts here:
Two examples:
1. Doubling all numbers in an array
Imperatively:
var numbers = [1,2,3,4,5]
var doubled = []
for(var i = 0; i < numbers.length; i++) {
var newNumber = numbers[i] * 2
doubled.push(newNumber)
}
console.log(doubled) //=> [2,4,6,8,10]
Declaratively:
var numbers = [1,2,3,4,5]
var doubled = numbers.map(function(n) {
return n * 2
})
console.log(doubled) //=> [2,4,6,8,10]
2. Summing all items in a list
Imperatively
var numbers = [1,2,3,4,5]
var total = 0
for(var i = 0; i < numbers.length; i++) {
total += numbers[i]
}
console.log(total) //=> 15
Declaratively
var numbers = [1,2,3,4,5]
var total = numbers.reduce(function(sum, n) {
return sum + n
});
console.log(total) //=> 15
Note how the imperative examples involve creating a new variable, mutating it, and returning that new value (i.e., how to make something happen), whereas the declarative examples execute on a given input and return the new value based on the initial input (i.e., what we want to happen).
If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). You can then sort these using one of the extension methods in System.Linq, e.g.:
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);
Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.
Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.
Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.
If you don't want to use numpy or a collections module you can use a dictionary:
d = dict()
a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
for item in a:
try:
d[item]+=1
except KeyError:
d[item]=1
result:
>>>d
{0: 8, 1: 4}
Of course you can also use an if/else statement. I think the Counter function does almost the same thing but this is more transparant.
Okay... so i know that i'm answering to a decade question, but wanted to add something! I wanted to add a google calendar with special iframe parameters. Problem is that the calendar didn't work without it. 30 seconds is a bit short for my use, so i changed that in my own file to 15 minutes This worked for me.
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.getElementById("calendar").src=calendar.src;
}
</script>
<iframe id="calendar" src="[URL]" style="border-width:0" width=100% height=100% frameborder="0" scrolling="no"></iframe>
Calling savefig before show() worked for me.
fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')
plt.savefig('figure.png')
plt.show()
Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.
If this has anything to do with money, do not use float or double, instead use BigDecimal.
I guess what you want is:
@title = tokens[Title]
@title.strip!
The #strip!
method will return nil
if it didn't strip anything, and the variable itself if it was stripped.
According to Ruby standards, a method suffixed with an exclamation mark changes the variable in place.
Hope this helps.
Update: This is output from irb
to demonstrate:
>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"
I succeeded by using a form control. This is my html code :
<md-input-container>
<input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
<md-error>Please enter a value between 0 and 100</md-error>
</md-input-container>
And in my Typescript code, I have :
this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])
So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
almost there, just change outerWidth: 100%;
to width: auto;
(outerWidth is not a CSS property)
alternatively, apply the following styles to bar:
width: auto;
display: block;
button2.Enabled == true ;
thats the problem - it should be:
button2.Enabled = true ;
What is the basic problem in your code?
Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like
ClassTwo obj;
This is because the compiler needs to reserve enough memory for object of type ClassTwo
to do so it needs to see the definition of ClassTwo
. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.
Why can't I simply put all code in cpp files and include them in other files?
You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.
How to solve this particular problem?
Your code should be organized as follows:
//File1.h
Define ClassOne
//File2.h
#include <iostream>
#include <string>
class ClassTwo
{
private:
string myType;
public:
void setType(string);
std::string getType();
};
//File1.cpp
#include"File1.h"
Implementation of ClassOne
//File2.cpp
#include"File2.h"
void ClassTwo::setType(std::string sType)
{
myType = sType;
}
void ClassTwo::getType(float fVal)
{
return myType;
}
//main.cpp
#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;
int main()
{
ClassOne cone;
ClassTwo ctwo;
//some codes
}
Is there any alternative means rather than including header files?
If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.
Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition
The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)
Code::where(function ($query) {
$query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');
})->get();
Look at DATEADD
SELECT DATEADD(mm, 1, OrderDate)AS TimeFrame
Here's the MSDN
In your case
...WHERE reference_dt = DATEADD(MM,1, myColDate)
You can pass custom http headers with RestTemplate exchange method as below.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);
RestTemplate template = new RestTemplate();
ResponseEntity<RestResponse> respEntity = template
.exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
EDIT : Below is the updated code. This link has several ways of calling rest service with examples
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);
Mall[] resp = respEntity.getBody();
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
you call function on page load time but not call on button event, you will need to call function onclick
event, you may add event inline element style or event bining
function Choice(elem) {_x000D_
var box = document.getElementById("box");_x000D_
if (elem.id == "no") {_x000D_
box.style.backgroundColor = "red";_x000D_
} else if (elem.id == "yes") {_x000D_
box.style.backgroundColor = "green";_x000D_
} else {_x000D_
box.style.backgroundColor = "purple";_x000D_
};_x000D_
};
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
or event binding,
window.onload = function() {_x000D_
var box = document.getElementById("box");_x000D_
document.getElementById("yes").onclick = function() {_x000D_
box.style.backgroundColor = "red";_x000D_
}_x000D_
document.getElementById("no").onclick = function() {_x000D_
box.style.backgroundColor = "green";_x000D_
}_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again
if npm version is < 5 then use npm cache clean --force
npm install -g @angular/cli@latest
and created a new project file and create a new angular project.
The following works for me on Snow Leopard:
Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);
Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,
Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Allows you to read the line-by-line output of the command pretty easily.
The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:
{"start", "cmd.exe", "\c"}
To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.
Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?
Would that require an IFNULL() and another SELECT statement for each field ?
The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.
If your backend support CORS, you probably need to add to your request this header:
headers: {"Access-Control-Allow-Origin": "*"}
[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.
But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.
You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
You can use a lambda expression, e.g:
sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.
http://<server>/svn/<module>
and not http://<server>/svn/
usvn
/<module>
. Is that /usvn/
directory suppose to be there?
For those experiencing issues after upgrading to MacOS Catalina.
Short version:
# 1a) Use tool: conda-prefix-replacement -
# Restores: Desktop -> Relocated Items -> Security -> anaconda3
curl -L https://repo.anaconda.com/pkgs/misc/cpr-exec/cpr-0.1.1-osx-64.exe -o cpr && chmod +x cpr
./cpr rehome ~/anaconda3
# or if fails
#./cpr rehome ~/anaconda3 --old-prefix /Anaconda3
source ~/anaconda3/bin/activate
# 1b) Alternatively - reintall anaconda -
# brew cask install anaconda
# 2) conda init
conda init zsh
# or
# conda init
Further reading - Anaconda blog post and Github discussion.
I have done this way:
Get Compressed Bitmap from Singleton class:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
imageView.setImageBitmap(bitmap);
ImageUtils.java:
public class ImageUtils {
public static ImageUtils mInstant;
public static ImageUtils getInstant(){
if(mInstant==null){
mInstant = new ImageUtils();
}
return mInstant;
}
public Bitmap getCompressedBitmap(String imagePath) {
float maxHeight = 1920.0f;
float maxWidth = 1080.0f;
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
byte[] byteArray = out.toByteArray();
Bitmap updatedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
return updatedBitmap;
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
Dimensions are same after compressing Bitmap.
How did I checked ?
Bitmap beforeBitmap = BitmapFactory.decodeFile("Your_Image_Path_Here");
Log.i("Before Compress Dimension", beforeBitmap.getWidth()+"-"+beforeBitmap.getHeight());
Bitmap afterBitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
Log.i("After Compress Dimension", afterBitmap.getWidth() + "-" + afterBitmap.getHeight());
Output:
Before Compress : Dimension: 1080-1452
After Compress : Dimension: 1080-1452
Hope this will help you.
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
Git has nothing to do with how you open/edit files in your project. Configuring the editor in git is only so that git internal things that require an editor (commit messages for example) can use your preferred editor.
If you just want to open files from the command line (cmd.exe) as if they were double clicked in the windows explorer, I think you can use start <filename>
.
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,_x000D_
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
msg = document.getElementById('msg'),_x000D_
onChange = function(ev){_x000D_
ev.preventDefault();_x000D_
let _this = this,_x000D_
arrVal = Array.prototype.slice.call(_x000D_
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
.map(function(cur){return cur.value});_x000D_
_x000D_
if(arrVal.length){_x000D_
msg.innerHTML = JSON.stringify(arrVal);_x000D_
} else {_x000D_
_this.checked=true;_x000D_
msg.innerHTML = "At least one value must be checked!";_x000D_
}_x000D_
};_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
To break out from a ruby block simply use return
keyword
return if value.nil?
If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function
then:
data = [7, 7, 7, 7]
print(*data, sep='')
Otherwise, you'll need to convert to string and print:
print ''.join(map(str, data))
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
I think this will helpful to you...
DECLARE @ConstraintName nvarchar(200)
SELECT
@ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'TABLE_NAME' AND
KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName)
It will delete foreign Key Constraint based on specific table and column.
You should reference System.Web and call:
HttpContext.Current.Server.MapPath(...)
If your date is in the format of a string use the explode function
array explode ( string $delimiter , string $string [, int $limit ] )
//In the case of your code
$length = strrpos($oldDate," ");
$newDate = explode( "-" , substr($oldDate,$length));
$output = $newDate[2]."/".$newDate[1]."/".$newDate[0];
Hope the above works now
You must set app:elevation="0dp"
in the android.support.design.widget.AppBarLayout
and then it works.
<android.support.design.widget.AppBarLayout
app:elevation="0dp"... >
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/transparent"
app:popupTheme="@style/AppTheme.PopupOverlay" >
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
The problem is that the Android emulator maps 10.0.2.2
to 127.0.0.1
, not to localhost
. So configure your web server to serveron 127.0.0.1:54722
and not localhost:54722
. That should do it.
Why not try fadeOut?
$(document).ready(function() {_x000D_
$('#plsme').fadeOut(5000); // 5 seconds x 1000 milisec = 5000 milisec_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='plsme'>Loading... Please Wait</div>
_x000D_
fadeOut (Javascript Pure):
Use keydown
, not keypress
for non-printable keys such as arrow keys:
function checkKey(e) {
e = e || window.event;
alert(e.keyCode);
}
document.onkeydown = checkKey;
The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
this is Extension to @Félix Brunet answer
Reason - there is code hidden in your app
How to find -
Eg - In my case i created 30 instances of winston log Unknowingly and it started giving error
Note : if u supress this error , it will come again afetr 3..4 days
If you work on Linux you can try this:
setwd(system("pwd", intern = T) )
It works for me.
Yes, in order for the z-index
to work, you'll need to give the element a position: absolute
or a position: relative
property.
You have to go up the nodes of the elements to check if at the level of the common parent the first descendants have a defined z-index.
All other descendants can never be in the foreground if at the base there is a lower definite z-index
.
In this snippet example, div1-2-1
has a z-index
of 1000 but is nevertheless under the div1-1-1
which has a z-index of 3.
This is because div1-1 has a z-index greater than div1-2.
.div {
}
#div1 {
z-index: 1;
position: absolute;
width: 500px;
height: 300px;
border: 1px solid black;
}
#div1-1 {
z-index: 2;
position: absolute;
left: 230px;
width: 200px;
height: 200px;
top: 31px;
background-color: indianred;
}
#div1-1-1 {
z-index: 3;
position: absolute;
top: 50px;
width: 100px;
height: 100px;
background-color: burlywood;
}
#div1-2 {
z-index: 1;
position: absolute;
width: 200px;
height: 200px;
left: 80px;
top: 5px;
background-color: red;
}
#div1-2-1 {
z-index: 1000;
position: absolute;
left: 70px;
width: 120px;
height: 100px;
top: 10px;
color: red;
background-color: lightyellow;
}
.blink {
animation: blinker 1s linear infinite;
}
@keyframes blinker {
50% {
opacity: 0;
}
}
.rotate {
writing-mode: vertical-rl;
padding-left: 50px;
font-weight: bold;
font-size: 20px;
}
_x000D_
<div class="div" id="div1">div1</br>z-index: 1
<div class="div" id="div1-1">div1-1</br>z-index: 2
<div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
</div>
<div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
<div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br> parent)</span></div>
</div>
</div>
_x000D_
if let
/if var
optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil
and only use the variable if it's non-nil
.
In your case, the tableView
parameter is declared as the non-optional type UITableView
. It is guaranteed to never be nil
. So optional binding here is unnecessary.
func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
myData.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
All we have to do is get rid of the if let
and change any occurrences of tv
within it to just tableView
.
What you want is org.mockito.Mockito.CALLS_REAL_METHODS
according to the docs:
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*/
Thus your code should look like:
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
public class StockTest {
public class Stock {
private final double price;
private final int quantity;
Stock(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public double getValue() {
return getPrice() * getQuantity();
}
}
@Test
public void getValueTest() {
Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
when(stock.getPrice()).thenReturn(100.00);
when(stock.getQuantity()).thenReturn(200);
double value = stock.getValue();
assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
}
}
The call to Stock stock = mock(Stock.class);
calls org.mockito.Mockito.mock(Class<T>)
which looks like this:
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}
The docs of the value RETURNS_DEFAULTS
tell:
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration.
* If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
*/
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved.As already noted by manu, XOR algorithm is a popular one which works for all integer values (that includes pointers then, with some luck and casting). For the sake of completeness I would like to mention another less powerful algorithm with addition/subtraction:
A = A + B
B = A - B
A = A - B
Here you have to be careful of overflows/underflows, but otherwise it works just as fine. You might even try this on floats/doubles in the case XOR isn't allowed on those.
RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).
While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:
Microsoft Internet Explorer (Browser)
Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.
Microsoft Edge (Browser)
The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge
Chrome
It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.
Firefox (Browser)
After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.
Safari (Browser)
At least 80,000 characters will work. Testing was not tried beyond that.
Opera (Browser)
At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable,
copyable and pasteable URL in the location bar even at 190,000 characters.
Apache (Server)
Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.
Microsoft Internet Information Server (Server)
The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.
Perl HTTP::Daemon (Server)
Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
[Android] if someone looking to implement timer on android using java.
you need use UI thread like this to perform operations.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ActivityName.this.runOnUiThread(new Runnable(){
@Override
public void run() {
// do something
}
});
}
}, 2000));
You cant set links to "disabled" just system elements like input, textfield etc.
But you can disable links with jQuery/JavaScript
$('.disabled').click(function(e){
e.preventDefault();
});
Just wrap the above code in whatever event you want to disable the links.
People often talk about performance, reads vs. writes, foreign keys, etc. but there's one other must-have feature for a storage engine in my opinion: atomic updates.
Try this:
killall -9 mysqld
to simulate a crash.Performance is desirable of course, but not losing data should trump that.
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
This also happens if you are trying to write a file, but your path is a folder.
This can happen easily by mistake.
To defend against that, use:
import os
path = r"my/path/to/file.txt"
assert os.path.isfile(path)
with open(path, "r") as f:
pass
The assertion will fail if your path is actually a folder.
Here is working example:
in head
<script type="text/javascript" src="jspdf.debug.js"></script>
script:
<script type="text/javascript">
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#customers')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, {// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}
, margins);
}
</script>
and table:
<div id="customers">
<table id="tab_customers" class="table table-striped" >
<colgroup>
<col width="20%">
<col width="20%">
<col width="20%">
<col width="20%">
</colgroup>
<thead>
<tr class='warning'>
<th>Country</th>
<th>Population</th>
<th>Date</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Chinna</td>
<td>1,363,480,000</td>
<td>March 24, 2014</td>
<td>19.1</td>
</tr>
<tr>
<td>India</td>
<td>1,241,900,000</td>
<td>March 24, 2014</td>
<td>17.4</td>
</tr>
<tr>
<td>United States</td>
<td>317,746,000</td>
<td>March 24, 2014</td>
<td>4.44</td>
</tr>
<tr>
<td>Indonesia</td>
<td>249,866,000</td>
<td>July 1, 2013</td>
<td>3.49</td>
</tr>
<tr>
<td>Brazil</td>
<td>201,032,714</td>
<td>July 1, 2013</td>
<td>2.81</td>
</tr>
</tbody>
</table>
</div>
and button to run:
<button onclick="javascript:demoFromHTML()">PDF</button>
and working example online:
or try this: HTML Table Export
using (FileStream fs = File.OpenRead(binarySourceFile.Path))
using (BinaryReader reader = new BinaryReader(fs))
{
// Read in all pairs.
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
Item item = new Item();
item.UniqueId = reader.ReadString();
item.StringUnique = reader.ReadString();
result.Add(item);
}
}
return result;
Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
The first issue is that you need to make sure that the end declaration for your heredoc -- EOD;
-- is not indented at all. If it is indented, then you will get errors.
As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)
To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:
<?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
Then you can include the logic directly in the string like you originally intended.
Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.
This is the Docker Hub page for Ubuntu and this is how it is created. It only has (somewhat) bare minimum packages installed, thus if you need anything extra you need to install it yourself.
apt-get update && apt-get install -y iputils-ping
However usually you'd create a "Dockerfile" and build it:
mkdir ubuntu_with_ping
cat >ubuntu_with_ping/Dockerfile <<'EOF'
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD bash
EOF
docker build -t ubuntu_with_ping ubuntu_with_ping
docker run -it ubuntu_with_ping
Please use Google to find tutorials and browse existing Dockerfiles to see how they usually do things :) For example image size should be minimized by running apt-get clean && rm -rf /var/lib/apt/lists/*
after apt-get install
commands.
There is a dedicated npm
package for it. css-scrollbar-side
Hey Its working for me..
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
$shell.Namespace("destination where files need to unzip").CopyHere($item)
}
I actually ended up with something like this to allow for the navbar collapse.
@media (min-width: 768px) { //set this to wherever the navbar collapse executes
.navbar-nav > li > a{
line-height: 7em; //set this height to the height of the logo.
}
}
Sorry for resurrecting an old thread, but I was with the same problem today. The simplest way that I have found is the following:
# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(0,0,0,6))
# Plot graph normally
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
# Plot legend where you want
legend(3.2,1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))
# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)
Found here: http://www.harding.edu/fmccown/R/
this is pretty simple:
HttpUtility.HtmlDecode(Model.Content)
Another Solution, you could also return a HTMLString, Razor will output the correct formatting:
in the view itself:
@Html.GetSomeHtml()
in controller:
public static HtmlString GetSomeHtml()
{
var Data = "abc<br/>123";
return new HtmlString(Data);
}
when we use the
php artisan serve
it will start with the default HTTP-server port mostly it will be 8000
when we want to run the more site in the localhost we have to change the port. Just add the --port argument:
php artisan serve --port=8081
private static boolean isPalindrome(String word) {
int z = word.length();
boolean isPalindrome = false;
for (int i = 0; i <= word.length() / 2; i++) {
if (word.charAt(i) == word.charAt(--z)) {
isPalindrome = true;
}
}
return isPalindrome;
}
I was using Postman to test my Laravel API.
I received an error that stated
"SQLSTATE[42S22]: Column not found: 1054 Unknown column" because Laravel was trying to automatically create two columns "created_at" and "updated_at".
I had to enter public $timestamps = false;
to my model. Then, I tested again with Postman and saw that an "id" = 0
variable was being created in my database.
I finally had to add public $incrementing false;
to fix my API.
I would like to mention the key before writing the code for your consideration.
//Key
temp= address of new node allocated by malloc function (member od alloc.h library in C )
prev= address of last node of existing link list.
next = contains address of next node
struct node {
int data;
struct node *next;
} *head;
void addnode_end(int a) {
struct node *temp, *prev;
temp = (struct node*) malloc(sizeof(node));
if (temp == NULL) {
cout << "Not enough memory";
} else {
node->data = a;
node->next = NULL;
prev = head;
while (prev->next != NULL) {
prev = prev->next;
}
prev->next = temp;
}
}
One common way is to add the image to a QLabel
widget using QLabel::setPixmap()
, and then display the QLabel
as you would any other widget. Example:
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPixmap pm("your-image.jpg");
QLabel lbl;
lbl.setPixmap(pm);
lbl.show();
return app.exec();
}
Here's how you do it
private fun sendNotification() {
val notificationId = 100
val chanelid = "chanelid"
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
val name = "my channel"
val description = "channel description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(chanelid, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(this, chanelid)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Want to Open My App?")
.setContentText("Open my app and see good things")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true) // cancel the notification when clicked
.addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent
val notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, mBuilder.build());
}
Read full tutorial at => https://developer.android.com/training/notify-user/build-notification
docker system prune -a
(You'll be asked to confirm the command. Use -f
to force run, if you know what you're doing.)
I will provide a detailed differences between Visual Studio and Visual Studio Code below.
If you really look at it the most obvious difference is that .NET has been split into two:
All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.
The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!
The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.
Visual Studio Code:
Visual Studio:
Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.
In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).
In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.
Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code
Similar to John Wilkey's answer I would run python2 by finding which python
, something like using /usr/bin/python
and then creating an alias in .bash_profile
:
alias python2="/usr/bin/python"
I can now run python3 by calling python
and python2 by calling python2
.
suppose supply_master is a table, and
SQL>desc supply_master;
SQL>Name
SUPPLIER_NO
SUPPLIER_NAME
ADDRESS1
ADDRESS2
CITY
STATE
PINCODE
SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered
SQL> desc Supply_master;
Name
-----------------------
SUPPLIER_NO
SUPPLIER_NAME
ADDR ///////////this has been renamed........//////////////
ADDRESS2
CITY
STATE
PINCODE
While specifying spellcheck="false" in the < tag > will certainly disable that feature, it's handy to be able to toggle that functionality on and off as needed after the page has loaded. So here's a non-jQuery way to set the spellcheck attribute programmatically:
:
<textarea id="my-ta" spellcheck="whatever">abcd dcba</textarea>
:
function setSpellCheck( mode ) {
var myTextArea = document.getElementById( "my-ta" )
, myTextAreaValue = myTextArea.value
;
myTextArea.value = '';
myTextArea.setAttribute( "spellcheck", String( mode ) );
myTextArea.value = myTextAreaValue;
myTextArea.focus();
}
:
setSpellCheck( true );
setSpellCheck( 'false' );
The function argument may be either boolean or string.
No need to loop through the textarea contents, we just cut 'n paste what's there, and then set focus.
Tested in blink engines (Chrome(ium), Edge, etc.)
By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?
The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:
this.dispose();
If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.
If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:
I use the first, and it works perfectly! It has a sample project to try it on.
I had the same problem on GoDaddy. I added the extension=pdo.so
to php.ini
, still didn't work. And then only one thing came to my mind: Permissions
Before uploading the file, kill all PHP processes(cPanel->PHP Processes).
The problem was that with the file permissions, it was set to 0644
and was not executable . You need to set the file permission at least 0755
.
In C++11 you can. A note beforehand: Don't new
the array, there's no need for that.
First, string[] strArray
is a syntax error, that should either be string* strArray
or string strArray[]
. And I assume that it's just for the sake of the example that you don't pass any size parameter.
#include <string>
void foo(std::string* strArray, unsigned size){
// do stuff...
}
template<class T>
using alias = T;
int main(){
foo(alias<std::string[]>{"hi", "there"}, 2);
}
Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
Note that this will only match stack arrays, like int x[5] = ...
. Or temporary ones, created by the use of alias
above.
int main(){
foo(alias<int[]>{1, 2, 3});
}
It seems some what center of the screen. So I would like to do like this
body {
background: url('http://oi44.tinypic.com/33tjudk.jpg') no-repeat center center fixed;
background-size:cover;
text-align: 0 auto; // Make the play button horizontal center
}
#play_button {
position:absolute; // absolutely positioned
transition: .5s ease;
top: 50%; // Makes vertical center
}
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40