Programs & Examples On #Savechanges

Error: the entity type requires a primary key

Removed and added back in the table using Scaffold-DbContext and the error went away

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Add services.AddSingleton(); in your ConfigureServices method of Startup.cs file of your project.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        // To register interface with its concrite type
        services.AddSingleton<IEmployee, EmployeesMockup>();
    }

For More details please visit this URL : https://www.youtube.com/watch?v=aMjiiWtfj2M

for All methods (i.e. AddSingleton vs AddScoped vs AddTransient) Please visit this URL: https://www.youtube.com/watch?v=v6Nr7Zman_Y&list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU&index=44)

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

public async Task<Product> GetValue(int id)
    {
        Product Products = await _context.Products.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
        return Products;
    }

AsNoTracking()

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

By Changing The DbContext As Below;

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    }

Just adding in OnModelCreating method call to base.OnModelCreating(modelBuilder); and it becomes fine. I am using EF6.

Special Thanks To #The Senator

How to set up a Web API controller for multipart/form-data

Here's another answer for the ASP.Net Core solution to this problem...

On the Angular side, I took this code example...

https://stackblitz.com/edit/angular-drag-n-drop-directive

... and modified it to call an HTTP Post endpoint:

  prepareFilesList(files: Array<any>) {

    const formData = new FormData();
    for (var i = 0; i < files.length; i++) { 
      formData.append("file[]", files[i]);
    }

    let URL = "https://localhost:44353/api/Users";
    this.http.post(URL, formData).subscribe(
      data => { console.log(data); },
      error => { console.log(error); }
    );

With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

[HttpPost]
public ActionResult Post()
{
  try
  {
    var files = Request.Form.Files;

    foreach (IFormFile file in files)
    {
        if (file.Length == 0)
            continue;
        
        string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
        System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");

        using (var fileStream = new FileStream(tempFilename, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
    return new OkObjectResult("Yes");
  }
  catch (Exception ex)
  {
    return new BadRequestObjectResult(ex.Message);
  }
}

Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

How to update record using Entity Framework 6?

This if for Entity Framework 6.2.0.

If you have a specific DbSet and an item that needs to be either updated or created:

var name = getNameFromService();

var current = _dbContext.Names.Find(name.BusinessSystemId, name.NameNo);
if (current == null)
{
    _dbContext.Names.Add(name);
}
else
{
    _dbContext.Entry(current).CurrentValues.SetValues(name);
}
_dbContext.SaveChanges();

However this can also be used for a generic DbSet with a single primary key or a composite primary key.

var allNames = NameApiService.GetAllNames();
GenericAddOrUpdate(allNames, "BusinessSystemId", "NameNo");

public virtual void GenericAddOrUpdate<T>(IEnumerable<T> values, params string[] keyValues) where T : class
{
    foreach (var value in values)
    {
        try
        {
            var keyList = new List<object>();

            //Get key values from T entity based on keyValues property
            foreach (var keyValue in keyValues)
            {
                var propertyInfo = value.GetType().GetProperty(keyValue);
                var propertyValue = propertyInfo.GetValue(value);
                keyList.Add(propertyValue);
            }

            GenericAddOrUpdateDbSet(keyList, value);
            //Only use this when debugging to catch save exceptions
            //_dbContext.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
    _dbContext.SaveChanges();
}

public virtual void GenericAddOrUpdateDbSet<T>(List<object> keyList, T value) where T : class
{
    //Get a DbSet of T type
    var someDbSet = Set(typeof(T));

    //Check if any value exists with the key values
    var current = someDbSet.Find(keyList.ToArray());
    if (current == null)
    {
        someDbSet.Add(value);
    }
    else
    {
        Entry(current).CurrentValues.SetValues(value);
    }
}

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

i mange to fix the issue by updating state. when you trigger find or any other query operation on the same record sate has been updated with modified so we need to set status to Detached then you can fire your update change

     ActivityEntity activity = new ActivityEntity();
      activity.name="vv";
    activity.ID = 22 ; //sample id
   var savedActivity = context.Activities.Find(22);

            if (savedActivity!=null)
            {
                context.Entry(savedActivity).State = EntityState.Detached;
                context.SaveChanges();

                activity.age= savedActivity.age;
                activity.marks= savedActivity.marks; 

                context.Entry(activity).State = EntityState.Modified;
                context.SaveChanges();
                return activity.ID;
            }

How are people unit testing with Entity Framework 6, should you bother?

I like to separate my filters from other portions of the code and test those as I outline on my blog here http://coding.grax.com/2013/08/testing-custom-linq-filter-operators.html

That being said, the filter logic being tested is not identical to the filter logic executed when the program is run due to the translation between the LINQ expression and the underlying query language, such as T-SQL. Still, this allows me to validate the logic of the filter. I don't worry too much about the translations that happen and things such as case-sensitivity and null-handling until I test the integration between the layers.

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

json parsing error syntax error unexpected end of input

I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don't need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

Entity Framework - Code First - Can't Store List<String>

I want to add that when using Npgsql (data provider for PostgreSQL), arrays and lists of primitive types are actually supported:

https://www.npgsql.org/efcore/mapping/array.html

Running an Excel macro via Python?

Hmm i was having some trouble with that part (yes still xD):

xl.Application.Run("excelsheet.xlsm!macroname.macroname")

cos im not using excel often (same with vb or macros, but i need it to use femap with python) so i finaly resolved it checking macro list: Developer -> Macros: there i saw that: this macroname.macroname should be sheet_name.macroname like in "Macros" list.

(i spend something like 30min-1h trying to solve it, so it may be helpful for noobs like me in excel) xD

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

Solve error javax.mail.AuthenticationFailedException

Most of AuthenticationFieldException Error occur when sign-in attempted prevented, login your gmail first and go to https://www.google.com/settings/security/lesssecureapps and check turn on. I solved this kind of problem like this way.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

Value cannot be null. Parameter name: source

I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.

At a guess, you'll need something like this:

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

DbEntityValidationException - How can I easily tell what caused the error?

I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.

I would prefer to create an extension method. More reasons to this:

  • Keep original stack trace
  • Follow open/closed principle (ie.: I can use different messages for different kind of logs)
  • In production environments there could be other places (ie.: other dbcontext) where a DbEntityValidationException could be thrown.

Entity Framework 5 Updating a Record

Just to add to the list of options. You can also grab the object from the database, and use an auto mapping tool like Auto Mapper to update the parts of the record you want to change..

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Entity Framework. Delete all rows in table

There are several issues with pretty much all the answers here:

1] Hard-coded sql. Will brackets work on all database engines?
2] Entity framework Remove and RemoveRange calls. This loads all entities into memory affected by the operation. Yikes.
3] Truncate table. Breaks with foreign key references and may not work accross all database engines.

Use https://entityframework-plus.net/, they handle the cross database platform stuff, translate the delete into the correct sql statement and don't load entities into memory, and the library is free and open source.

Disclaimer: I am not affiliated with the nuget package. They do offer a paid version that does even more stuff.

Automapper missing type map configuration or unsupported mapping - Error

In your class AutoMapper profile, you need to create a map for your entity and viewmodel.

ViewModel To Domain Model Mappings:

This is usually in AutoMapper/DomainToViewModelMappingProfile

In Configure(), add a line like

Mapper.CreateMap<YourEntityViewModel, YourEntity>();

Domain Model To ViewModel Mappings:

In ViewModelToDomainMappingProfile, add:

Mapper.CreateMap<YourEntity, YourEntityViewModel>();

Gist example

Handle ModelState Validation in ASP.NET Web API

Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)
     return BadRequest(ModelState);

Depending on the model errors, you get this result:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

This is an old thread, but another solution, which I prefer, is just update the cityId and not assign the hole model City to Employee... to do that Employee should look like:

public class Employee{
    ...
    public int? CityId; //The ? is for allow City nullable
    public virtual City City;
}

Then it's enough assigning:

e1.CityId=city1.ID;

How can I change the default width of a Twitter Bootstrap modal box?

For Bootstrap 3 here's how to do it.

Add a modal-wide style to your HTML markup (as adapted from the example in the Bootstrap 3 docs)

<div class="modal fade modal-wide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 id="myModalLabel" class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

and add the following CSS

.modal-wide .modal-dialog {
  width: 80%; /* or whatever you wish */
}

There is no need to override margin-left in Bootstrap 3 to get this to be centered now.

C# ASP.NET MVC Return to Previous Page

I know this is very late, but maybe this will help someone else.

I use a Cancel button to return to the referring url. In the View, try adding this:

@{
  ViewBag.Title = "Page title";
  Layout = "~/Views/Shared/_Layout.cshtml";

  if (Request.UrlReferrer != null)
  {
    string returnURL = Request.UrlReferrer.ToString();
    ViewBag.ReturnURL = returnURL;
  }
}

Then you can set your buttons href like this:

<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>

Other than that, the update by Jason Enochs works great!

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

just Check Your Database Table Field Length . Your Input Text Is Greater than the length of column field data type length

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This can also happen if data model is out of date.

Hopefully this will save someone else frustration :)

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Here is a way to do it without adding an ID to the form elements.

<form method="post">
    ...
    <select name="List">
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
    <select name="List">
        <option value="3">Test3</option>
        <option value="4">Test4</option>
    </select>
    ...
</form>

public ActionResult OrderProcessor()
{
    string[] ids = Request.Form.GetValues("List");
}

Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}

Hope this helps.

Improving bulk insert performance in Entity framework

Better way is to skip the Entity Framework entirely for this operation and rely on SqlBulkCopy class. Other operations can continue using EF as before.

That increases the maintenance cost of the solution, but anyway helps reduce time required to insert large collections of objects into the database by one to two orders of magnitude compared to using EF.

Here is an article that compares SqlBulkCopy class with EF for objects with parent-child relationship (also describes changes in design required to implement bulk insert): How to Bulk Insert Complex Objects into SQL Server Database

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.

I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

No code change required:

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (Ctrl+Alt+Q) and paste in there:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

or:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

If you are not in a try/catch or don't have access to the exception object.

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

How can I retrieve Id of inserted entity using Entity framework?

All answers are very well suited for their own scenarios, what i did different is that i assigned the int PK directly from object (TEntity) that Add() returned to an int variable like this;

using (Entities entities = new Entities())
{
      int employeeId = entities.Employee.Add(new Employee
                        {
                            EmployeeName = employeeComplexModel.EmployeeName,
                            EmployeeCreatedDate = DateTime.Now,
                            EmployeeUpdatedDate = DateTime.Now,
                            EmployeeStatus = true
                        }).EmployeeId;

      //...use id for other work
}

so instead of creating an entire new object, you just take what you want :)

EDIT For Mr. @GertArnold :

enter image description here

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 support 0001/1/1 through eternity.

Msdn

Answer: I suppose you try to save DateTime with '0001/1/1' value. Just set breakpoint and debug it, if so then replace DateTime with null or set normal date.

Closing Excel Application using VBA

To avoid the Save prompt message, you have to insert those lines

Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True

After saving your work, you need to use this line to quit the Excel application

Application.Quit

Don't just simply put those line in Private Sub Workbook_Open() unless you got do a correct condition checking, else you may spoil your excel file.

For safety purpose, please create a module to run it. The following are the codes that i put:

Sub testSave()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub

Hope it help you solve the problem.

The model backing the <Database> context has changed since the database was created

Create custom context initializer:

public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
    public override void InitializeDatabase(MyDbContext context)
    {
        bool exists = context.Database.Exists();

        base.InitializeDatabase(context);

        if (!exists)
        {         
            MyDbSeed.Seed(context);
        }
    }       
}

Note that Migrations.Configuration is a class generating by migration command line in Package Manager Console. You may need to change internal to public modifier of the Migrations.Configuration class.

And register it from your OmModelCreating:

public partial class MyDbContext : DbContext
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());

        //other code for creating model
    }
}

How do I delete multiple rows in Entity Framework (without foreach)

If you want to delete all rows of a table, you can execute sql command

using (var context = new DataDb())
{
     context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
}

TRUNCATE TABLE (Transact-SQL) Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.

How to delete an object by id with entity framework

Similar question here.

With Entity Framework there is EntityFramework-Plus (extensions library).
Available on NuGet. Then you can write something like:

// DELETE all users which has been inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
     .Delete();

It is also useful for bulk deletes.

How to resolve javax.mail.AuthenticationFailedException issue?

The problem is, you are creating a transport object and using it's connect method to authenticate yourself. But then you use a static method to send the message which ignores authentication done by the object.

So, you should either use the sendMessage(message, message.getAllRecipients()) method on the object or use an authenticator as suggested by others to get authorize through the session.

Here's the Java Mail FAQ, you need to read.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

use context.Database.BeginTransaction.

From MSDN:

using (var context = new BloggingContext()) 
{ 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
        try 
        { 
            context.Database.ExecuteSqlCommand( 
                @"UPDATE Blogs SET Rating = 5" + 
                    " WHERE Name LIKE '%Entity Framework%'" 
                ); 

            var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
            foreach (var post in query) 
            { 
                post.Title += "[Cool Blog]"; 
            } 

            context.SaveChanges(); 

            dbContextTransaction.Commit(); 
        } 
        catch (Exception) 
        { 
            dbContextTransaction.Rollback(); //Required according to MSDN article 
            throw; //Not in MSDN article, but recommended so the exception still bubbles up
        } 
    } 
} 

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

fopen deprecated warning

It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>

The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add _CRT_SECURE_NO_DEPRECATE to Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.

Getting Textbox value in Javascript

        <script type="text/javascript">
            function MyFunction() {
                var FNumber = Number(document.getElementById('txtFirstNumber').value);
                var SNumber = Number(document.getElementById("txtSecondNumber").value);
                var Sum = FNumber + SNumber;
                alert(Sum);
            }

        </script>

        <table class="auto-style1">
            <tr>
                <td>FirstNaumber</td>
                <td>
                    <asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>SecondNumber</td>
                <td>
                    <asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
                </td>
            </tr>
        </table>
    </div>
</form>

Dynamically Add Variable Name Value Pairs to JSON Object

From what the other answers have proposed, I believe this might help:

var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:

object["string"] = value;
//object = {string: value}

"The given path's format is not supported."

For me the problem was an invisible to human eye "?" Left-To-Right Embedding character.
It stuck at the beginning of the string (just before the 'D'), after I copy-pasted the path, from the windows file properties security tab.

var yourJson = System.IO.File.ReadAllText(@"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(@"?D:\test\json.txt"); // Error

So those, identical at first glance, two lines are actually different.

How to run a Python script in the background even after I logout SSH?

Running a Python Script in the Background

First, you need to add a shebang line in the Python script which looks like the following:

#!/usr/bin/env python3

This path is necessary if you have multiple versions of Python installed and /usr/bin/env will ensure that the first Python interpreter in your $$PATH environment variable is taken. You can also hardcode the path of your Python interpreter (e.g. #!/usr/bin/python3), but this is not flexible and not portable on other machines. Next, you’ll need to set the permissions of the file to allow execution:

chmod +x test.py

Now you can run the script with nohup which ignores the hangup signal. This means that you can close the terminal without stopping the execution. Also, don’t forget to add & so the script runs in the background:

nohup /path/to/test.py &

If you did not add a shebang to the file you can instead run the script with this command:

nohup python /path/to/test.py &

The output will be saved in the nohup.out file, unless you specify the output file like here:

nohup /path/to/test.py > output.log &
nohup python /path/to/test.py > output.log &

If you have redirected the output of the command somewhere else - including /dev/null - that's where it goes instead.

# doesn't create nohup.out

nohup command >/dev/null 2>&1   

If you're using nohup, that probably means you want to run the command in the background by putting another & on the end of the whole thing:

# runs in background, still doesn't create nohup.out

 nohup command >/dev/null 2>&1 &  

You can find the process and its process ID with this command:

ps ax | grep test.py

# or
# list of running processes Python

ps -fA | grep python

ps stands for process status

If you want to stop the execution, you can kill it with the kill command:

kill PID

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

CSS background image to fit width, height should auto-scale in proportion

body{
    background-image: url(../url/imageName.jpg);
    background-attachment: fixed;
    background-size: auto 100%;
    background-position: center;
}

Unknown version of Tomcat was specified in Eclipse

Probably, you are trying to point the tomcat directory having the source folder. Please download the tomcat binary version from here .For Linux environments, there you can find .zip and .tar.gz files under core section. Please download and extract them. after that, if you point this extracted directory, eclipse will be able to identify the tomcat version. Eclipse was not able to find the version of tomcat, since the directory you pointed out didn't contain the conf folder. Hope this helps!

Is it possible to focus on a <div> using JavaScript focus() function?

To make the border flash you can do this:

function focusTries() {
    document.getElementById('tries').style.border = 'solid 1px #ff0000;'
    setTimeout ( clearBorder(), 1000 );
}

function clearBorder() {
    document.getElementById('tries').style.border = '';
}

This will make the border solid red for 1 second then remove it again.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to set value to form control in Reactive Forms in Angular

In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).

setValue:

  • Initialize Model Structure in Constructor:

    this.newForm = this.formBuilder.group({  
       firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
       lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
    });
    
  • If you want to update all fields of form:

    this.newForm.setValue({
       firstName: 'abc',
       lastName: 'def'
    });
    
  • If you want to update specific field of form:

    this.newForm.controls.firstName.setValue('abc');
    

Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.

patchValue:

  • If you want to update some/ specific fields of form:

    this.newForm.patchValue({
       firstName: 'abc'
    });
    

Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

HTML input field hint

I think for your situation, the easy and simple for your html input , you can probably add the attribute title

<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">

Creating a new directory in C

I want to write a program that (...) creates the directory and a (...) file inside of it

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}

Is there an Eclipse plugin to run system shell in the Console?

I just found out about WickedShell, but it seems to work wrong with GNU/Linux and bash. Seems like some sort of encoding issue, all the characters in my prompt are displayed wrong.

Seems to be the best (only) tool for the job anyways, so I'll give it some more testing and see if it's good enough. I'll contact the developer anyways about this issue.

Python Unicode Encode Error

If you need to print an approximate representation of the string to the screen, rather than ignoring those nonprintable characters, please try unidecode package here:

https://pypi.python.org/pypi/Unidecode

The explanation is found here:

https://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/

This is better than using the u.encode('ascii', 'ignore') for a given string u, and can save you from unnecessary headache if character precision is not what you are after, but still want to have human readability.

Wirawan

Converting SVG to PNG using C#

To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.

    foreach(var child in svgDocument.Children)
    {
        SetFont(child);
    }

    public void SetFont(SvgElement element)
    {
        foreach(var child in element.Children)
        {
            SetFont(child); //Call this function again with the child, this will loop
                            //until the element has no more children
        }

        try
        {
            var svgText = (SvgText)parent; //try to cast the element as a SvgText
                                           //if it succeeds you can modify the font

            svgText.Font = new Font("Arial", 12.0f);
            svgText.FontSize = new SvgUnit(12.0f);
        }
        catch
        {

        }
    }

Let me know if there are questions.

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

Changing password with Oracle SQL Developer

You can now do this in SQL Developer 4.1.0.17, no PL/SQL required, assuming you have another account that has administrative privileges:

  1. Create a connection to the database in SQL Developer 4.1.0.17 with an alternative administrative user
  2. Expand the "Other Users" section once connected, and right-click the user whose password has expired. Choose "Edit User".
  3. Uncheck the "Password Expired..." checkbox, type in a new password for the user, and hit "Save".
  4. Job done! You can test by connecting with the user whose password had expired, to confirm it is now valid again.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I was only using full screen mode to hide the status bar. However, I want the app to resize when keyboard is shown. All of the other solutions (likely due to age of post) were complicated or not possible for my use (want to avoid change Java code for sack of PhoneGap Build).

Instead of using Full screen, I modified my configure for Android to be non-fullscreen:

            <preference name="fullscreen" value="false" />

And added the cordova-plugin-statusbar, via command line:

cordova plugin add cordova-plugin-statusbar

When app has loaded, I simple call a method on the plugin to hide itself, like:

    if (window.cordova && window.cordova.platformId == 'android' && window.StatusBar)
        window.StatusBar.hide();

This works like a charm. Only real downside is that the status bar is breifly visible while the app loads. For my needs, that wasn't an issue.

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

How to input matrix (2D list) in Python?

If you want to take n lines of input where each line contains m space separated integers like:

1 2 3
4 5 6 
7 8 9 

Then you can use:

a=[] // declaration 
for i in range(0,n):   //where n is the no. of lines you want 
 a.append([int(j) for j in input().split()])  // for taking m space separated integers as input

Then print whatever you want like for the above input:

print(a[1][1]) 

O/P would be 5 for 0 based indexing

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

How to cancel a Task in await?

One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.

public async Task<Results> ProcessDataAsync(MyData data)
{
    var client = await GetClientAsync();
    await client.UploadDataAsync(data);
    await client.CalculateAsync();
    return await client.GetResultsAsync();
}

If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.

public static class TaskExtensions
{
    public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        await Task.WhenAny(task, token.WhenCanceled());
        token.ThrowIfCancellationRequested();

        return await task;
    }

    public static Task WhenCanceled(this CancellationToken cancellationToken)
    {
        var tcs = new TaskCompletionSource<bool>();
        cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
        return tcs.Task;
    }
}

So to use it then just add .WaitOrCancel(token) to any async call:

public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
{
    Client client;
    try
    {
        client = await GetClientAsync().WaitOrCancel(token);
        await client.UploadDataAsync(data).WaitOrCancel(token);
        await client.CalculateAsync().WaitOrCancel(token);
        return await client.GetResultsAsync().WaitOrCancel(token);
    }
    catch (OperationCanceledException)
    {
        if (client != null)
            await client.CancelAsync();
        throw;
    }
}

Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync call in the example, or better yet pass in the same CancellationToken to the Task so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Git - How to fix "corrupted" interactive rebase?

In my case it was because I had opened SmartGit's Log in the respective Git project and Total Commander in the respective project directory. When I closed both I was able to rebase without any problem.

The more I think about it, the more I suspect Total Commander, i.e. Windows having a lock on opened directory the git rebase was trying to something with.

Friendly advice: When you try to fix something, always do one change at a time. ;)

Android Device Chooser -- device not showing up

Okay... so I could never get my PENDO pad to show up.. until I encountered this..

process android.process.acore has stopped..

Yeah.. nothing to do with this issue right? Ah ah but it lead me to MOBILEGO. It's a desk application that lets you admin your device.. Guess how.. by connecting via USB. Yep and it does.. It installed everything on my windows box, and now Eclipse has no problem seeing my PENDO.

How to right-align and justify-align in Markdown?

If you want to use this answer, I found out that when you are using MacDown on MacOs, you can <div style="text-align: justify"> at the beginning of the document to justify all text and keep all code formating. Maybe it works on other editors too, for you to try ;)

Jquery validation plugin - TypeError: $(...).validate is not a function

for me, the problem was from require('jquery-validation') i added in the begging of that js file which Validate method used which is necessary as an npm module

unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes

so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

How can I set Image source with base64

Your problem are the cr (carriage return)

http://jsfiddle.net/NT9KB/210/

you can use:

document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

Remove border radius from Select tag in bootstrap 3

Using the SVG from @ArnoTenkink as an data url combined with the accepted answer, this gives us the perfect solution for retina displays.

select.form-control:not([multiple]) {
    border-radius: 0;
    appearance: none;
    background-position: right 50%;
    background-repeat: no-repeat;
    background-image: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%20%3C%21DOCTYPE%20svg%20PUBLIC%20%22-//W3C//DTD%20SVG%201.1//EN%22%20%22http%3A//www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22%3E%20%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2214px%22%20height%3D%2212px%22%20viewBox%3D%220%200%2014%2012%22%20enable-background%3D%22new%200%200%2014%2012%22%20xml%3Aspace%3D%22preserve%22%3E%20%3Cpolygon%20points%3D%223.862%2C7.931%200%2C4.069%207.725%2C4.069%20%22/%3E%3C/svg%3E);
    padding: .5em;
    padding-right: 1.5em
}

Rank function in MySQL

The most straight forward solution to determine the rank of a given value is to count the number of values before it. Suppose we have the following values:

10 20 30 30 30 40
  • All 30 values are considered 3rd
  • All 40 values are considered 6th (rank) or 4th (dense rank)

Now back to the original question. Here is some sample data which is sorted as described in OP (expected ranks are added on the right):

+------+-----------+------+--------+    +------+------------+
| id   | firstname | age  | gender |    | rank | dense_rank |
+------+-----------+------+--------+    +------+------------+
|   11 | Emily     |   20 | F      |    |    1 |          1 |
|    3 | Grace     |   25 | F      |    |    2 |          2 |
|   20 | Jill      |   25 | F      |    |    2 |          2 |
|   10 | Megan     |   26 | F      |    |    4 |          3 |
|    8 | Lucy      |   27 | F      |    |    5 |          4 |
|    6 | Sarah     |   30 | F      |    |    6 |          5 |
|    9 | Zoe       |   30 | F      |    |    6 |          5 |
|   14 | Kate      |   35 | F      |    |    8 |          6 |
|    4 | Harry     |   20 | M      |    |    1 |          1 |
|   12 | Peter     |   20 | M      |    |    1 |          1 |
|   13 | John      |   21 | M      |    |    3 |          2 |
|   16 | Cole      |   25 | M      |    |    4 |          3 |
|   17 | Dennis    |   27 | M      |    |    5 |          4 |
|    5 | Scott     |   30 | M      |    |    6 |          5 |
|    7 | Tony      |   30 | M      |    |    6 |          5 |
|    2 | Matt      |   31 | M      |    |    8 |          6 |
|   15 | James     |   32 | M      |    |    9 |          7 |
|    1 | Adams     |   33 | M      |    |   10 |          8 |
|   18 | Smith     |   35 | M      |    |   11 |          9 |
|   19 | Zack      |   35 | M      |    |   11 |          9 |
+------+-----------+------+--------+    +------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for Sarah, you can use this query:

SELECT COUNT(id) + 1 AS rank, COUNT(DISTINCT age) + 1 AS dense_rank
FROM testdata
WHERE gender = (SELECT gender FROM testdata WHERE id = 6)
AND age < (SELECT age FROM testdata WHERE id = 6)

+------+------------+
| rank | dense_rank |
+------+------------+
|    6 |          5 |
+------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for All rows you can use this query:

SELECT testdata.id, COUNT(lesser.id) + 1 AS rank, COUNT(DISTINCT lesser.age) + 1 AS dense_rank
FROM testdata
LEFT JOIN testdata AS lesser ON lesser.age < testdata.age AND lesser.gender = testdata.gender
GROUP BY testdata.id

And here is the result (joined values are added on right):

+------+------+------------+    +-----------+-----+--------+
| id   | rank | dense_rank |    | firstname | age | gender |
+------+------+------------+    +-----------+-----+--------+
|   11 |    1 |          1 |    | Emily     |  20 | F      |
|    3 |    2 |          2 |    | Grace     |  25 | F      |
|   20 |    2 |          2 |    | Jill      |  25 | F      |
|   10 |    4 |          3 |    | Megan     |  26 | F      |
|    8 |    5 |          4 |    | Lucy      |  27 | F      |
|    6 |    6 |          5 |    | Sarah     |  30 | F      |
|    9 |    6 |          5 |    | Zoe       |  30 | F      |
|   14 |    8 |          6 |    | Kate      |  35 | F      |
|    4 |    1 |          1 |    | Harry     |  20 | M      |
|   12 |    1 |          1 |    | Peter     |  20 | M      |
|   13 |    3 |          2 |    | John      |  21 | M      |
|   16 |    4 |          3 |    | Cole      |  25 | M      |
|   17 |    5 |          4 |    | Dennis    |  27 | M      |
|    5 |    6 |          5 |    | Scott     |  30 | M      |
|    7 |    6 |          5 |    | Tony      |  30 | M      |
|    2 |    8 |          6 |    | Matt      |  31 | M      |
|   15 |    9 |          7 |    | James     |  32 | M      |
|    1 |   10 |          8 |    | Adams     |  33 | M      |
|   18 |   11 |          9 |    | Smith     |  35 | M      |
|   19 |   11 |          9 |    | Zack      |  35 | M      |
+------+------+------------+    +-----------+-----+--------+

Git: How to remove file from index without deleting files from any repository

My solution is to pull on the other working copy and then do:

git log --pretty="format:" --name-only -n1 | xargs git checkout HEAD^1

which says get all the file paths in the latest comment, and check them out from the parent of HEAD. Job done.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).

This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.

Hidden features of Windows batch files

Bail on error.

IF "%errorlevel%" NEQ "0" (
   echo "ERROR:  Something broke.  Bailing out."
   exit /B 1
)

How to send an email from JavaScript

Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.

How to set base url for rest in spring boot?

With Spring Boot 1.2+ (<2.0) all it takes is a single property in application.properties:

spring.data.rest.basePath=/api

ref link : https://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-started.changing-base-uri

For 2.x, use

server.servlet.context-path=/api

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

Windows 7 environment variable not working in path

If there is any error at all in the PATH windows will silently disregard it. Things like having %PATH% or spaces between items in your path will break it. Be warned

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

Setting core.filemode to false does work, but make sure the settings in ~/.gitconfig aren't being overridden by those in .git/config.

Trigger a keypress/keydown/keyup event in JS/jQuery?

First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.

function triggerEvent(el, type, keyCode) {
    if ('createEvent' in document) {
            // modern browsers, IE9+
            var e = document.createEvent('HTMLEvents');
            e.keyCode = keyCode;
            e.initEvent(type, false, true);
            el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.keyCode = keyCode;
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press

How to restore the dump into your running mongodb

I have been through a lot of trouble so I came up with my own solution, I created this script, just set the path inside script and db name and run it, it will do the trick

#!/bin/bash

FILES= #absolute or relative path to dump directory
DB=`db` #db name
for file in $FILES
do

    name=$(basename $file)
    collection="${name%.*}"
    echo `mongoimport --db "$DB" --file "$name" --collection "$collection"`

done

How can I get my webapp's base URL in ASP.NET MVC?

So none of the ones listed here worked for me, but using a few of the answers, I got something working:

public string GetBaseUrl()
{
    var request = HttpContext.Current.Request;
    var appUrl = HttpRuntime.AppDomainAppVirtualPath;

    if (appUrl != "/") 
        appUrl = "/" + appUrl;

    var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

    return baseUrl;
}

Update for ASP.NET Core / MVC 6:

ASP.NET Core makes this process a bit more painful, especially if you are deep in your code. You have 2 options to get at the HttpContext

1) Pass it in from your controller:

var model = new MyClass(HttpContext);

then in model:

private HttpContext currentContext;

public MyClass(HttpContext currentContext)
{
    this.currentContext = currentContext;
}

2) Perhaps the cleaner way is to inject it into your class, which starts with registering the types in your Startup:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddTransient<MyClass, MyClass>();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

then have it injected for you like this:

private HttpContext currentContext;

public MyClass(IHttpContextAccessor httpContextAccessor)
{
    currentContext = httpContextAccessor.HttpContext;
}

in either case, here is the updated for .NET Core GetBaseUrl():

public string GetBaseUrl()
{
    var request = currentContext.Request;

    var host = request.Host.ToUriComponent();

    var pathBase = request.PathBase.ToUriComponent();

    return $"{request.Scheme}://{host}{pathBase}";
}

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

MySQL: Insert datetime into other datetime field

Try

    UPDATE products SET former_date=20111218131717 WHERE id=1

Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.

How to get JSON response from http.Get

The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target structure.

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

Example use:

type Foo struct {
    Bar string
}

func main() {
    foo1 := new(Foo) // or &Foo{}
    getJson("http://example.com", foo1)
    println(foo1.Bar)

    // alternately:

    foo2 := Foo{}
    getJson("http://example.com", &foo2)
    println(foo2.Bar)
}

You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

SQL query to select dates between two dates

select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

Annotations from javax.validation.constraints not working

I came across this problem recently in a very similar situation: Met all requirements as the top-rated answer listed but still got the wrong result.

So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.

I was using hibernate, the required dependencies were: Dependencies Snapshot

*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy

How to edit an Android app?

Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.

That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).

Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.

Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.

There are possible ways to decompile Java programs. You can use dex2jar, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.

However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.

The tools are always out there. But the conscience, unfortunately, not always.

edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).

Declaring variables inside loops, good practice or bad practice?

Once upon a time (pre C++98); the following would break:

{
    for (int i=0; i<.; ++i) {std::string foo;}
    for (int i=0; i<.; ++i) {std::string foo;}
}

with the warning that i was already declared (foo was fine as that's scoped within the {}). This is likely the WHY people would first argue it's bad. It stopped being true a long time ago though.

If you STILL have to support such an old compiler (some people are on Borland) then the answer is yes, a case could be made to put the i out the loop, because not doing so makes it makes it "harder" for people to put multiple loops in with the same variable, though honestly the compiler will still fail, which is all you want if there's going to be a problem.

If you no longer have to support such an old compiler, variables should be kept to the smallest scope you can get them so that you not only minimise the memory usage; but also make understanding the project easier. It's a bit like asking why don't you have all your variables global. Same argument applies, but the scopes just change a bit.

How to find if an array contains a specific string in JavaScript/jQuery?

Here you go:

$.inArray('specialword', arr)

This function returns a positive integer (the array index of the given value), or -1 if the given value was not found in the array.

Live demo: http://jsfiddle.net/simevidas/5Gdfc/

You probably want to use this like so:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}

Cropping an UIImage

Looks a little bit strange but works great and takes into consideration image orientation:

var image:UIImage = ...

let img = CIImage(image: image)!.imageByCroppingToRect(rect)
image = UIImage(CIImage: img, scale: 1, orientation: image.imageOrientation)

How to split string using delimiter char using T-SQL?

For your specific data, you can use

Select col1, col2, LTRIM(RTRIM(SUBSTRING(
    STUFF(col3, CHARINDEX('|', col3,
    PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
    PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01

EDIT - charindex vs patindex

Test

select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)

set statistics time on

dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1

dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2

set statistics time off

Timings

CHARINDEX:

 SQL Server Execution Times (1):
   CPU time = 5656 ms,  elapsed time = 6418 ms.
 SQL Server Execution Times (2):
   CPU time = 5813 ms,  elapsed time = 6114 ms.
 SQL Server Execution Times (3):
   CPU time = 5672 ms,  elapsed time = 6108 ms.

PATINDEX:

 SQL Server Execution Times (1):
   CPU time = 5906 ms,  elapsed time = 6296 ms.
 SQL Server Execution Times (2):
   CPU time = 5860 ms,  elapsed time = 6404 ms.
 SQL Server Execution Times (3):
   CPU time = 6109 ms,  elapsed time = 6301 ms.

Conclusion

The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.

Excel - Shading entire row based on change of value

If you are using MS Excel 2007, you could use the conditional formatting on the Home tab as shown in the screenshot below. You could either use the color scales default option as I have done here or you can go ahead and create a new rule based on your data set. Conditional Formatting

Flexbox: center horizontally and vertically

How to Center Elements Vertically and Horizontally in Flexbox

Below are two general centering solutions.

One for vertically-aligned flex items (flex-direction: column) and the other for horizontally-aligned flex items (flex-direction: row).

In both cases the height of the centered divs can be variable, undefined, unknown, whatever. The height of the centered divs doesn't matter.

Here's the HTML for both:

<div id="container"><!-- flex container -->

    <div class="box" id="bluebox"><!-- flex item -->
        <p>DIV #1</p>
    </div>

    <div class="box" id="redbox"><!-- flex item -->
        <p>DIV #2</p>
    </div>

</div>

CSS (excluding decorative styles)

When flex items are stacked vertically:

#container {
    display: flex;           /* establish flex container */
    flex-direction: column;  /* make main axis vertical */
    justify-content: center; /* center items vertically, in this case */
    align-items: center;     /* center items horizontally, in this case */
    height: 300px;
}

.box {
    width: 300px;
    margin: 5px;
    text-align: center;     /* will center text in <p>, which is not a flex item */
}

enter image description here

DEMO


When flex items are stacked horizontally:

Adjust the flex-direction rule from the code above.

#container {
    display: flex;
    flex-direction: row;     /* make main axis horizontal (default setting) */
    justify-content: center; /* center items horizontally, in this case */
    align-items: center;     /* center items vertically, in this case */
    height: 300px;
}

enter image description here

DEMO


Centering the content of the flex items

The scope of a flex formatting context is limited to a parent-child relationship. Descendants of a flex container beyond the children do not participate in flex layout and will ignore flex properties. Essentially, flex properties are not inheritable beyond the children.

Hence, you will always need to apply display: flex or display: inline-flex to a parent element in order to apply flex properties to the child.

In order to vertically and/or horizontally center text or other content contained in a flex item, make the item a (nested) flex container, and repeat the centering rules.

.box {
    display: flex;
    justify-content: center;
    align-items: center;        /* for single line flex container */
    align-content: center;      /* for multi-line flex container */
}

More details here: How to vertically align text inside a flexbox?

Alternatively, you can apply margin: auto to the content element of the flex item.

p { margin: auto; }

Learn about flex auto margins here: Methods for Aligning Flex Items (see box#56).


Centering multiple lines of flex items

When a flex container has multiple lines (due to wrapping) the align-content property will be necessary for cross-axis alignment.

From the spec:

8.4. Packing Flex Lines: the align-content property

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container.

More details here: How does flex-wrap work with align-self, align-items and align-content?


Browser support

Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.


Centering solution for older browsers

For an alternative centering solution using CSS table and positioning properties see this answer: https://stackoverflow.com/a/31977476/3597276

Google maps API V3 method fitBounds()

 var map = new google.maps.Map(document.getElementById("map"),{
                mapTypeId: google.maps.MapTypeId.ROADMAP

            });
var bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++){
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
bounds.extend(marker.position);
}
map.fitBounds(bounds);

PHP check if date between two dates

Edit: use <= or >= to count today's date.

This is the right answer for your code. Just use the strtotime() php function.

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}

Cast IList to List

This is the best option to cast/convert list of generic object to list of string.

object valueList;
List<string> list = ((IList)valueList).Cast<object>().Select(o => o.ToString()).ToList();

How to manage a redirect request after a jQuery Ajax call

in the servlet you should put response.setStatus(response.SC_MOVED_PERMANENTLY); to send the '301' xmlHttp status you need for a redirection...

and in the $.ajax function you should not use the .toString() function..., just

if (xmlHttp.status == 301) { top.location.href = 'xxxx.jsp'; }

the problem is it is not very flexible, you can't decide where you want to redirect..

redirecting through the servlets should be the best way. but i still can not find the right way to do it.

Retrieving a property of a JSON object by index?

You could iterate over the object and assign properties to indexes, like this:

var lookup = [];
var i = 0;

for (var name in obj) {
    if (obj.hasOwnProperty(name)) {
        lookup[i] = obj[name];
        i++;
    }
}

lookup[2] ...

However, as the others have said, the keys are in principle unordered. If you have code which depends on the corder, consider it a hack. Make sure you have unit tests so that you will know when it breaks.

How do I run all Python unit tests in a directory?

Here is my approach by creating a wrapper to run tests from the command line:

#!/usr/bin/env python3
import os, sys, unittest, argparse, inspect, logging

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument("-d", "--debug",    action="store_true", dest="debug",    help="show debug messages" )
    parser.add_argument("-h", "--host",     action="store",      dest="host",     help="Destination host" )
    parser.add_argument("-b", "--browser",  action="store",      dest="browser",  help="Browser driver.", choices=["Firefox", "Chrome", "IE", "Opera", "PhantomJS"] )
    parser.add_argument("-r", "--reports-dir", action="store",   dest="dir",      help="Directory to save screenshots.", default="reports")
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    # Load files from the arguments.
    for filename in args.files:
        exec(open(filename).read())

    # See: http://codereview.stackexchange.com/q/88655/15346
    def make_suite(tc_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(tc_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(tc_class(name, cargs=args))
        return suite

    # Add all tests.
    alltests = unittest.TestSuite()
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name.startswith("FooTest"):
            alltests.addTest(make_suite(obj))

    # Set-up logger
    verbose = bool(os.environ.get('VERBOSE', args.verbose))
    debug   = bool(os.environ.get('DEBUG', args.debug))
    if verbose or debug:
        logging.basicConfig( stream=sys.stdout )
        root = logging.getLogger()
        root.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
        root.addHandler(ch)
    else:
        logging.basicConfig(stream=sys.stderr)

    # Run tests.
    result = unittest.TextTestRunner(verbosity=2).run(alltests)
    sys.exit(not result.wasSuccessful())

For sake of simplicity, please excuse my non-PEP8 coding standards.

Then you can create BaseTest class for common components for all your tests, so each of your test would simply look like:

from BaseTest import BaseTest
class FooTestPagesBasic(BaseTest):
    def test_foo(self):
        driver = self.driver
        driver.get(self.base_url + "/")

To run, you simply specifying tests as part of the command line arguments, e.g.:

./run_tests.py -h http://example.com/ tests/**/*.py

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

In case if you're trying to deploy a project using VSTS, then issue might be connected with checking "Hosted Windows Container" option instead of "Hosted VS2017"(or 18, etc.):

enter image description here

Disable all table constraints in Oracle

To take in count the dependencies between the constraints:

SET Serveroutput ON
BEGIN
    FOR c IN
    (SELECT c.owner,c.table_name,c.constraint_name
    FROM user_constraints c,user_tables t
    WHERE c.table_name=t.table_name
    AND c.status='ENABLED'
    ORDER BY c.constraint_type DESC,c.last_change DESC
    )
    LOOP
        FOR D IN
        (SELECT P.Table_Name Parent_Table,C1.Table_Name Child_Table,C1.Owner,P.Constraint_Name Parent_Constraint,
            c1.constraint_name Child_Constraint
        FROM user_constraints p
        JOIN user_constraints c1 ON(p.constraint_name=c1.r_constraint_name)
        WHERE(p.constraint_type='P'
        OR p.constraint_type='U')
        AND c1.constraint_type='R'
        AND p.table_name=UPPER(c.table_name)
        )
        LOOP
            dbms_output.put_line('. Disable the constraint ' || d.Child_Constraint ||' (on table '||d.owner || '.' ||
            d.Child_Table || ')') ;
            dbms_utility.exec_ddl_statement('alter table ' || d.owner || '.' ||d.Child_Table || ' disable constraint ' ||
            d.Child_Constraint) ;
        END LOOP;
    END LOOP;
END;
/

ComboBox SelectedItem vs SelectedValue

This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).

Anyway, I hope that helps =D

CSS strikethrough different color from text?

Here's an approach which uses a gradient to fake the line. It works with multiline strikes and doesn't need additional DOM elements. But as it's a background gradient, it's behind the text...

del, strike {
  text-decoration: none;
  line-height: 1.4;
  background-image: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.63em, transparent), color-stop(0.63em, #ff0000), color-stop(0.7em, #ff0000), color-stop(0.7em, transparent), to(transparent));
  background-image: -webkit-linear-gradient(top, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
  background-image: -o-linear-gradient(top, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
  background-image: linear-gradient(to bottom, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
  -webkit-background-size: 1.4em 1.4em;
  background-size: 1.4em 1.4em;
  background-repeat: repeat;
}

See fiddle: http://jsfiddle.net/YSvaY/

Gradient color-stops and background size depend on line-height. (I used LESS for calculation and Autoprefixer afterwards...)

Install opencv for Python 3.3

Someone has published a docker container / file for this:

https://github.com/vipul-sharma20/docker-opencv3-python3

https://hub.docker.com/r/vipul20/docker-opencv3-python3/~/dockerfile/

You can pull the image directly from docker hub or follow the instructions in the Dockerfile to install.

Best way to convert strings to symbols in hash

In Rails you can use:

{'g'=> 'a', 2 => {'v' => 'b', 'x' => { 'z' => 'c'}}}.deep_symbolize_keys!

Converts to:

{:g=>"a", 2=>{:v=>"b", :x=>{:z=>"c"}}}

Convert java.util.Date to String

One Line option

This option gets a easy one-line to write the actual date.

Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not logical to use it under Java8.

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

What does the symbol \0 mean in a string-literal?

What is the length of str array, and with how much 0s it is ending?

Let's find out:

int main() {
  char str[] = "Hello\0";
  int length = sizeof str / sizeof str[0];
  // "sizeof array" is the bytes for the whole array (must use a real array, not
  // a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
  // to get the number of items in the array
  printf("array length: %d\n", length);
  printf("last 3 bytes: %02x %02x %02x\n",
         str[length - 3], str[length - 2], str[length - 1]);
  return 0;
}

Moving items around in an ArrayList

I came across this old question in my search for an answer, and I thought I would just post the solution I found in case someone else passes by here looking for the same.

For swapping 2 elements, Collections.swap is fine. But if we want to move more elements, there is a better solution that involves a creative use of Collections.sublist and Collections.rotate that I hadn't thought of until I saw it described here:

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29

Here's a quote, but go there and read the whole thing for yourself too:

Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j):

Collections.rotate(list.subList(j, k+1), -1);

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

The SQL OVER() clause - when and why is it useful?

If you only wanted to GROUP BY the SalesOrderID then you wouldn't be able to include the ProductID and OrderQty columns in the SELECT clause.

The PARTITION BY clause let's you break up your aggregate functions. One obvious and useful example would be if you wanted to generate line numbers for order lines on an order:

SELECT
    O.order_id,
    O.order_date,
    ROW_NUMBER() OVER(PARTITION BY O.order_id) AS line_item_no,
    OL.product_id
FROM
    Orders O
INNER JOIN Order_Lines OL ON OL.order_id = O.order_id

(My syntax might be off slightly)

You would then get back something like:

order_id    order_date    line_item_no    product_id
--------    ----------    ------------    ----------
    1       2011-05-02         1              5
    1       2011-05-02         2              4
    1       2011-05-02         3              7
    2       2011-05-12         1              8
    2       2011-05-12         2              1

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    'Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

What are carriage return, linefeed, and form feed?

Carriage return means to return to the beginning of the current line without advancing downward. The name comes from a printer's carriage, as monitors were rare when the name was coined. This is commonly escaped as \r, abbreviated CR, and has ASCII value 13 or 0x0D.

Linefeed means to advance downward to the next line; however, it has been repurposed and renamed. Used as "newline", it terminates lines (commonly confused with separating lines). This is commonly escaped as \n, abbreviated LF or NL, and has ASCII value 10 or 0x0A. CRLF (but not CRNL) is used for the pair \r\n.

Form feed means advance downward to the next "page". It was commonly used as page separators, but now is also used as section separators. (It's uncommonly used in source code to divide logically independent functions or groups of functions.) Text editors can use this character when you "insert a page break". This is commonly escaped as \f, abbreviated FF, and has ASCII value 12 or 0x0C.


As control characters, they may be interpreted in various ways.

The most common difference (and probably the only one worth worrying about) is lines end with CRLF on Windows, NL on Unix-likes, and CR on older Macs (the situation has changed with OS X to be like Unix). Note the shift in meaning from LF to NL, for the exact same character, gives the differences between Windows and Unix. (Windows is, of course, newer than Unix, so it didn't adopt this semantic shift. I don't know the history of Macs using CR.) Many text editors can read files in any of these three formats and convert between them, but not all utilities can.

Form feed is a bit more interesting (even though less commonly used directly), and with the usual definition of page separator, it can only come between lines (e.g. after the newline sequence of NL, CRLF, or CR) or at the start or end of the file.

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

sqlalchemy: how to join several tables by one query?

As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...

If you're interested in writing a query along the lines of:

SELECT
    user.email,
    user.name,
    document.name,
    documents_permissions.readAllowed,
    documents_permissions.writeAllowed
FROM
    user, document, documents_permissions
WHERE
    user.email = "[email protected]";

Then you should go for something like:

session.query(
    User, 
    Document, 
    DocumentsPermissions
).filter(
    User.email == Document.author
).filter(
    Document.name == DocumentsPermissions.document
).filter(
    User.email == "[email protected]"
).all()

If instead, you want to do something like:

SELECT 'all the columns'
FROM user
JOIN document ON document.author_id = user.id AND document.author == User.email
JOIN document_permissions ON document_permissions.document_id = document.id AND document_permissions.document = document.name

Then you should do something along the lines of:

session.query(
    User
).join(
    Document
).join(
    DocumentsPermissions
).filter(
    User.email == "[email protected]"
).all()

One note about that...

query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses)                    # specify relationship from left to right
query.join(Address, User.addresses)           # same, with explicit target
query.join('addresses')                       # same, using a string

For more information, visit the docs.

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

How to convert string to boolean php

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):

  1. "" (an empty string);
  2. "0" (0 as a string)

If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.

$test_mode_mail = $string === 'true'? true: false;

EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:

$test_mode_mail = ($string === 'true');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on". See here for more details.

"UnboundLocalError: local variable referenced before assignment" after an if statement

To Solve this Error just initialize that variable above that loop or statement. For Example var a =""

How to embed YouTube videos in PHP?

This YouTube embed generator solve all my problems with video embedding.

Color different parts of a RichTextBox string

I have expanded the method with font as a parameter:

public static void AppendText(this RichTextBox box, string text, Color color, Font font)
{
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    box.SelectionColor = color;
    box.SelectionFont = font;
    box.AppendText(text);
    box.SelectionColor = box.ForeColor;
}

Copy map values to vector in STL

Here is what I would do.
Also I would use a template function to make the construction of select2nd easier.

#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>

/*
 * A class to extract the second part of a pair
 */   
template<typename T>
struct select2nd
{
    typename T::second_type operator()(T const& value) const
    {return value.second;}
};

/*
 * A utility template function to make the use of select2nd easy.
 * Pass a map and it automatically creates a select2nd that utilizes the
 * value type. This works nicely as the template functions can deduce the
 * template parameters based on the function parameters. 
 */
template<typename T>
select2nd<typename T::value_type> make_select2nd(T const& m)
{
    return select2nd<typename T::value_type>();
}

int main()
{
    std::map<int,std::string>   m;
    std::vector<std::string>    v;

    /*
     * Please note: You must use std::back_inserter()
     *              As transform assumes the second range is as large as the first.
     *              Alternatively you could pre-populate the vector.
     *
     * Use make_select2nd() to make the function look nice.
     * Alternatively you could use:
     *    select2nd<std::map<int,std::string>::value_type>()
     */   
    std::transform(m.begin(),m.end(),
                   std::back_inserter(v),
                   make_select2nd(m)
                  );
}

file path Windows format to java format

Just check

in MacOS

File directory = new File("/Users/sivo03/eclipse-workspace/For4DC/AutomationReportBackup/"+dir);
File directoryApache = new File("/Users/sivo03/Automation/apache-tomcat-9.0.22/webapps/AutomationReport/"+dir); 

and same we use in windows

File directory = new File("C:\\Program Files (x86)\\Jenkins\\workspace\\BrokenLinkCheckerALL\\AutomationReportBackup\\"+dir);
File directoryApache = new File("C:\\Users\\Admin\\Downloads\\Automation\\apache-tomcat-9.0.26\\webapps\\AutomationReports\\"+dir);

use double backslash instead of single frontslash

so no need any converter tool just use find and replace

"C:\Documents and Settings\Manoj\Desktop" to "C:\\Documents and Settings\\Manoj\\Desktop"

How return error message in spring mvc @Controller

Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
     *                method.
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then use an exception handler to retrieve the information and return it to the service caller.

@ControllerAdvice
public class ExceptionHandlerAdvice { 

    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        // log exception 
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }         
} 

Then create an exception when you need to.

throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");

How to make a floated div 100% height of its parent?

For #outer height to be based on its content, and have #inner base its height on that, make both elements absolutely positioned.

More details can be found in the spec for the css height property, but essentially, #inner must ignore #outer height if #outer's height is auto, unless #outer is positioned absolutely. Then #inner height will be 0, unless #inner itself is positioned absolutely.

<style>
    #outer {
        position:absolute; 
        height:auto; width:200px; 
        border: 1px solid red; 
    }
    #inner {
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
    }
</style>

<div id='outer'>
    <div id='inner'>
    </div>
    text
</div>

However... By positioning #inner absolutely, a float setting will be ignored, so you will need to choose a width for #inner explicitly, and add padding in #outer to fake the text wrapping I suspect you want. For example, below, the padding of #outer is the width of #inner +3. Conveniently (as the whole point was to get #inner height to 100%) there's no need to wrap text beneath #inner, so this will look just like #inner is floated.

<style>
    #outer2{
        padding-left: 23px;
        position:absolute; 
        height:auto; 
        width:200px; 
        border: 1px solid red; 
    }
    #inner2{
        left:0;
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
   }
</style>

<div id='outer2'>
    <div id='inner2'>
    </div>
    text
</div>

I deleted my previous answer, as it was based on too many wrong assumptions about your goal.

How to wait 5 seconds with jQuery?

Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.

button = $('.status-button a', whatever);
if(button.hasClass('close')) {
  button.delay(10000).queue(function() {
    $(this).click().dequeue();
  });
}

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

java build path problems

Here's a good discussion on this:

Basically you should

  1. Download and install the 1.5 JDK. (download link)
  2. In Eclipse, Go to Window ? Preferences ? Java ? Installed JREs.
  3. Add the 1.5 JDK to the list.
  4. Select 1.5 as Compiler Compliance Level.

What is the pythonic way to detect the last element in a 'for' loop?

There can be multiple ways. slicing will be fastest. Adding one more which uses .index() method:

>>> l1 = [1,5,2,3,5,1,7,43]                                                 
>>> [i for i in l1 if l1.index(i)+1==len(l1)]                               
[43]

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

How do I run a file on localhost?

Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system or exec for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.

Import Excel spreadsheet columns into SQL Server database

Microsoft suggest several methods:

  • SQL Server Data Transformation Services (DTS)
  • Microsoft SQL Server 2005 Integration Services (SSIS)
  • SQL Server linked servers
  • SQL Server distributed queries
  • ActiveX Data Objects (ADO) and the Microsoft OLE DB Provider for SQL Server
  • ADO and the Microsoft OLE DB Provider for Jet 4.0

If the wizard (DTS) isn't working (and I think it should) you could try something like this http://www.devasp.net/net/articles/display/771.html which basically suggests doing something like

INSERT INTO [tblTemp] ([Column1], [Column2], [Column3], [Column4])

SELECT A.[Column1], A.[Column2], A.[Column3], A.[Column4]
FROM OPENROWSET 
('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\Excel.xls;HDR=YES', 'select * from [Sheet1$]') AS A;

What is "String args[]"? parameter in main method Java

try this:

System.getProperties().getProperty("sun.java.command", 
    System.getProperties().getProperty("sun.rt.javaCommand"));

Interactive shell using Docker Compose

docker-compose run myapp sh should do the deal.

There is some confusion with up/run, but docker-compose run docs have great explanation: https://docs.docker.com/compose/reference/run

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Strings as Primary Keys in SQL Database

Inserts to a table having a clustered index where the insertion occurs in the middle of the sequence DOES NOT cause the index to be rewritten. It does not cause the pages comprising the data to be rewritten. If there is room on the page where the row will go, then it is placed in that page. The single page will be reformatted to place the row in the right place in the page. When the page is full, a page split will happen, with half of the rows on the page going to one page, and half going on the other. The pages are then relinked into the linked list of pages that comprise a tables data that has the clustered index. At most, you will end up writing 2 pages of database.

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

How to set a value of a variable inside a template code?

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

from django import template
register = template.Library()

@register.simple_tag
def define(val=None):
  return val

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


Then in your template you can assign values to the context like this:

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}


Would you like to {{action}} this item?

How to capitalize first letter of each word, like a 2-word city?

There's a good answer here:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

or in ES6:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

how to pass command line arguments to main method dynamically

We can pass string value to main method as argument without using commandline argument concept in java through Netbean

 package MainClass;
 import java.util.Scanner;
 public class CmdLineArgDemo {

static{
 Scanner readData = new Scanner(System.in);   
 System.out.println("Enter any string :");
 String str = readData.nextLine();
 String [] str1 = str.split(" ");
 // System.out.println(str1.length);
 CmdLineArgDemo.main(str1);
}  

   public static void main(String [] args){
      for(int i = 0 ; i<args.length;i++) {
        System.out.print(args[i]+" ");
      }
    }
  }

Output

Enter any string : 
Coders invent Digital World 
Coders invent Digital World

Can I use conditional statements with EJS templates (in JMVC)?

You can also use else if syntax:

<% if (x === 1) { %>
    <p>Hello world!</p>
<% } else if (x === 2) { %>
    <p>Hi earth!</p>
<% } else { %>
    <p>Hey terra!</p>
<% } %>

How do I determine the dependencies of a .NET application?

Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.

To see which things your .NET app actually relies on, you can use the tremendously excellent .NET reflector from Red Gate. (EDIT: Note that .NET Reflector is now a paid product. ILSpy is free and open source and very similar.)

Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.

It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.

To troubleshoot those kinds of issues, Microsoft have an Assembly Binding Log Viewer which can show you what's going on at runtime

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

how to get the value of a textarea in jquery?

$('textarea#message') cannot be undefined (if by $ you mean jQuery of course).

$('textarea#message') may be of length 0 and then $('textarea#message').val() would be empty that's all

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I solved this problem by ORDERING my source data (xls, csv, whatever) such that the longest text values on at the top of the file. Excel is great. use the LEN() function on your challenging column. Order by that length value with the longest value on top of your dataset. Save. Try the import again.

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

To open hyperlink in the same tab, use:

$(document).on('click', "a.classname", function() {
    var form = $("<form></form>");
    form.attr(
    {
        id     : "formid",
        action : $(this).attr("href"),
        method : "GET",
    });

    $("body").append(form);
    $("#formid").submit();
    $("#formid").remove();
    return false;
});

Python Socket Multiple Clients

accept can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:

  • Open new threads to handle clients, while the main thread goes back to accepting new clients
  • As above but with processes, instead of threads
  • Use asynchronous socket frameworks like Twisted, or a plethora of others

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

jQuery: enabling/disabling datepicker

Well You can remove datepicker by simply remove hasDatepicker class from input.

Code

$( "#from" ).removeClass('hasDatepicker')

Map HTML to JSON

I got few links sometime back while reading on ExtJS full framework in itself is JSON.

http://www.thomasfrank.se/xml_to_json.html

http://camel.apache.org/xmljson.html

online XML to JSON converter : http://jsontoxml.utilities-online.info/

UPDATE BTW, To get JSON as added in question, HTML need to have type & content tags in it too like this or you need to use some xslt transformation to add these elements while doing JSON conversion

<?xml version="1.0" encoding="UTF-8" ?>
<type>div</type>
<content>
    <type>span</type>
    <content>Text2</content>
</content>
<content>Text2</content>

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

If you want to change the permissions of an existing file, use chmod (change mode):

$itWorked = chmod ("/yourdir/yourfile", 0777);

If you want all new files to have certain permissions, you need to look into setting your umode. This is a process setting that applies a default modification to standard modes.

It is a subtractive one. By that, I mean a umode of 022 will give you a default permission of 755 (777 - 022 = 755).

But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

Best way to specify whitespace in a String.Split operation

Note that adjacent whitespace will NOT be treated as a single delimiter, even when using String.Split(null). If any of your tokens are separated with multiple spaces or tabs, you'll get empty strings returned in your array.

From the documentation:

Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

Export javascript data to CSV file without server interaction

See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

Java Refuses to Start - Could not reserve enough space for object heap

You need to look at upgrading your OS and Java. Java 5.0 is EOL but if you cannot update to Java 6, you could use the latest patch level 22!

32-bit Windows is limited to ~ 1.3 GB so you are doing well to se the maximum to 1.8. Note: this is a problem with continous memory, and as your system runs its memory space can get fragmented so it does not suprise me you have this problem.

A 64-bit OS, doesn't have this problem as it has much more virtual space, you don't even have to upgrade to a 64-bit version of java to take advantage of this.

BTW, in my experience, 32-bit Java 5.0 can be faster than 64-bit Java 5.0. It wasn't until many years later that Java 6 update 10 was faster for 64-bit.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Here is a sample for ISO-8859-9;

protected void btnKaydet_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet";
    Response.AddHeader("Content-Disposition", "attachment; filename=XXXX.doc");
    Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-9");
    Response.Charset = "ISO-8859-9";
    EnableViewState = false;


    StringWriter writer = new StringWriter();
    HtmlTextWriter html = new HtmlTextWriter(writer);
    form1.RenderControl(html);


    byte[] bytesInStream = Encoding.GetEncoding("iso-8859-9").GetBytes(writer.ToString());
    MemoryStream memoryStream = new MemoryStream(bytesInStream);


    string msgBody = "";
    string Email = "[email protected]";
    SmtpClient client = new SmtpClient("mail.xxxxx.org");
    MailMessage message = new MailMessage(Email, "[email protected]", "ONLINE APP FORM WITH WORD DOC", msgBody);
    Attachment att = new Attachment(memoryStream, "XXXX.doc", "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet");
    message.Attachments.Add(att);
    message.BodyEncoding = System.Text.Encoding.UTF8;
    message.IsBodyHtml = true;
    client.Send(message);}

Nginx no-www to www and www to no-www

not sure if anyone notice it may be correct to return a 301 but browsers choke on it to doing

rewrite ^(.*)$ https://yoursite.com$1; 

is faster than:

return 301 $scheme://yoursite.com$request_uri;

powershell mouse move does not prevent idle mode

Try this: (source: http://just-another-blog.net/programming/powershell-and-the-net-framework/)

Add-Type -AssemblyName System.Windows.Forms 

$position = [System.Windows.Forms.Cursor]::Position  
$position.X++  
[System.Windows.Forms.Cursor]::Position = $position 

    while(1) {  
    $position = [System.Windows.Forms.Cursor]::Position  
    $position.X++  
    [System.Windows.Forms.Cursor]::Position = $position  

    $time = Get-Date;  
    $shorterTimeString = $time.ToString("HH:mm:ss");  

    Write-Host $shorterTimeString "Mouse pointer has been moved 1 pixel to the right"  
    #Set your duration between each mouse move
    Start-Sleep -Seconds 150  
    }  

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

You just need to perform a selector with a delay - (0 seconds works).

override func viewDidLoad() {
    super.viewDidLoad()
    perform(#selector(presentExampleController), with: nil, afterDelay: 0)
}

@objc private func presentExampleController() {
    let exampleStoryboard = UIStoryboard(named: "example", bundle: nil)
    let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleVC") as! ExampleVC
    present(exampleVC, animated: true) 
}

How does Python's super() work with multiple inheritance?

Overall

Assuming everything descends from object (you are on your own if it doesn't), Python computes a method resolution order (MRO) based on your class inheritance tree. The MRO satisfies 3 properties:

  • Children of a class come before their parents
  • Left parents come before right parents
  • A class only appears once in the MRO

If no such ordering exists, Python errors. The inner workings of this is a C3 Linerization of the classes ancestry. Read all about it here: https://www.python.org/download/releases/2.3/mro/

Thus, in both of the examples below, it is:

  1. Child
  2. Left
  3. Right
  4. Parent

When a method is called, the first occurrence of that method in the MRO is the one that is called. Any class that doesn't implement that method is skipped. Any call to super within that method will call the next occurrence of that method in the MRO. Consequently, it matters both what order you place classes in inheritance, and where you put the calls to super in the methods.

With super first in each method

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        print "parent"

class Left(Parent):
    def __init__(self):
        super(Left, self).__init__()
        print "left"

class Right(Parent):
    def __init__(self):
        super(Right, self).__init__()
        print "right"

class Child(Left, Right):
    def __init__(self):
        super(Child, self).__init__()
        print "child"

Child() Outputs:

parent
right
left
child

With super last in each method

class Parent(object):
    def __init__(self):
        print "parent"
        super(Parent, self).__init__()

class Left(Parent):
    def __init__(self):
        print "left"
        super(Left, self).__init__()

class Right(Parent):
    def __init__(self):
        print "right"
        super(Right, self).__init__()

class Child(Left, Right):
    def __init__(self):
        print "child"
        super(Child, self).__init__()

Child() Outputs:

child
left
right
parent

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

How to disable back swipe gesture in UINavigationController on iOS 7

All of these solutions manipulate Apple's gesture recognizer in a way they do not recommend. I've just been told by a friend that there's a better solution:

[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];

where myPanGestureRecognizer is the gesture recognizer you are using to e.g. show your menu. That way, Apple's gesture recognizer doesn't get turned back on by them when you push a new navigation controller and you don't need to rely on hacky delays that may fire too early if your phone is put to sleep or under heavy load.

Leaving this here because I know I'll not remember this the next time I need it, and then I'll have the solution to the issue here.

Getting the application's directory from a WPF application

One method:

System.AppDomain.CurrentDomain.BaseDirectory

Another way to do it would be:

System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)

How can I print literal curly-brace characters in a string and also use .format on it?

Reason is , {} is the syntax of .format() so in your case .format() doesn't recognize {Hello} so it threw an error.

you can override it by using double curly braces {{}},

x = " {{ Hello }} {0} "

or

try %s for text formatting,

x = " { Hello } %s"
print x%(42)  

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

How to use readline() method in Java?

This will explain it, I think...

import java.io.*;

class reading
{
    public static void  main(String args[]) throws IOException
    {
        float number;
        System.out.println("Enter a number");
        try
        {
            InputStreamReader in = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(in);
            String a = br.readLine();
            number = Float.valueOf(a);
            int x = (int)number;

            System.out.println("Your input=" + number);
            System.out.println("Your input in integer terms is = " + x);
        }
        catch(Exception e){
        }
    }
}

Can I access a form in the controller?

Bit late for an answer but came with following option. It is working for me but not sure if it is the correct way or not.

In my view I'm doing this:

<form name="formName">
    <div ng-init="setForm(formName);"></div>
</form>

And in the controller:

$scope.setForm = function (form) {
    $scope.myForm = form;
}

Now after doing this I have got my form in my controller variable which is $scope.myForm

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

How to round double to nearest whole number and then convert to a float?

Here is a quick example:

public class One {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double a = 4.56777;
        System.out.println( new Float( Math.round(a)) );

    }

}

the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double values and provides whole long values

Regards

How to write a switch statement in Ruby

It is done using case in Ruby. Also see "Switch statement" on Wikipedia.

Quoted:

case n
when 0
  puts 'You typed zero'
when 1, 9
  puts 'n is a perfect square'
when 2
  puts 'n is a prime number'
  puts 'n is an even number'
when 3, 5, 7
  puts 'n is a prime number'
when 4, 6, 8
  puts 'n is an even number'
else
  puts 'Only single-digit numbers are allowed'
end

Another example:

score = 70

result = case score
   when 0..40 then "Fail"
   when 41..60 then "Pass"
   when 61..70 then "Pass with Merit"
   when 71..100 then "Pass with Distinction"
   else "Invalid Score"
end

puts result

On around page 123 of The Ruby Programming Language (1st Edition, O'Reilly) on my Kindle, it says the then keyword following the when clauses can be replaced with a newline or semicolon (just like in the if then else syntax). (Ruby 1.8 also allows a colon in place of then, but this syntax is no longer allowed in Ruby 1.9.)

Turning off eslint rule for a specific line

Or for multiple ignores on the next line, string the rules using commas

// eslint-disable-next-line class-methods-use-this, no-unused-vars

Convert decimal to hexadecimal in UNIX shell script

xd() {
    printf "hex> "
    while read i
    do
        printf "dec  $(( 0x${i} ))\n\nhex> "
    done
}
dx() {
    printf "dec> "
    while read i
    do
        printf 'hex  %x\n\ndec> ' $i
    done
}

Access to the path is denied

please add IIS_IUSERS full control permission to your folder. you find this option from security tab in folder properties. find this option and user in this image

Why won't bundler install JSON gem?

This appears to be a bug in Bundler not recognizing the default gems installed along with ruby 2.x. I still experienced the problem even with the latest version of bundler (1.5.3).

One solution is to simply delete json-1.8.1.gemspec from the default gemspec directory.

rm ~/.rubies/ruby-2.1.0/lib/ruby/gems/2.1.0/specifications/default/json-1.8.1.gemspec

After doing this, bundler should have no problem locating the gem. Note that I am using chruby. If you're using some other ruby manager, you'll have to update your path accordingly.

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

Black transparent overlay on image hover with only CSS?

See what I've done here: http://jsfiddle.net/dyarbrough93/c8wEC/

First off, you never set the dimensions of the overlay, meaning it wasn't showing up in the first place. Secondly, I recommend just changing the z-index of the overlay when you hover over the image. Change the opacity / color of the overlay to suit your needs.

.image { position: relative; width: 200px; height: 200px;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background-color: gray; z-index: -10; width: 200px; height: 200px; opacity: 0.5}
.image:hover .overlay { z-index: 10}

Check if a given time lies between two times regardless of date

This worked for me:

fun timeBetweenInterval(
    openTime: String,
    closeTime: String
): Boolean {
    try {
        val dateFormat = SimpleDateFormat(TIME_FORMAT)
        val afterCalendar = Calendar.getInstance().apply {
            time = dateFormat.parse(openTime)
            add(Calendar.DATE, 1)
        }
        val beforeCalendar = Calendar.getInstance().apply {
            time = dateFormat.parse(closeTime)
            add(Calendar.DATE, 1)
        }

        val current = Calendar.getInstance().apply {
            val localTime = dateFormat.format(timeInMillis)
            time = dateFormat.parse(localTime)
            add(Calendar.DATE, 1)
        }
        return current.time.after(afterCalendar.time) && current.time.before(beforeCalendar.time)
    } catch (e: ParseException) {
        e.printStackTrace()
        return false
    }
}

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

BeanFactory vs ApplicationContext

ApplicationContext: It loads spring beans configured in spring configuration file,and manages the life cycle of the spring bean as and WHEN CONTAINER STARTS.It won't wait until getBean("springbeanref") is called.

BeanFactory It loads spring beans configured in spring configuration file,manages the life cycle of the spring bean when we call the getBean("springbeanref").So when we call the getBean("springbeanref") at the time of spring bean life cycle starts.

How to "grep" out specific line ranges of a file

The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.

sed -n '1234,5555p' someFile

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

What is InputStream & Output Stream? Why and when do we use them?

OutputStream is an abstract class that represents writing output. There are many different OutputStream classes, and they write out to certain things (like the screen, or Files, or byte arrays, or network connections, or etc). InputStream classes access the same things, but they read data in from them.

Here is a good basic example of using FileOutputStream and FileInputStream to write data to a file, then read it back in.

Django template how to look up a dictionary value with a variable

Environment: Django 2.2

  1. Example code:


    from django.template.defaulttags import register

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value.get(arg)

I put this code in a file named template_filters.py in my project folder named portfoliomgr

  1. No matter where you put your filter code, make sure you have __init__.py in that folder

  2. Add that file to libraries section in templates section in your projectfolder/settings.py file. For me, it is portfoliomgr/settings.py



    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'template_filters': 'portfoliomgr.template_filters',
                }
            },
        },
    ]

  1. In your html code load the library

    
    {% load template_filters %}
    

How can I repeat a character in Bash?

My proposal (accepting variable values for n):

n=100
seq 1 $n | xargs -I {} printf =

How can I export tables to Excel from a webpage

There are practical two ways to do this automaticly while only one solution can be used in all browsers. First of all you should use the open xml specification to build the excel sheet. There are free plugins from Microsoft available that make this format also available for older office versions. The open xml is standard since office 2007. The the two ways are obvious the serverside or the clientside.

The clientside implementation use a new standard of CSS that allow you to store data instead of just the URL to the data. This is a great approach coz you dont need any servercall, just the data and some javascript. The killing downside is that microsoft don't support all parts of it in the current IE (I don't know about IE9) releases. Microsoft restrict the data to be a image but we will need a document. In firefox it works quite fine. For me the IE was the killing point.

The other way is to user a serverside implementation. There should be a lot implementations of open XML for all languages. You just need to grap one. In most cases it will be the simplest way to modify a Viewmodel to result in a Document but for sure you can send all data from Clientside back to server and do the same.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

As "M.A. Hanin" said above, it can caused by an InnerException like this:

"Unrecognized configuration section userSettings. (C:\Users\Pourakbar.h\AppData\Local\Accounting\Accounting.vshost.exe_Url_a4h1gnabohiu4wgiejk0d21rc2kbwr4g\1.0.0.0\user.config line 3)"

and I deleted the folder: C:\Users\Pourakbar.h\AppData\Local\Accounting\Accounting.vshost.exe_Url_a4h1gnabohiu4wgiejk0d21rc2kbwr4g from my computer and that worked for me!

nginx- duplicate default server error

If you're on Digital Ocean this means you need to go to /etc/nginx/sites-enabled/ and then REMOVE using rm -R digitalocean and default

It fixed it for me!

Pic of Console on Windows 10 using Bitvise

How do you get the length of a list in the JSF expression language?

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

In class MyBean:
public int getSomelistLength() { return this.somelist.length; }

In your JSF page:
#{MyBean.somelistLength}

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

In JSF page:
#{ fn:length(MyBean.somelist) }

MySQL DELETE FROM with subquery as condition

you can use the alias in this way on the delete statement

DELETE  th.*
FROM term_hierarchy th
INNER JOIN term_hierarchy th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th.parent = 1015;

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Check if date is in the past Javascript

function isPrevDate() {
    alert("startDate is " + Startdate);
    if(Startdate.length != 0 && Startdate !='') {
        var start_date = Startdate.split('-');
        alert("Input date: "+ start_date);
        start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
        alert("start date arrray format " + start_date);
        var a = new Date(start_date);
        //alert("The date is a" +a);
        var today = new Date();
        var day = today.getDate();
        var mon = today.getMonth()+1;
        var year = today.getFullYear();
        today = (mon+"/"+day+"/"+year);
        //alert(today);
        var today = new Date(today);
        alert("Today: "+today.getTime());
        alert("a : "+a.getTime());
        if(today.getTime() > a.getTime() )
        {
            alert("Please select Start date in range");
            return false;
        } else {
            return true;
        }
    }
}

Adding gif image in an ImageView in android

We can easily add animated gif image on imageview using Ion library.

Tutorial video :: https://www.youtube.com/watch?v=IqKtpdeIpjA

ImageView image = (ImageView)findViewById(R.id.image_gif);
Ion.with(image).load("http://mygifimage.gif");

Pandas Merge - How to avoid duplicating columns

Building on @rprog's answer, you can combine the various pieces of the suffix & filter step into one line using a negative regex:

dfNew = df.merge(df2, left_index=True, right_index=True,
             how='outer', suffixes=('', '_DROP')).filter(regex='^(?!.*_DROP)')

Or using df.join:

dfNew = df.join(df2, lsuffix="DROP").filter(regex="^(?!.*DROP)")

The regex here is keeping anything that does not end with the word "DROP", so just make sure to use a suffix that doesn't appear among the columns already.

if else in a list comprehension

Make a list from items in an iterable

It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.

[expression1(item)                                        for item in iterable]

[expression1(item) if conditional1                        for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]

The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.

For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:

newlist = [s for s in firstlist if s.strip()]

Changing an AIX password via script?

Use GNU passwd stdin flag.

From the man page:

   --stdin
          This option is used to indicate that passwd should read the new password from standard input, which can be a pipe.

NOTE: Only for root user.

Example

$ adduser foo 
$ echo "NewPass" |passwd foo --stdin
Changing password for user foo.
passwd: all authentication tokens updated successfully.

Alternatively you can use expect, this simple code will do the trick:

#!/usr/bin/expect
spawn passwd foo
expect "password:"
send "Xcv15kl\r"
expect "Retype new password:"
send "Xcv15kl\r"
interact

Results

$ ./passwd.xp 
spawn passwd foo
Changing password for user foo.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.

What is an MvcHtmlString and when should I use it?

A nice practical use of this is if you want to make your own HtmlHelper extensions. For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

Creating Roles in Asp.net Identity MVC 5

Verify you have following signature of your MyContext class

public class MyContext : IdentityDbContext<MyUser>

Or

public class MyContext : IdentityDbContext

The code is working for me, without any modification!!!

ASP.Net 2012 Unobtrusive Validation with jQuery

This is the official Microsoft answer from the MS Connect forums. I am copying the relevant text below :-

When targeting .NET 4.5 Unobtrusive Validation is enabled by default. You need to have jQuery in your project and have something like this in Global.asax to register jQuery properly:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition {
        Path = "~/scripts/jquery-1.4.1.min.js",
        DebugPath = "~/scripts/jquery-1.4.1.js",
        CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js"
    });

Replacing the version of jQuery with the version you are using.

You can also disable this new feature in web.config by removing the following line:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

I came researching the options that I would have to do this, however, I believe the method I use is the simplest:

SELECT COUNT(*), 
       DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup 
FROM TABLE 
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0) 
ORDER BY dtgroup ASC;

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I had the same problem and couldn't figure it out for almost a day. I added IUSR and NetworkService to the folder permissions, I made sure it was running as NetworkService. I tried impersonation and even running as administrator (DO NOT DO THIS). Then someone recommended that I try running the page from inside the Windows 2008 R2 server and it pointed me to the Handler Mappings, which were all disabled.

I got it to work with this:

  • Open the Feature View of your website.
  • Go to Handler Mappings.
  • Find the path for .cshtml
  • Right Click and Click Edit Feature Permissions
  • Select Execute
  • Hit OK.

Now try refreshing your website.

Algorithm to return all combinations of k elements from n

Simple recursive algorithm in Haskell

import Data.List

combinations 0 lst = [[]]
combinations n lst = do
    (x:xs) <- tails lst
    rest   <- combinations (n-1) xs
    return $ x : rest

We first define the special case, i.e. selecting zero elements. It produces a single result, which is an empty list (i.e. a list that contains an empty list).

For n > 0, x goes through every element of the list and xs is every element after x.

rest picks n - 1 elements from xs using a recursive call to combinations. The final result of the function is a list where each element is x : rest (i.e. a list which has x as head and rest as tail) for every different value of x and rest.

> combinations 3 "abcde"
["abc","abd","abe","acd","ace","ade","bcd","bce","bde","cde"]

And of course, since Haskell is lazy, the list is gradually generated as needed, so you can partially evaluate exponentially large combinations.

> let c = combinations 8 "abcdefghijklmnopqrstuvwxyz"
> take 10 c
["abcdefgh","abcdefgi","abcdefgj","abcdefgk","abcdefgl","abcdefgm","abcdefgn",
 "abcdefgo","abcdefgp","abcdefgq"]

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

DateTime fields from SQL Server display incorrectly in Excel

i've faced the same problem when copying data from ssms to excel. the date format got messed up. at last i changed my laptop's system date format to yyyy-mm-dd from yyyy/mm/dd. everything works just fine.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

delete a column with awk or sed

Try using cut... its fast and easy

First you have repeated spaces, you can squeeze those down to a single space between columns if thats what you want with tr -s ' '

If each column already has just one delimiter between it, you can use cut -d ' ' -f-2 to print fields (columns) <= 2.

for example if your data is in a file input.txt you can do one of the following:

cat input.txt | tr -s ' ' | cut -d ' ' -f-2

Or if you better reason about this problem by removing the 3rd column you can write the following

cat input.txt | tr -s ' ' | cut -d ' ' --complement -f3

cut is pretty powerful, you can also extract ranges of bytes, or characters, in addition to columns

excerpt from the man page on the syntax of how to specify the list range

Each LIST is made up of one range, or many ranges separated by commas.
Selected input is written in the same order that it is read, and is
written exactly once. Each range is one of:

  N     N'th byte, character or field, counted from 1
  N-    from N'th byte, character or field, to end of line
  N-M   from N'th to M'th (included) byte, character or field
  -M    from first to M'th (included) byte, character or field

so you also could have said you want specific columns 1 and 2 with...

cat input.txt | tr -s ' ' | cut -d ' ' -f1,2

"No such file or directory" but it exists

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected. I hope it would be useful.

Change IPython/Jupyter notebook working directory

import sys
sys.path.append('C:/')

Casting objects in Java

Have a look at this sample:

public class A {
  //statements
}

public class B extends A {
  public void foo() { }
}

A a=new B();

//To execute **foo()** method.

((B)a).foo();

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

How do I see if Wi-Fi is connected on Android?

This is an easier solution. See Stack Overflow question Checking Wi-Fi enabled or not on Android.

P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>

SQL SELECT from multiple tables

SELECT pid, cid, pname, name1, name2 
FROM customer1 c1, product p 
WHERE p.cid=c1.cid 
UNION SELECT pid, cid, pname, name1, name2 
FROM customer2 c2, product p 
WHERE p.cid=c2.cid;

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

Open a webpage in the default browser

This worked perfectly for me. Since this is for personal use, I used Firefox as my browser.

 Dim url As String
    url = "http://www.google.com"
    Process.Start("Firefox", url)

What is the difference between Release and Debug modes in Visual Studio?

The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.

How can I format a decimal to always show 2 decimal places?

You should use the new format specifications to define how your value should be represented:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:

Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:

>>> f'{pi:.2f}'
'3.14'

ASP.NET Web Application Message Box

'ASP.net MessageBox

'Add a scriptmanager to the ASP.Net Page

<asp:scriptmanager id="ScriptManager1" runat="server" />

try:

{

  string sMsg = "My Message";

  ScriptManager.RegisterStartupScript(Page, Page.GetType, Guid.NewGuid().ToString(), "alert('" + sMsg + "')", true);

}

Comparing two .jar files

use java decompiler and decompile all the .class files and save all files as project structure .

then use meld diff viewer and compare as folders ..

json_encode/json_decode - returns stdClass instead of Array in PHP

tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.

After all, it's JSON, not JSAAN. :)

So PHP has to convert your array into an object in order to encode into JSON.

IntelliJ: Never use wildcard imports

If you don't want to change preferences, you can optimize imports by pressing Ctrl+Option+o on Mac or Ctrl+Alt+o on Windows/Linux and this will replace all imports with single imports in current file.

What is the difference between HTML tags and elements?

http://html.net/tutorials/html/lesson3.php

Tags are labels you use to mark up the begining and end of an element.

All tags have the same format: they begin with a less-than sign "<" and end with a greater-than sign ">".

Generally speaking, there are two kinds of tags - opening tags: <html> and closing tags: </html>. The only difference between an opening tag and a closing tag is the forward slash "/". You label content by putting it between an opening tag and a closing tag.

HTML is all about elements. To learn HTML is to learn and use different tags.

For example:

<h1></h1>

Where as elements are something that consists of start tag and end tag as shown:

<h1>Heading</h1>

Simple and clean way to convert JSON string to Object in Swift

let jsonString = "{\"id\":123,\"Name\":\"Munish\"}"

Convert String to NSData

 var data: NSData =jsonString.dataUsingEncoding(NSUTF8StringEncoding)!

 var error: NSError?

Convert NSData to AnyObject

var jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,     options: NSJSONReadingOptions.allZeros, error: &error)

println("Error: \\(error)")

let id = (jsonObject as! NSDictionary)["id"] as! Int

let name = (jsonObject as! NSDictionary)["name"] as! String

println("Id: \\(id)")

println("Name: \\(name)")

Currency format for display

public static string ToFormattedCurrencyString(
    this decimal currencyAmount,
    string isoCurrencyCode,
    CultureInfo userCulture)
{
    var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;

if (userCurrencyCode == isoCurrencyCode)
{
    return currencyAmount.ToString("C", userCulture);
}

return string.Format(
    "{0} {1}", 
    isoCurrencyCode, 
    currencyAmount.ToString("N2", userCulture));

}

Copying data from one SQLite database to another

Easiest and correct way on a single line:

sqlite3 old.db ".dump mytable" | sqlite3 new.db

The primary key and the columns types will be kept.