Programs & Examples On #Tigase

Tigase is an open source (GPL3) collection of XMPP/Jabber software (server, web client, test-suite) implemented in Java.

How can I properly use a PDO object for a parameterized SELECT query

I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.

$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();

ios Upload Image and Text using HTTP POST

Use AFNetworking; Put other parameters in the parameter dictionary and append the image data in form data.

//Upload Image Using AFNetworking

-(BOOL)uploadImageAFNetworkingWithURL:(NSString *)path andImage:(UIImage *)image andImageNameWithExtension:(NSString *)strImageName andParamDict:(NSDictionary *)dictParam andKeyForUploadingImage:(NSString *)keyUplaodImg{

    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *strError = EMPTY_STRING;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:path parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:imageData name:keyUplaodImg fileName:strImageName mimeType:@"image/jpeg"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"success = %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@", error);
        NSLog(@"Response = %@", operation);
        [strError stringByAppendingString:STR_ERR_MESSAGE];
    }];
    if(strError.length>0){
        return NO;
    }else{
        return YES;
    }
}

Show popup after page load

Use this below code to display pop-up box on page load:

$(document).ready(function() { 
  var id = '#dialog';
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();
  $('#mask').css({'width':maskWidth,'height':maskHeight}); 
  $('#mask').fadeIn(500); 
  $('#mask').fadeTo("slow",0.9); 
        var winH = $(window).height();
  var winW = $(window).width();
        $(id).css('top',  winH/2-$(id).height()/2);
  $(id).css('left', winW/2-$(id).width()/2);
     $(id).fadeIn(2000);  
     $('.window .close').click(function (e) {
  e.preventDefault();
  $('#mask').hide();
  $('.window').hide();
     });  
     $('#mask').click(function () {
  $(this).hide();
  $('.window').hide();
 });  

});

<div class="maintext">
<h2> Main text goes here...</h2>
</div>
<div id="boxes">
<div style="top: 50%; left: 50%; display: none;" id="dialog" class="window"> 
<div id="san">
<a href="#" class="close agree"><img src="close-icon.png" width="25" style="float:right; margin-right: -25px; margin-top: -20px;"></a>
<img src="san-web-corner.png" width="450">
</div>
</div>
<div style="width: 2478px; font-size: 32pt; color:white; height: 1202px; display: none; opacity: 0.4;" id="mask"></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script> 

I refereed this code from here Demo

How to split a string into an array in Bash?

Use this:

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe

Foreign Key naming scheme

How about FK_TABLENAME_COLUMNNAME?

Keep It Simple Stupid whenever possible.

Can't resolve module (not found) in React.js

Adding NODE_PATH as environment variable in .env is deprecated and is replaced by adding "baseUrl": "./src", to compilerOptions in jsconfig.json or tsconfig.json.

Reference

Opposite of %in%: exclude rows with values specified in a vector

If you look at the code of %in%

 function (x, table) match(x, table, nomatch = 0L) > 0L

then you should be able to write your version of opposite. I use

`%not in%` <- function (x, table) is.na(match(x, table, nomatch=NA_integer_))

Another way is:

function (x, table) match(x, table, nomatch = 0L) == 0L

New features in java 7

I think ForkJoinPool and related enhancement to Executor Framework is an important addition in Java 7.

Using if elif fi in shell scripts

Change [ to [[, and ] to ]].

How do I work with a git repository within another repository?

The key is git submodules.

Start reading the Submodules chapter of the Git Community Book or of the Users Manual

Say you have repository PROJECT1, PROJECT2, and MEDIA...

cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"

Repeat on the other repo...

Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:

cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"

This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.

It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.

With great power comes the great chance to get bitten in the rump.

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Add an element to an array in Swift

You can also pass in a variable and/or object if you wanted to.

var str1:String = "John"
var str2:String = "Bob"

var myArray = ["Steve", "Bill", "Linus", "Bret"]

//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)

To add them to the front:

//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)

//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)

As others have already stated, you can no longer use '+=' as of xCode 6.1

Git diff against a stash

Depending on what you want to compare the stash with (local working tree / parent commit / head commit), there are actually several commands available, amongst which the good old git diff, and the more specific git stash show:

+--------------------------------------------------------------------------+
¦ Compare stash with ? ¦ git diff                      ¦ git stash show    ¦
¦----------------------+-------------------------------+-------------------¦
¦ Local working tree   ¦ git diff stash@{0}            ¦ git stash show -l ¦
¦----------------------¦-------------------------------¦-------------------¦
¦ Parent commit        ¦ git diff stash@{0}^ stash@{0} ¦ git stash show -p ¦
¦----------------------¦-------------------------------¦-------------------¦
¦ HEAD commit          ¦ git diff stash@{0} HEAD       ¦   /               ¦
+--------------------------------------------------------------------------+

While git stash show looks more user friendly on first sight, git diff is actually more powerful in that it allows specifying filenames for a more focused diff. I've personally set up aliases for all of these commands in my zsh git plugin.

How can I set the value of a DropDownList using jQuery?

Try this very simple approach:

/*make sure that value is included in the options value of the dropdownlist 
e.g. 
(<select><option value='CA'>California</option><option value='AK'>Alaska</option>      </select>)
*/

$('#mycontrolId').val(myvalue).attr("selected", "selected");

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

select a value where it doesn't exist in another table

SELECT ID
  FROM A
 WHERE ID NOT IN (
      SELECT ID
        FROM B);

SELECT ID    
  FROM A a
 WHERE NOT EXISTS (
      SELECT 1 
        FROM B b
       WHERE b.ID = a.ID)

         SELECT a.ID 
           FROM A a    
LEFT OUTER JOIN B b 
             ON a.ID = b.ID    
          WHERE b.ID IS NULL

DELETE 
  FROM A 
 WHERE ID NOT IN (
      SELECT ID 
        FROM B) 

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

JSON.NET Error Self referencing loop detected for type

I was facing the same problem and I tried using JsonSetting to ignore the self-referencing error its kinda work until I got a class which self-referencing very deeply and my dot-net process hangs on Json writing value.

My Problem

    public partial class Company : BaseModel
{
    public Company()
    {
        CompanyUsers = new HashSet<CompanyUser>();
    }

    public string Name { get; set; }

    public virtual ICollection<CompanyUser> CompanyUsers { get; set; }
}

public partial class CompanyUser
{
    public int Id { get; set; }
    public int CompanyId { get; set; }
    public int UserId { get; set; }

    public virtual Company Company { get; set; }

    public virtual User User { get; set; }
}

public partial class User : BaseModel
{
    public User()
    {
        CompanyUsers = new HashSet<CompanyUser>();
    }

    public string DisplayName { get; set; }
    public virtual ICollection<CompanyUser> CompanyUsers { get; set; }

}

You can see the problem in User class it's referencing to CompanyUser class which is a self-referencing.

Now, I'm calling the GetAll Method which includes all the relational properties.

cs.GetAll("CompanyUsers", "CompanyUsers.User");

On this stage my DotNetCore process hangs on Executing JsonResult, writing value ... and never come. In my Startup.cs, I've already set the JsonOption. For some reason EFCore is including nested property which I'm not asking Ef to give.

    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

expected behavior should be this

Hey EfCore can you please include "CompanyUsers" data as well in my Company class so that i can easily access the data.

then

Hey EfCore can you also please include the "CompanyUsers.User" data as well so that i can easily access the data like this Company.CompanyUsers.First().User.DisplayName

at this stage i should only get this "Company.CompanyUsers.First().User.DisplayName" and it should not give me Company.CompanyUsers.First().User.CompanyUsers which causing the self-referencing issue; Technically it shouldn't give me User.CompanyUsers as CompanyUsers is a navigational property. But, EfCore get very excited and giving me User.CompanyUsers.

So, I decided to write an extension method for property to be excluded from the object (it's actually not excluding it's just setting the property to null). Not only that it will also work on array properties as well. below is the code I'm also going to export the nuget package for other users (not sure if this even helps someone). Reason is simple because I'm too lazy to write .Select(n => new { n.p1, n.p2}); I just don't want to write select statement to exclude only 1 property!

This is not the best code (I'll update at some stage) as I have written in a hurry and though this might help someone who wants to exclude (set null) in the object with arrays also.

    public static class PropertyExtensions
{
    public static void Exclude<T>(this T obj, Expression<Func<T, object>> expression)
    {
        var visitor = new PropertyVisitor<T>();
        visitor.Visit(expression.Body);
        visitor.Path.Reverse();
        List<MemberInfo> paths = visitor.Path;
        Action<List<MemberInfo>, object> act = null;

        int recursiveLevel = 0;
        act = (List<MemberInfo> vPath, object vObj) =>
        {

            // set last propert to null thats what we want to avoid the self-referencing error.
            if (recursiveLevel == vPath.Count - 1)
            {
                if (vObj == null) throw new ArgumentNullException("Object cannot be null");

                vObj.GetType().GetMethod($"set_{vPath.ElementAt(recursiveLevel).Name}").Invoke(vObj, new object[] { null });
                return;
            }

            var pi = vObj.GetType().GetProperty(vPath.ElementAt(recursiveLevel).Name);
            if (pi == null) return;
            var pv = pi.GetValue(vObj, null);
            if (pi.PropertyType.IsArray || pi.PropertyType.Name.Contains("HashSet`1") || pi.PropertyType.Name.Contains("ICollection`1"))
            {
                var ele = (IEnumerator)pv.GetType().GetMethod("GetEnumerator").Invoke(pv, null);

                while (ele.MoveNext())
                {
                    recursiveLevel++;
                    var arrItem = ele.Current;

                    act(vPath, arrItem);

                    recursiveLevel--;
                }

                if (recursiveLevel != 0) recursiveLevel--;
                return;
            }
            else
            {
                recursiveLevel++;
                act(vPath, pv);
            }

            if (recursiveLevel != 0) recursiveLevel--;

        };

        // check if the root level propert is array
        if (obj.GetType().IsArray)
        {
            var ele = (IEnumerator)obj.GetType().GetMethod("GetEnumerator").Invoke(obj, null);
            while (ele.MoveNext())
            {
                recursiveLevel = 0;
                var arrItem = ele.Current;

                act(paths, arrItem);
            }
        }
        else
        {
            recursiveLevel = 0;
            act(paths, obj);
        }

    }

    public static T Explode<T>(this T[] obj)
    {
        return obj.FirstOrDefault();
    }

    public static T Explode<T>(this ICollection<T> obj)
    {
        return obj.FirstOrDefault();
    }
}

above extension class will give you the ability to set the property to null to avoid the self-referencing loop even arrays.

Expression Builder

    internal class PropertyVisitor<T> : ExpressionVisitor
{
    public readonly List<MemberInfo> Path = new List<MemberInfo>();

    public Expression Modify(Expression expression)
    {
        return Visit(expression);
    }


    protected override Expression VisitMember(MemberExpression node)
    {
        if (!(node.Member is PropertyInfo))
        {
            throw new ArgumentException("The path can only contain properties", nameof(node));
        }

        Path.Add(node.Member);
        return  base.VisitMember(node);
    }
}

Usages:

Model Classes

    public class Person
{
    public string Name { get; set; }
    public Address AddressDetail { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public Country CountryDetail { get; set; }
    public Country[] CountryDetail2 { get; set; }
}

public class Country
{
    public string CountryName { get; set; }
    public Person[] CountryDetail { get; set; }
}

Dummy Data

           var p = new Person
        {
            Name = "Adeel Rizvi",
            AddressDetail = new Address
            {
                Street = "Sydney",
                CountryDetail = new Country
                {
                    CountryName = "AU"
                }
            }
        };

        var p1 = new Person
        {
            Name = "Adeel Rizvi",
            AddressDetail = new Address
            {
                Street = "Sydney",
                CountryDetail2 = new Country[]
                {
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A1" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A2" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A3" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A4" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A5" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A6" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A7" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A8" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A9" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A1" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A2" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A3" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A4" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A5" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A6" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A7" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A8" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },
                    new Country{ CountryName = "AU", CountryDetail = new Person[]{ new Person { Name = "A9" }, new Person { Name = "A1" }, new Person { Name = "A1" } } },

                }
            }
        };

Cases:

Case 1: Exclude only property without any array

p.Exclude(n => n.AddressDetail.CountryDetail.CountryName);

Case 2: Exclude property with 1 array

p1.Exclude(n => n.AddressDetail.CountryDetail2.Explode().CountryName);

Case 3: Exclude property with 2 nested array

p1.Exclude(n => n.AddressDetail.CountryDetail2.Explode().CountryDetail.Explode().Name);

Case 4: EF GetAll Query With Includes

var query = cs.GetAll("CompanyUsers", "CompanyUsers.User").ToArray();
query.Exclude(n => n.Explode().CompanyUsers.Explode().User.CompanyUsers);
return query;

You have notice that Explode() method its also a extension method just for our expression builder to get the property from array property. Whenever there is a array property use the .Explode().YourPropertyToExclude or .Explode().Property1.MyArrayProperty.Explode().MyStupidProperty. Above code helps me to avoid the self-referencing so deep as deep i want. Now i can use GetAll and exclude the property which i don;t want!

Thank you for reading this big post!

Is it possible to get only the first character of a String?

The string has a substring method that returns the string at the specified position.

String name="123456789";
System.out.println(name.substring(0,1));

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

Jenkins Git Plugin: How to build specific tag?

None of these answers were sufficient for me, using Jenkins CI v.1.555, Git Client plugin v.1.6.4, and Git plugin 2.0.4.

I wanted a job to build for one Git repository for one specific, fixed (i.e., non-parameterized) tag. I had to cobble together a solution from the various answers plus the "build a Git tag" blog post cited by Thilo.

  1. Make sure you push your tag to the remote repository with git push --tags
  2. In the "Git Repository" section of your job, under the "Source Code Management" heading, click "Advanced".
  3. In the field for Refspec, add the following text: +refs/tags/*:refs/remotes/origin/tags/*
  4. Under "Branches to build", "Branch specifier", put */tags/<TAG_TO_BUILD> (replacing <TAG_TO_BUILD> with your actual tag name).

Adding the Refspec for me turned out to be critical. Although it seemed the git repositories were fetching all the remote information by default when I left it blank, the Git plugin would nevertheless completely fail to find my tag. Only when I explicitly specified "get the remote tags" in the Refspec field was the Git plugin able to identify and build from my tag.

Update 2014-5-7: Unfortunately, this solution does come with an undesirable side-effect for Jenkins CI (v.1.555) and the Git repository push notification mechanism à la Stash Webhook to Jenkins: any time any branch on the repository is updated in a push, the tag build jobs will also fire again. This leads to a lot of unnecessary re-builds of the same tag jobs over and over again. I have tried configuring the jobs both with and without the "Force polling using workspace" option, and it seemed to have no effect. The only way I could prevent Jenkins from making the unnecessary builds for the tag jobs is to clear the Refspec field (i.e., delete the +refs/tags/*:refs/remotes/origin/tags/*).

If anyone finds a more elegant solution, please edit this answer with an update. I suspect, for example, that maybe this wouldn't happen if the refspec specifically was +refs/tags/<TAG TO BUILD>:refs/remotes/origin/tags/<TAG TO BUILD> rather than the asterisk catch-all. For now, however, this solution is working for us, we just remove the extra Refspec after the job succeeds.

Real-world examples of recursion

Recursion is used in things like BSP trees for collision detection in game development (and other similar areas).

Create controller for partial view in ASP.NET MVC

Html.Action is a poorly designed technology. Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.

To be closer to WebForm UserControl (*.ascx) you need to:

  1. Create a page Model and a Partial Model

  2. Place your Partial Model as a property in your page Model

  3. In page's View use Html.EditorFor(m => m.MyPartialModel)
  4. Create an appropriate Partial View
  5. Create a class very similar to that Child Action Controller described here in answers many times. But it will be just a class (inherited from Object rather than from Controller). Let's name it as MyControllerPartial. MyControllerPartial will know only about Partial Model.
  6. Use your MyControllerPartial in your page controller. Pass model.MyPartialModel to MyControllerPartial
  7. Take care about proper prefix in your MyControllerPartial. Fox example: ModelState.AddError("MyPartialModel." + "SomeFieldName", "Error")
  8. In MyControllerPartial you can make validation and implement other logics related to this Partial Model

In this situation you can use it like:

public class MyController : Controller
{
    ....
    public MyController()
    {
    MyChildController = new MyControllerPartial(this.ViewData);
    }

    [HttpPost]
    public ActionResult Index(MyPageViewModel model)
    {
    ...
    int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
    ...
    }
}

P.S. In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see ASP.NET MVC partial views: input name prefixes

Implicit function declarations in C

Implicit declarations are not valid in C.

C99 removed this feature (present in C89).

gcc chooses to only issue a warning by default with -std=c99 but a compiler has the right to refuse to translate such a program.

Trim Cells using VBA in Excel

Only thing that worked for me is this function:

Sub DoTrim()
Dim cell As Range
Dim str As String
For Each cell In Selection.Cells
    If cell.HasFormula = False Then
        str = Left(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Right(cell.Value, Len(cell.Value) - 1)
            str = Left(cell.Value, 1) 'space
        Wend
        str = Right(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Left(cell.Value, Len(cell.Value) - 1)
            str = Right(cell.Value, 1) 'space
        Wend
    End If
Next cell
End Sub

How to declare a global variable in php?

You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
    echo "$foo $bar";
})("York");

demo | info

When is it appropriate to use C# partial classes?

Service references are another example where partial classes are useful to separate generated code from user-created code.

You can "extend" the service classes without having them overwritten when you update the service reference.

Getter and Setter?

I made an experiment using the magic method __call. Not sure if I should post it (because of all the "DO NOT USE MAGIC METHODS" warnings in the other answers and comments) but i'll leave it here.. just in case someone find it useful.


public function __call($_name, $_arguments){
    $action  = substr($_name, 0, 4);
    $varName = substr($_name, 4);

    if (isset($this->{$varName})){
        if ($action === "get_") return $this->{$varName};
        if ($action === "set_") $this->{$varName} = $_arguments[0];
    }
}

Just add that method above in your class, now you can type:

class MyClass{
    private foo = "bar";
    private bom = "bim";
    // ...
    // public function __call(){ ... }
    // ...
}
$C = new MyClass();

// as getter
$C->get_foo(); // return "bar"
$C->get_bom(); // return "bim"

// as setter
$C->set_foo("abc"); // set "abc" as new value of foo
$C->set_bom("zam"); // set "zam" as new value of bom


This way you can get/set everything in your class if it exist so, if you need it for only a few specific elements, you could use a "whitelist" as filter.

Example:

private $callWhiteList = array(
    "foo" => "foo",
    "fee" => "fee",
    // ...
);

public function __call($_name, $_arguments){
    $action  = substr($_name, 0, 4);
    $varName = $this->callWhiteList[substr($_name, 4)];

    if (!is_null($varName) && isset($this->{$varName})){
        if ($action === "get_") return $this->{$varName};
        if ($action === "set_") $this->{$varName} = $_arguments[0];
    }
}

Now you can only get/set "foo" and "fee".
You can also use that "whitelist" to assign custom names to access to your vars.
For example,

private $callWhiteList = array(
    "myfoo" => "foo",
    "zim" => "bom",
    // ...
);

With that list you can now type:

class MyClass{
    private foo = "bar";
    private bom = "bim";
    // ...
    // private $callWhiteList = array( ... )
    // public function __call(){ ... }
    // ...
}
$C = new MyClass();

// as getter
$C->get_myfoo(); // return "bar"
$C->get_zim(); // return "bim"

// as setter
$C->set_myfoo("abc"); // set "abc" as new value of foo
$C->set_zim("zam"); // set "zam" as new value of bom

.
.
.
That's all.


Doc: __call() is triggered when invoking inaccessible methods in an object context.

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

I found this question after seeing the 'more than one device' error, with 2 offline phones showing:

C:\Program Files (x86)\Android\android-sdk\android-tools>adb devices
List of devices attached
SH436WM01785    offline
SH436WM01785    offline
SH436WM01785    sideload

If you only have one device connected, run the following commands to get rid of the offline connections:

adb kill-server
adb devices

How to create a self-signed certificate for a domain name for development?

Using PowerShell

From Windows 8.1 and Windows Server 2012 R2 (Windows PowerShell 4.0) and upwards, you can create a self-signed certificate using the new New-SelfSignedCertificate cmdlet:

Examples:

New-SelfSignedCertificate -DnsName www.mydomain.com -CertStoreLocation cert:\LocalMachine\My

New-SelfSignedCertificate -DnsName subdomain.mydomain.com -CertStoreLocation cert:\LocalMachine\My

New-SelfSignedCertificate -DnsName *.mydomain.com -CertStoreLocation cert:\LocalMachine\My

Using the IIS Manager

  1. Launch the IIS Manager
  2. At the server level, under IIS, select Server Certificates
  3. On the right hand side under Actions select Create Self-Signed Certificate
  4. Where it says "Specify a friendly name for the certificate" type in an appropriate name for reference.
    1. Examples: www.domain.com or subdomain.domain.com
  5. Then, select your website from the list on the left hand side
  6. On the right hand side under Actions select Bindings
  7. Add a new HTTPS binding and select the certificate you just created (if your certificate is a wildcard certificate you'll need to specify a hostname)
  8. Click OK and test it out.

how to get login option for phpmyadmin in xampp

You can use

  1. Go browser & type localhost/phpmyadmin/
  2. Go to User accounts
  3. Edit privileges from marked bellow image in last options root->localhost-> Yes->ALL PRIVILEGES->Yes-> Edit privileges

Here is image like bellow enter image description here

  1. you can click on Edit privileges last option above image
  2. Then you can click on Change password. It shows enter password screen
  3. Enter your password & retype your password in password the field
  4. Then click on GO
  5. Then Go to XAMPP->xamppfiles->config.inc.php
  6. Open config.inc.php file & go to /* Authentication type */ sections
  7. change config to cookie & type your password in ' ' in password like bellow

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = 'your password';
    
  8. Then save & type on browser localhost/phpmyadmin/

  9. Enter your given password & enjoy

Find and replace words/lines in a file

You can use Java's Scanner class to parse words of a file and process them in your application, and then use a BufferedWriter or FileWriter to write back to the file, applying the changes.

I think there is a more efficient way of getting the iterator's position of the scanner at some point, in order to better implement editting. But since files are either open for reading, or writing, I'm not sure regarding that.

In any case, you can use libraries already available for parsing of XML files, which have all of this implemented already and will allow you to do what you want easily.

How to remove unused dependencies from composer?

In fact, it is very easy.

composer update

will do all this for you, but it will also update the other packages.

To remove a package without updating the others, specifiy that package in the command, for instance:

composer update monolog/monolog

will remove the monolog/monolog package.

Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.

How to use jQuery Plugin with Angular 4?

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

Auto-size dynamic text to fill fixed size container

Thanks Attack. I wanted to use jQuery.

You pointed me in the right direction, and this is what I ended up with:

Here is a link to the plugin: https://plugins.jquery.com/textfill/
And a link to the source: http://jquery-textfill.github.io/

;(function($) {
    $.fn.textfill = function(options) {
        var fontSize = options.maxFontPixels;
        var ourText = $('span:visible:first', this);
        var maxHeight = $(this).height();
        var maxWidth = $(this).width();
        var textHeight;
        var textWidth;
        do {
            ourText.css('font-size', fontSize);
            textHeight = ourText.height();
            textWidth = ourText.width();
            fontSize = fontSize - 1;
        } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        return this;
    }
})(jQuery);

$(document).ready(function() {
    $('.jtextfill').textfill({ maxFontPixels: 36 });
});

and my html is like this

<div class='jtextfill' style='width:100px;height:50px;'>
    <span>My Text Here</span>
</div>

This is my first jquery plugin, so it's probably not as good as it should be. Pointers are certainly welcome.

Figure out size of UILabel based on String in Swift

This solution will help to calculate the height and width at runtime.

    let messageText = "Your Text String"
    let size = CGSize.init(width: 250, height: 1000)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    let estimateFrame = NSString(string: messageText).boundingRect(with:  size, options: options, attributes: [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue", size: 17)!], context: nil)

Here you can calculate the estimated height that your string would take and pass it to the UILabel frame.

estimateFrame.Width
estimateFrame.Height 

Laravel 5 Clear Views Cache

To get all the artisan command, type...

php artisan

If you want to clear view cache, just use:

php artisan view:clear

If you don't know how to use specific artisan command, just add "help" (see below)

php artisan help view:clear

Generate MD5 hash string with T-SQL

SELECT CONVERT(
      VARCHAR(32),
      HASHBYTES(
                   'MD5',
                   CAST(prescrip.IsExpressExamRX AS VARCHAR(250))
                   + CAST(prescrip.[Description] AS VARCHAR(250))
               ),
      2
  ) MD5_Value;

works for me.

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

Try to go back to the internet information services, right clink on the intranet you created and select edit permission.

When the wwwroot pop up windows open, select the sharing tab and click "share" on the drop down menu select the users and their permission level or just select everyone and for permission read and Right

Run chrome in fullscreen mode on Windows

Running chrome.exe --start-fullscreen --app=https://google.com will not get you Chrome in fullscreen, but in kiosk mode.

However, running chrome --start-fullscreen --app=https://google.com (notice : it's chrome instead of chrome.exe) worked in my case.

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()

{this.renderIcon()}   

jQuery: How can I show an image popup onclick of the thumbnail?

This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You can use

Trace.WriteLine()

to write to the Output window when debugging a unit test.

docker run <IMAGE> <MULTIPLE COMMANDS>

You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    

How to do a redirect to another route with react-router?

For the simple answer, you can use Link component from react-router, instead of button. There is ways to change the route in JS, but seems you don't need that here.

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>

To do it programmatically in 1.0.x, you do like this, inside your clickHandler function:

this.history.pushState(null, 'login');

Taken from upgrade doc here

You should have this.history placed on your route handler component by react-router. If it child component beneath that mentioned in routes definition, you may need pass that down further

Vertical align in bootstrap table

SCSS

.table-vcenter {
    td,
    th {
        vertical-align: middle;
    }
}

use

<table class="table table-vcenter">
</table>

blur() vs. onblur()

Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.

Javascript Equivalent to C# LINQ Select

Since you're using knockout, you should consider using the knockout utility function arrayMap() and it's other array utility functions.

Here's a listing of array utility functions and their equivalent LINQ methods:

arrayFilter() -> Where()
arrayFirst() -> First()
arrayForEach() -> (no direct equivalent)
arrayGetDistictValues() -> Distinct()
arrayIndexOf() -> IndexOf()
arrayMap() -> Select()
arrayPushAll() -> (no direct equivalent)
arrayRemoveItem() -> (no direct equivalent)
compareArrays() -> (no direct equivalent)

So what you could do in your example is this:

var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
    return fruit.id;
});

If you want a LINQ like interface in javascript, you could use a library such as linq.js which offers a nice interface to many of the LINQ methods.

var mapped = Enumerable.From(selectedFruits)
    .Select("$.id") // 1 of 3 different ways to specify a selector function
    .ToArray();

Communication between tabs or windows

There is a modern API dedicated for this purpose - Broadcast Channel

It is as easy as:

var bc = new BroadcastChannel('test_channel');

bc.postMessage('This is a test message.'); /* send */

bc.onmessage = function (ev) { console.log(ev); } /* receive */

There is no need for the message to be just a DOMString, any kind of object can be sent.

Probably, apart from API cleanness, it is the main benefit of this API - no object stringification.

Currently supported only in Chrome and Firefox, but you can find a polyfill that uses localStorage.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Combine two (or more) PDF's

Combining two byte[] using iTextSharp up to version 5.x:

internal static MemoryStream mergePdfs(byte[] pdf1, byte[] pdf2)
{
    MemoryStream outStream = new MemoryStream();
    using (Document document = new Document())
    using (PdfCopy copy = new PdfCopy(document, outStream))
    {
        document.Open();
        copy.AddDocument(new PdfReader(pdf1));
        copy.AddDocument(new PdfReader(pdf2));
    }
    return outStream;
}

Instead of the byte[]'s it's possible to pass also Stream's

Xcode 10 Error: Multiple commands produce

For me the problem was tied to having the same file included in the bundle resources twice. Not sure how that happened, but I removed one of them and it compiled fine with the new build system.

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

Well yes, the access exception is due to the fact that document.domain must match in your parent and your iframe, and before they do, you won't be able to programmatically set the document.domain property of your iframe.

I think your best option here is to point the page to a template of your own:

iframe.src = '/myiframe.htm#' + document.domain;

And in myiframe.htm:

document.domain = location.hash.substring(1);

SQL : BETWEEN vs <= and >=

Logically there are no difference at all. Performance-wise there are -typically, on most DBMSes- no difference at all.

data.frame Group By column

This is a common question. In base, the option you're looking for is aggregate. Assuming your data.frame is called "mydf", you can use the following.

> aggregate(B ~ A, mydf, sum)
  A  B
1 1  5
2 2  3
3 3 11

I would also recommend looking into the "data.table" package.

> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
   A V1
1: 1  5
2: 2  3
3: 3 11

React - Preventing Form Submission

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

Example: http://jsbin.com/vowuley/edit?html,js,console,output

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

_x000D_
_x000D_
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
_x000D_
_x000D_
_x000D_

Process escape sequences in a string in Python

This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.

input_string = eval('b"' + sys.argv[1] + '"')

It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?

PHP CURL DELETE request

I finally solved this myself. If anyone else is having this problem, here is my solution:

I created a new method:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

Update 2

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

Where does Jenkins store configuration files for the jobs it runs?

Jenkins stores some of the related builds data like the following:

  • The working directory is stored in the directory {JENKINS_HOME}/workspace/.

    • Each job store its related temporal workspace folder in the directory {JENKINS_HOME}/workspace/{JOBNAME}
  • The configuration for all jobs stored in the directory {JENKINS_HOME}/jobs/.

    • Each job store its related builds data in the directory {JENKINS_HOME}/jobs/{JOBNAME}

    • Each job folder contains:

      • The job configuration file is {JENKINS_HOME}/jobs/{JOBNAME}/config.xml

      • The job builds are stored in {JENKINS_HOME}/jobs/{JOBNAME}/builds/

See the Jenkins documentation for a visual representation and further details.

JENKINS_HOME
 +- config.xml     (jenkins root configuration)
 +- *.xml          (other site-wide configuration files)
 +- userContent    (files in this directory will be served under your http://server/userContent/)
 +- fingerprints   (stores fingerprint records)
 +- nodes          (slave configurations)
 +- plugins        (stores plugins)
 +- secrets        (secretes needed when migrating credentials to other servers)
 +- workspace (working directory for the version control system)
     +- [JOBNAME] (sub directory for each job)
 +- jobs
     +- [JOBNAME]      (sub directory for each job)
         +- config.xml     (job configuration file)
         +- latest         (symbolic link to the last successful build)
         +- builds
             +- [BUILD_ID]     (for each build)
                 +- build.xml      (build result summary)
                 +- log            (log file)
                 +- changelog.xml  (change log)

How to replace list item in best way

i find best for do it fast and simple

  1. find ur item in list

    var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
    
  2. make clone from current

    OrderDetail dd = d;
    
  3. Update ur clone

    dd.Quantity++;
    
  4. find index in list

    int idx = Details.IndexOf(d);
    
  5. remove founded item in (1)

      Details.Remove(d);
    
  6. insert

     if (idx > -1)
          Details.Insert(idx, dd);
      else
          Details.Insert(Details.Count, dd);
    

How do I tell if a variable has a numeric value in Perl?

I found this interesting though

if ( $value + 0 eq $value) {
    # A number
    push @args, $value;
} else {
    # A string
    push @args, "'$value'";
}

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

How to find MAC address of an Android device programmatically

With this code you will be also able to get MacAddress in Android 6.0 also

public static String getMacAddr() {
    try {
        List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif: all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b: macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {}
    return "02:00:00:00:00:00";
}

EDIT 1. This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

return(
  data.frame(
    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE
  )
)

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

How to create a hidden <img> in JavaScript?

How about

<img style="display: none;" src="a.gif">

That will disable the display completely, and not leave a placeholder

Linux command for extracting war file?

You can use the unzip command.

Sorting object property by values

Sort values without multiple for-loops (to sort by the keys change index in the sort callback to "0")

_x000D_
_x000D_
const list = {_x000D_
    "you": 100, _x000D_
    "me": 75, _x000D_
    "foo": 116, _x000D_
    "bar": 15_x000D_
  };_x000D_
_x000D_
let sorted = Object.fromEntries(_x000D_
                Object.entries(list).sort( (a,b) => a[1] - b[1] )    _x000D_
             ) _x000D_
console.log('Sorted object: ', sorted) 
_x000D_
_x000D_
_x000D_

invalid conversion from 'const char*' to 'char*'

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Actually, none of these answers reflect current state of the art with Git (v2.29 by time of writing this answer). In the latest versions of Git, cache, winstore, wincred are deprecated.


If you want to clone a Bitbucket repository via HTTPS, e.g.

git clone https://[email protected]/SomeOrganization/SomeRepo.git

You have to:

  1. Generate app password at Bitbucket user administration.
  2. Setup your credential method in .gitconfig accordingly (global or local)
[credential]
    helper = manager

You can locate your .gitconfig by executing this command.

git config --list --show-origin
  1. Execute
git clone https://[email protected]/SomeOrganization/SomeRepo.git

and wait until log on window appears. Use your user name from the url (kutlime in my case) and your generated app password as a password.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

POST request via RestTemplate in JSON

I'm doing in this way and it works .

HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{   
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    for (Entry<String, String> entry : map.entrySet()) {
        headers.add(entry.getKey(),entry.getValue());
    }
    return headers;
}

// Pass headers here

 String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());

Hope this helps

How to get the difference between two arrays in JavaScript?

You can use underscore.js : http://underscorejs.org/#intersection

You have needed methods for array :

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

How to run a cron job on every Monday, Wednesday and Friday?

Use crontab to add job

  crontab -e

And job should be in this format:

  00 19 * * 1,3,5 /home/user/somejob.sh

Load a bitmap image into Windows Forms using open file dialog

Works Fine. Try this,

private void addImageButton_Click(object sender, EventArgs e)
{
    OpenFileDialog of = new OpenFileDialog();
    //For any other formats
    of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG"; 
    if (of.ShowDialog() == DialogResult.OK)
    {
        pictureBox1.ImageLocation = of.FileName;

    }
}

Remove large .pack file created by git

One option:

run git gc manually to condense a number of pack files into one or a few pack files. This operation is persistent (i.e. the large pack file will retain its compression behavior) so it may be beneficial to compress a repository periodically with git gc --aggressive

Another option is to save the code and .git somewhere and then delete the .git and start again using this existing code, creating a new git repository (git init).

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

How to find the minimum value in an ArrayList, along with the index number? (Java)

Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);

while (a.size() > 0) {
    int min = 1000;
    for (int b:a) {
        if (b < min)
            min = b;
    }
    System.out.println("minimum: " + min);
    System.out.println("index of min: " + a.indexOf((Integer) min));
    a.remove((Integer) min);
}

How can I generate a list or array of sequential integers in Java?

Well, this one liner might qualify (uses Guava Ranges)

ContiguousSet<Integer> integerList = ContiguousSet.create(Range.closedOpen(0, 10), DiscreteDomain.integers());
System.out.println(integerList);

This doesn't create a List<Integer>, but ContiguousSet offers much the same functionality, in particular implementing Iterable<Integer> which allows foreach implementation in the same way as List<Integer>.

In older versions (somewhere before Guava 14) you could use this:

ImmutableList<Integer> integerList = Ranges.closedOpen(0, 10).asSet(DiscreteDomains.integers()).asList();
System.out.println(integerList);

Both produce:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Delete directory with files in it?

I do not remember from where I copied this function, but it looks like it is not listed and it is working for me

function rm_rf($path) {
    if (@is_dir($path) && is_writable($path)) {
        $dp = opendir($path);
        while ($ent = readdir($dp)) {
            if ($ent == '.' || $ent == '..') {
                continue;
            }
            $file = $path . DIRECTORY_SEPARATOR . $ent;
            if (@is_dir($file)) {
                rm_rf($file);
            } elseif (is_writable($file)) {
                unlink($file);
            } else {
                echo $file . "is not writable and cannot be removed. Please fix the permission or select a new path.\n";
            }
        }
        closedir($dp);
        return rmdir($path);
    } else {
        return @unlink($path);
    }
}

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

How to check if the URL contains a given string?

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf('franky') > -1) {
     alert("your url contains the name franky");
}

vagrant login as root by default

I know this is an old question, but looking at the original question, it looks like the user just wanted to run a command as root, that's what I need to do when I was searching for an answer and stumbled across the question.

So this one is worth knowing in my opinion:

vagrant ssh servername -c "echo vagrant | sudo -S shutdown 0"

vagrant is the password being echoed into the the sudo command, because as we all know, the vagrant account has sudo privileges and when you sudo, you need to specify the password of the user account, not root..and of course by default, the vagrant user's password is vagrant !

By default you need root privileges to shutdown so I guess doing a shutdown is a good test.

Obviously you don't need to specify a server name if there is only one for that vagrant environment. Also, we're talking about local vagrant virtual machine to the host, so there isn't really any security issue that I can see.

Hope this helps.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me issue is resolved by changing envs like this:

 env.put("LDAP_BASEDN", base)
 env.put(Context.SECURITY_PRINCIPAL,"user@domain")

log4net vs. Nlog

If you go here you can find a comprehensive matrix that includes both the NLog and Log4Net libs as well as Enterprise Lib and other products.

Somebody could argue that the matrix is done in a way to underline the features of the only commercial lib present in the matrix. I think it's true but it was useful anyway to drive my choice versus NLog.

Regards

How to add bootstrap in angular 6 project?

using command

npm install bootstrap --save

open .angular.json old (.angular-cli.json ) file find the "styles" add the bootstrap css file

"styles": [
       "src/styles.scss",
       "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

How to create a fixed-size array of objects

One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.

var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]

Getting visitors country from their IP

You can use a web-service from http://ip-api.com
in your php code, do as follow :

<?php
$ip = $_REQUEST['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
  echo 'Hello visitor from '.$query['country'].', '.$query['city'].'!';
} else {
  echo 'Unable to get location';
}
?>

the query have many other informations:

array (
  'status'      => 'success',
  'country'     => 'COUNTRY',
  'countryCode' => 'COUNTRY CODE',
  'region'      => 'REGION CODE',
  'regionName'  => 'REGION NAME',
  'city'        => 'CITY',
  'zip'         => ZIP CODE,
  'lat'         => LATITUDE,
  'lon'         => LONGITUDE,
  'timezone'    => 'TIME ZONE',
  'isp'         => 'ISP NAME',
  'org'         => 'ORGANIZATION NAME',
  'as'          => 'AS NUMBER / NAME',
  'query'       => 'IP ADDRESS USED FOR QUERY',
)

Restart container within pod

kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1

Assuming the container is run as root which is not recommended.

In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.

Read and write to binary files in C?

This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin;

Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
     {  printf("\n Unable to open the file ");
         exit(1);
      }

 fout=fopen("D:\\ newpic.jpg","wb");
 ch=fgetc(fin);
       while (ch!=EOF)
             { 
                  s=(char *)ch;
                  printf("%c",s);
                 ch=fgetc (fin):
                 fputc(s,fout);
                 s++;
              }

        printf("data read and copied");
        fclose(fin);
        fclose(fout);

Why can a function modify some arguments as perceived by the caller, but not others?

I will rename variables to reduce confusion. n -> nf or nmain. x -> xf or xmain:

def f(nf, xf):
    nf = 2
    xf.append(4)
    print 'In f():', nf, xf

def main():
    nmain = 1
    xmain = [0,1,2,3]
    print 'Before:', nmain, xmain
    f(nmain, xmain)
    print 'After: ', nmain, xmain

main()

When you call the function f, the Python runtime makes a copy of xmain and assigns it to xf, and similarly assigns a copy of nmain to nf.

In the case of n, the value that is copied is 1.

In the case of x the value that is copied is not the literal list [0, 1, 2, 3]. It is a reference to that list. xf and xmain are pointing at the same list, so when you modify xf you are also modifying xmain.

If, however, you were to write something like:

    xf = ["foo", "bar"]
    xf.append(4)

you would find that xmain has not changed. This is because, in the line xf = ["foo", "bar"] you have change xf to point to a new list. Any changes you make to this new list will have no effects on the list that xmain still points to.

Hope that helps. :-)

What is an IIS application pool?

Application pools are used to separate set of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability

How to get input text value from inside td

Ah I think a understand now. Have a look if this really is what you want:

$(".start").keyup(function(){
    $(this).closest('tr').find("input").each(function() {
        alert(this.value)
    });
});

This will give you all input values of a row.

Update:
To get the value of not all elements you can use :not():

$(this).closest('tr').find("input:not([name^=desc][name^=phone])").each(function() {
     alert(this.value)
});

Actually I am not 100% sure whether it works this way, maybe you have to use two nots instead of this one combining both conditions.

How to Right-align flex item?

If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:

h1 {
   flex-basis: 100%; // forces this element to take up any remaining space
}

img {
   margin: 0 5px; // small margin between images
   height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}

Here's what that will look like (only relavent CSS was included in snippet above)

enter image description here

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

How to assign the output of a command to a Makefile variable

Beware of recipes like this

target:
    MY_ID=$(GENERATE_ID);
    echo $MY_ID;

It does two things wrong. The first line in the recipe is executed in a separate shell instance from the second line. The variable is lost in the meantime. Second thing wrong is that the $ is not escaped.

target:
    MY_ID=$(GENERATE_ID); \
    echo $$MY_ID;

Both problems have been fixed and the variable is useable. The backslash combines both lines to run in one single shell, hence the setting of the variable and the reading of the variable afterwords, works.

I realize the original post said how to get the results of a shell command into a MAKE variable, and this answer shows how to get it into a shell variable. But other readers may benefit.

One final improvement, if the consumer expects an "environment variable" to be set, then you have to export it.

my_shell_script
    echo $MY_ID

would need this in the makefile

target:
    export MY_ID=$(GENERATE_ID); \
    ./my_shell_script;

Hope that helps someone. In general, one should avoid doing any real work outside of recipes, because if someone use the makefile with '--dry-run' option, to only SEE what it will do, it won't have any undesirable side effects. Every $(shell) call is evaluated at compile time and some real work could accidentally be done. Better to leave the real work, like generating ids, to the inside of the recipes when possible.

SQL Server Creating a temp table for this query

If you want to create a temp table after check exist table.You can use the following code

DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
  (
   SiteName             NVARCHAR(50),
   BillingMonth         varchar(10),
   Consumption          INT,
  )

After creating the temporary table, you can insert data into this table as a regular table:

INSERT INTO #temptable
SELECT COLUMN1,...
FROM
(...)

or

INSERT INTO #temptable
VALUES (value1, value2, value3, ...);

The SELECT statement is used to select data from a temp table.

SELECT * FROM #temptable

you can manually remove the temporary table by using the DROP TABLE statement:

DROP TABLE #temptable;

changing the language of error message in required field in html5 contact form

your forget this in oninvalid, change your code with this:

    oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"

enter image description here

_x000D_
_x000D_
<form><input type="text" name="company_name"  oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')" required /><input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

What is the difference between README and README.md in GitHub projects?

README.md or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

dereferencing pointer to incomplete type

What do you mean, the error only shows up when you assign? For example on GCC, with no assignment in sight:

int main() {
    struct blah *b = 0;
    *b; // this is line 6
}

incompletetype.c:6: error: dereferencing pointer to incomplete type.

The error is at line 6, that's where I used an incomplete type as if it were a complete type. I was fine up until then.

The mistake is that you should have included whatever header defines the type. But the compiler can't possibly guess what line that should have been included at: any line outside of a function would be fine, pretty much. Neither is it going to go trawling through every text file on your system, looking for a header that defines it, and suggest you should include that.

Alternatively (good point, potatoswatter), the error is at the line where b was defined, when you meant to specify some type which actually exists, but actually specified blah. Finding the definition of the variable b shouldn't be too difficult in most cases. IDEs can usually do it for you, compiler warnings maybe can't be bothered. It's some pretty heinous code, though, if you can't find the definitions of the things you're using.

How can I use a DLL file from Python?

If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr
clr.AddReference('path_to_your_dll')

then instantiate an object as per the class in the DLL, and access the methods within it.

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

How to 'grep' a continuous stream?

sed would be a better choice (stream editor)

tail -n0 -f <file> | sed -n '/search string/p'

and then if you wanted the tail command to exit once you found a particular string:

tail --pid=$(($BASHPID+1)) -n0 -f <file> | sed -n '/search string/{p; q}'

Obviously a bashism: $BASHPID will be the process id of the tail command. The sed command is next after tail in the pipe, so the sed process id will be $BASHPID+1.

How to get the IP address of the docker host from inside a docker container

For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.

curl http://169.254.169.254/latest/meta-data/local-ipv4

For example:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

Using jQuery to programmatically click an <a> link

Try this:

$('#myAnchor')[0].click();

It works for me.

Python method for reading keypress?

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

Escaping double quotes in JavaScript onClick event handler

I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

Casting interfaces for deserialization in JSON.NET

Nicholas Westby provided a great solution in a awesome article.

If you want Deserializing JSON to one of many possible classes that implement an interface like that:

public class Person
{
    public IProfession Profession { get; set; }
}

public interface IProfession
{
    string JobTitle { get; }
}

public class Programming : IProfession
{
    public string JobTitle => "Software Developer";
    public string FavoriteLanguage { get; set; }
}

public class Writing : IProfession
{
    public string JobTitle => "Copywriter";
    public string FavoriteWord { get; set; }
}

public class Samples
{
    public static Person GetProgrammer()
    {
        return new Person()
        {
            Profession = new Programming()
            {
                FavoriteLanguage = "C#"
            }
        };
    }
}

You can use a custom JSON converter:

public class ProfessionConverter : JsonConverter
{
    public override bool CanWrite => false;
    public override bool CanRead => true;
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(IProfession);
    }
    public override void WriteJson(JsonWriter writer,
        object value, JsonSerializer serializer)
    {
        throw new InvalidOperationException("Use default serialization.");
    }

    public override object ReadJson(JsonReader reader,
        Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var profession = default(IProfession);
        switch (jsonObject["JobTitle"].Value())
        {
            case "Software Developer":
                profession = new Programming();
                break;
            case "Copywriter":
                profession = new Writing();
                break;
        }
        serializer.Populate(jsonObject.CreateReader(), profession);
        return profession;
    }
}

And you will need to decorate the "Profession" property with a JsonConverter attribute to let it know to use your custom converter:

    public class Person
    {
        [JsonConverter(typeof(ProfessionConverter))]
        public IProfession Profession { get; set; }
    }

And then, you can cast your class with an Interface:

Person person = JsonConvert.DeserializeObject<Person>(jsonString);

How to mount host volumes into docker containers in Dockerfile during build

I think you can do what you want to do by running the build via a docker command which itself is run inside a docker container. See Docker can now run within Docker | Docker Blog. A technique like this, but which actually accessed the outer docker from with a container, was used, e.g., while exploring how to Create the smallest possible Docker container | Xebia Blog.

Another relevant article is Optimizing Docker Images | CenturyLink Labs, which explains that if you do end up downloading stuff during a build, you can avoid having space wasted by it in the final image by downloading, building and deleting the download all in one RUN step.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I had a similar issue when calling the WPF window out of WinForms.

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

However, showing window as a dialog, it worked

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.ShowDialog();

Hope this helps.

Android "hello world" pushnotification example

you can follow this tutorial

http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/

it helped me to do a push notification; or you can follow this other tutorial

http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html

but it's in spanish but you can download the code.

Handling a Menu Item Click Event - Android

Add Following Code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent i = new Intent(this,SecondActivity.class);
            this.startActivity(i);
            return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

SQL SERVER DATETIME FORMAT

Compatibility Supports Says that Under compatibility level 110, the default style for CAST and CONVERT operations on time and datetime2 data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.

That means by default datetime2 is CAST as varchar to 121 format. For ex; col1 and col2 formats (below) are same (other than the 0s at the end)

SELECT CONVERT(varchar, GETDATE(), 121) col1,
       CAST(convert(datetime2,GETDATE()) as varchar) col2,
       CAST(GETDATE() as varchar) col3

SQL FIDDLE DEMO

--Results
COL1                    | COL2                          | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000   | Feb 8 2013 9:53AM

FYI, if you use CONVERT instead of CAST you can use a third parameter to specify certain formats as listed here on MSDN

Convert a python UTC datetime to a local datetime using only python standard library?

A simple (but maybe flawed) way that works in Python 2 and 3:

import time
import datetime

def utc_to_local(dt):
    return dt - datetime.timedelta(seconds = time.timezone)

Its advantage is that it's trivial to write an inverse function

How can I run dos2unix on an entire directory?

If there is no sub-directory, you can also take

ls | xargs -I {} dos2unix "{}"

Can't get Gulp to run: cannot find module 'gulp-util'

This will solve all gulp problem

sudo npm install gulp && sudo npm install --save del && sudo gulp build

using CASE in the WHERE clause

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Why does using an Underscore character in a LIKE filter give me all the results?

As you want to specifically search for a wildcard character you need to escape that

This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

So your query would result in:

select * 
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';

But you can just as well use any other character:

select * 
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';

Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

how to empty recyclebin through command prompt?

I prefer recycle.exe from Frank P. Westlake. It provides a nice before and after status. (I've been using Frank's various utilities for well over ten years..)

C:\> recycle.exe /E /F
Recycle Bin: ALL
    Recycle Bin C:  44 items, 42,613,970 bytes.
    Recycle Bin D:   0 items, 0 bytes.
            Total:  44 items, 42,613,970 bytes.

Emptying Recycle Bin: ALL
    Recycle Bin C:   0 items, 0 bytes.
    Recycle Bin D:   0 items, 0 bytes.
            Total:   0 items, 0 bytes.

It also has many more uses and options (output listed is from /?).

Recycle all files and folders in C:\TEMP:
  RECYCLE C:\TEMP\*

List all DOC files which were recycled from any directory on the C: drive:
  RECYCLE /L C:\*.DOC

Restore all DOC files which were recycled from any directory on the C: drive:
  RECYCLE /U C:\*.DOC

Restore C:\temp\junk.txt to C:\docs\resume.txt:
  RECYCLE /U "C:\temp\junk.txt" "C:\docs\resume.txt"

Rename in place C:\etc\config.cfg to C:\archive\config.2007.cfg:
  RECYCLE /R "C:\etc\config.cfg" "C:\archive\config.2007.cfg"

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

Regex to match URL end-of-line or "/" character

You've got a couple regexes now which will do what you want, so that's adequately covered.

What hasn't been mentioned is why your attempt won't work: Inside a character class, $ (as well as ^, ., and /) has no special meaning, so [/$] matches either a literal / or a literal $ rather than terminating the regex (/) or matching end-of-line ($).

Only read selected columns

The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

Column selection (col_select)

The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().

Select columns by name
data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr  [ 4]: carrier, tailnum, origin, dest
#> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
#>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
#>  1 N142…  2013     1     1      517            515         2      830
#>  2 N242…  2013     1     1      533            529         4      850
#>  3 N619…  2013     1     1      542            540         2      923
#>  4 N804…  2013     1     1      544            545        -1     1004
#>  5 N668…  2013     1     1      554            600        -6      812
#>  6 N394…  2013     1     1      554            558        -4      740
#>  7 N516…  2013     1     1      555            600        -5      913
#>  8 N829…  2013     1     1      557            600        -3      709
#>  9 N593…  2013     1     1      557            600        -3      838
#> 10 N3AL…  2013     1     1      558            600        -2      753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> #   time_hour <dttm>

Uncaught ReferenceError: function is not defined with onclick

I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()" to @click="someFunction" and now they are working.

Can't run Curl command inside my Docker Container

If you are using an Alpine based image, you have to

RUN
... \
apk add --no-cache curl \
curl ...
...

How to hide Android soft keyboard on EditText

Hello Use this code it is working 100% for me

EditText ee=new EditText(this);
ee.setShowSoftInputOnFocus(false);

*But you want to just hide keyboard on edittext click given below code will work but keyboard icon and upward sign of back-button will create *Given code is like this

        EditText ee=new EditText(this);//create edittext
        final   View.OnTouchListener disable =new View.OnTouchListener() {
        public boolean onTouch (View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager img = 
        (InputMethodManager)v.getContext().getSystemService(INPUT_METHOD_SERVICE);
        if (img != null) {
        img.hideSoftInputFromWindow(v.getWindowToken(),0);
        }
        return true;
        }
        };
        //call touch listener
       ee.setOnTouchListener(disable);

Use also it in case of text-changing listener

        EditText ee= new EditText(this);
        Text=new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int 
        after) {
        InputMethodManager img = (InputMethodManager) 
        getSystemService(INPUT_METHOD_SERVICE);
        img.hideSoftInputFromWindow(ee.getWindowToken(), 0);

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        InputMethodManager img = (InputMethodManager) 
        getSystemService(INPUT_METHOD_SERVICE);
        img.hideSoftInputFromWindow(ee.getWindowToken(), 0);

        }
       @Override
        public void afterTextChanged(Editable s) {
        InputMethodManager img = (InputMethodManager) 
        getSystemService(INPUT_METHOD_SERVICE);
        img.hideSoftInputFromWindow(ee.getWindowToken(), 0);

        }
        };
       ee.addTextChangedListener(Text);

Use it also in case of onclick listener

 EditText ee=new EditText(this);
 ee.setOnClickListener(new View.OnClickListener() {
 public void onClick(View v) {

 InputMethodManager img= (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
 img.hideSoftInputFromWindow(ee.getWindowToken(),0);

 }});

All the code will work but for me first code is best

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

Autowiring two beans implementing same interface - how to set default bean to autowire?

I'd suggest marking the Hibernate DAO class with @Primary, i.e. (assuming you used @Repository on HibernateDeviceDao):

@Primary
@Repository
public class HibernateDeviceDao implements DeviceDao

This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.

Also, rather than using @Autowired @Qualifier, I find it more elegant to use @Resource for picking specific beans, i.e.

@Resource(name="jdbcDeviceDao")
DeviceDao deviceDao;

Remove 'standalone="yes"' from generated XML

If you have <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

but want this: <?xml version="1.0" encoding="UTF-8"?>

Just do:

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

Do I use <img>, <object>, or <embed> for SVG files?

I can recommend the SVG Primer (published by the W3C), which covers this topic: http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML

If you use <object> then you get raster fallback for free*:

<object data="your.svg" type="image/svg+xml">
  <img src="yourfallback.jpg" />
</object>

*) Well, not quite for free, because some browsers download both resources, see Larry's suggestion below for how to get around that.

2014 update:

  • If you want a non-interactive svg, use <img> with script fallbacks to png version (for older IE and android < 3). One clean and simple way to do that:

    <img src="your.svg" onerror="this.src='your.png'">.

    This will behave much like a GIF image, and if your browser supports declarative animations (SMIL) then those will play.

  • If you want an interactive svg, use either <iframe> or <object>.

  • If you need to provide older browsers the ability to use an svg plugin, then use <embed>.

  • For svg in css background-image and similar properties, modernizr is one choice for switching to fallback images, another is depending on multiple backgrounds to do it automatically:

    div {
        background-image: url(fallback.png);
        background-image: url(your.svg), none;
    }
    

    Note: the multiple backgrounds strategy doesn't work on Android 2.3 because it supports multiple backgrounds but not svg.

An additional good read is this blogpost on svg fallbacks.

Filtering a spark dataframe based on date

We can also use SQL kind of expression inside filter :


Note -> Here I am showing two conditions and a date range for future reference :


ordersDf.filter("order_status = 'PENDING_PAYMENT' AND order_date BETWEEN '2013-07-01' AND '2013-07-31' ")

C++ passing an array pointer as a function argument

This is another method . Passing array as a pointer to the function
void generateArray(int *array,  int size) {
    srand(time(0));
    for (int j=0;j<size;j++)
        array[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

Overlay with spinner

Here is simple overlay div without using any gif, This can be applied over another div.

<style>
.loader {
  position: relative;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  left:50%;
  top:50%;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}
#overlay{
    position: absolute;
    top:0px;
    left:0px;
    width: 100%;
    height: 100%;
    background: black;
    opacity: .5;
}
.container{
    position:relative;
    height: 300px;
    width: 200px;
    border:1px solid
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<h2>How To Create A Loader</h2>

<div class="container">
  <h3>Overlay over this div</h3>
  <div id="overlay">
      <div class="loader"></div>
  </div>
<div>

Indent starting from the second line of a paragraph with CSS

Make left-margin: 2em or so will push the whole text including first line to right 2em. Than add text-indent (applicable to first line) as -2em or so.. This brings first line back to start without margin. I tried it for list tags

<style>
    ul li{
      margin-left: 2em;
      text-indent: -2em;
    }
</style>

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How to find the mime type of a file in python?

You didn't state what web server you were using, but Apache has a nice little module called Mime Magic which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as Dave Webb Mentioned the MimeTypes Module under python will work, provided an extension is handy.

Alternatively, if you are sitting on a UNIX box you can use sys.popen('file -i ' + fileName, mode='r') to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.

console.writeline and System.out.println

First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example I have just implemented.

import java.io.Console;


public class TestConsole {
    public static void main(String[] args) {
        Console console = System.console();
        System.out.println("console=" + console);
        console.writer().println("hello from console");
    }
}

When I ran the application from command prompt I got the following:

$ java TestConsole
console=java.io.Console@93dcd
hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
        at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null

I hope my explanations help.

Angular 2 Unit Tests: Cannot find name 'describe'

npm install @types/jasmine

As mentioned in some comments the "types": ["jasmine"] is not needed anymore, all @types packages are automatically included in compilation (since v2.1 I think).

In my opinion the easiest solution is to exclude the test files in your tsconfig.json like:

"exclude": [
    "node_modules",
    "**/*.spec.ts"
]

This works for me.

Further information in the official tsconfig docs.

Inserting a string into a list without getting split into characters

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

Form Validation With Bootstrap (jQuery)

You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation

They use JQuery validation.

jquery.validate.js

jquery.validate.min.js

jquery-1.7.1.min.js

enter image description here

And you'll get the source code there.

 <form id="registration-form" class="form-horizontal">
 <h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
 <div class="form-control-group">
        <label class="control-label" for="name">Your Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="name" id="name"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">User Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="username" id="username"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">Password</label>
 <div class="controls">
          <input type="password" class="input-xlarge" name="password" id="password">

</div>
</div>
<div class="form-control-group">
            <label class="control-label" for="name"> Retype Password</label>
<div class="controls">
              <input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="email">Email Address</label>
<div class="controls">
              <input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message">Your Address</label>
<div class="controls">
              <textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
             <input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
            <button type="submit" class="btn btn-success btn-large">Register</button>
            <button type="reset" class="btn">Cancel</button></div>
</form>

And The JQuery :

<script src="assets/js/jquery-1.7.1.min.js"></script>

<script src="assets/js/jquery.validate.js"></script>

<script src="script.js"></script>
<script>
            addEventListener('load', prettyPrint, false);
            $(document).ready(function(){
            $('pre').addClass('prettyprint linenums');
                  });

Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/

Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/

happy coding.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

This code worked for me

public static void main(String[] args) {
    try {
        java.net.URL myUr = new java.net.URL("http://path");
        System.out.println("Instantiated new URL: " + connection_url);
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

Instantiated new URL: http://path

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

Extracting just Month and Year separately from Pandas Datetime column

If you want the month year unique pair, using apply is pretty sleek.

df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y')) 

Outputs month-year in one column.

Don't forget to first change the format to date-time before, I generally forget.

df['date_column'] = pd.to_datetime(df['date_column'])

Check if value is in select list with JQuery

_x000D_
_x000D_
if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){_x000D_
//do stuff_x000D_
}
_x000D_
_x000D_
_x000D_

ToList().ForEach in Linq

Try with this combination of Lambda expressions:

employees.ToList().ForEach(emp => 
{
    collection.AddRange(emp.Departments);
    emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);                    
});

Removing first x characters from string?

Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:

s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum

Send POST data using XMLHttpRequest

NO PLUGINS NEEDED!

Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :

enter image description here

javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);

That's all! Now you can visit any website, and click that button in BOOKMARK BAR!


NOTE:

The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:

 javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) {   var xForm= document.createElement("form");   xForm.setAttribute("method", "post");   xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank");   for(var key in params) {   if(params.hasOwnProperty(key)) {        var hiddenField = document.createElement("input");      hiddenField.setAttribute("name", key);      hiddenField.setAttribute("value", params[key]);         xForm.appendChild(hiddenField);     }   }   document.body.appendChild(xForm);  xForm.submit(); }   parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0); 

How to count the NaN values in a column in pandas DataFrame

if you are using Jupyter Notebook, How about....

 %%timeit
 df.isnull().any().any()

or

 %timeit 
 df.isnull().values.sum()

or, are there anywhere NaNs in the data, if yes, where?

 df.isnull().any()

How to remove folders with a certain name

This command works for me. It does its work recursively

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

. - current folder

"node_modules" - folder name

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

cleanup php session files

# Every 30 minutes, not on the hour<br>
# Grabs maxlifetime directly from \`php -i\`<br>
# doesn't care if /var/lib/php5 exists, errs go to /dev/null<br>

09,39 * * * *   find /var/lib/php5/ -type f -cmin +$(echo "\`php -i|grep -i session.gc_maxlifetime|cut -d' ' -f3\` / 60" | bc) -exec rm -f {} \\; >/dev/null 2>&1

The Breakdown: Only files: find /var/lib/php5/ -type f
Older than minutes: -cmin
Get php settings: $(echo "`php -i|grep -i session.gc_maxlifetime
Do the math: |cut -d' ' -f3` / 60" | bc)
RM matching files: -exec rm -f {} \;

How to delete Tkinter widgets from a window?

You simply use the destroy() method to delete the specified widgets like this:

lbl = tk.Label(....)

btn = tk.Button(....., command=lambda: lbl.destroy())

Using this you can completely destroy the specific widgets.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

I had the same issue and deleting the store and reading didn't work. I had to do the following.

  • Get a copy of OpenSSL. It is available for Windows. Or use a Linux box as they all pretty much all have it.

  • Run the following to export to a key file:

    openssl pkcs12 -in certfile.pfx -out backupcertfile.key
    
    openssl pkcs12 -export -out certfiletosignwith.pfx -keysig -in backupcertfile.key
    

Then in the project properties you can use the PFX file.

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

Why would an Enum implement an Interface?

When creating constants in a jar file, it is often helpful to let users extend enum values. We used enums for PropertyFile keys and got stuck because nobody could add any new ones! Below would have worked much better.

Given:

public interface Color {
  String fetchName();
}

and:

public class MarkTest {

  public static void main(String[] args) {
    MarkTest.showColor(Colors.BLUE);
    MarkTest.showColor(MyColors.BROWN);
  }

  private static void showColor(Color c) {
    System.out.println(c.fetchName());
  }
}

one could have one enum in the jar:

public enum Colors implements Color {
  BLUE, RED, GREEN;
  @Override
  public String fetchName() {
    return this.name();
  }
}

and a user could extend it to add his own colors:

public enum MyColors implements Color {
  BROWN, GREEN, YELLOW;
  @Override
  public String fetchName() {
    return this.name();
  }
}

disabling spring security in spring boot app

Use security.ignored property:

security.ignored=/**

security.basic.enable: false will just disable some part of the security auto-configurations but your WebSecurityConfig still will be registered.

There is a default security password generated at startup

Try to Autowired the AuthenticationManagerBuilder:

@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }

How to launch jQuery Fancybox on page load?

Its simple:

Make your element hidden first like this:

<div id="hidden" style="display:none;">
    Hi this is hidden
</div>

Then call your javascript:

<script type="text/javascript">
    $(document).ready(function() {
        $.fancybox("#hidden");
    });
</script>

Check out the image below:

enter image description here

Another example:

<div id="example2" style="display:none;">
        <img src="http://theinstitute.ieee.org/img/07tiProductsandServicesiStockphoto-1311258460873.jpg" />
    </div>

 <script type="text/javascript">
        $(document).ready(function() {
            $.fancybox("#example2");
        });
    </script>

enter image description here

ImportError: No module named win32com.client

pip install pywin32 didn't work for me but pypiwin32 did.

Initialize/reset struct to zero/null

I believe you can just assign the empty set ({}) to your variable.

struct x instance;

for(i = 0; i < n; i++) {
    instance = {};
    /* Do Calculations */
}

Rails 4 - Strong Parameters - Nested Objects

As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be

Update as suggested by @RafaelOliveira

params.require(:measurement)
      .permit(:name, :groundtruth => [:type, :coordinates => []])

On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this

params.require(:foo).permit(:bar, {:baz => [:x, :y]})


Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

For further clarification, you could look at the implementation of permit and strong_parameters itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

Ansible: filter a list by its attributes

Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:

- debug:
    msg: "{% for address in network.addresses.private_man %}\
        {% if address.type == 'fixed' %}\
          {{ address.addr }}\
        {% endif %}\
      {% endfor %}"

Or if you prefer to put it all on one line:

- debug:
    msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"

Which returns:

ok: [localhost] => {
    "msg": "172.16.1.100"
}

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

Form Submit jQuery does not work

Don't forget to close your form with a </form>. That stopped submit() working for me.

Python: Ignore 'Incorrect padding' error when base64 decoding

If there's a padding error it probably means your string is corrupted; base64-encoded strings should have a multiple of four length. You can try adding the padding character (=) yourself to make the string a multiple of four, but it should already have that unless something is wrong

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

iterate through a map in javascript

An answer to your Question from 2019:

It depends on what version of ECMAScript you use.

Pre ES6:

Use any of the answers below, e.g.:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

For ES6 (ES 2015):

You should use a Map object, which has the entries() function:

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

For ES8 (ES 2017):

Object.entries() was introduced:

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

R legend placement in a plot

Edit 2017:

use ggplot and theme(legend.position = ""):

library(ggplot2)
library(reshape2)

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")

Original answer 2012: Put the legend on the bottom:

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

dev.off()

layout(rbind(1,2), heights=c(7,1))  # put legend on bottom 1/8th of the chart

plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')

# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
       col=c('black','black','blue'),ncol=3,bty ="n")

enter image description here

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

How can I join on a stored procedure?

I actually like the previous answer (don't use the SP), but if you're tied to the SP itself for some reason, you could use it to populate a temp table, and then join on the temp table. Note that you're going to cost yourself some additional overhead there, but it's the only way I can think of to use the actual stored proc.

Again, you may be better off in-lining the query from the SP into the original query.

how to use concatenate a fixed string and a variable in Python

I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

Credit card expiration dates - Inclusive or exclusive?

In your example a credit card is expired on 6/2008.

Without knowing what you are doing I cannot say definitively you should not be validating ahead of time but be aware that sometimes business rules defy all logic.

For example, where I used to work they often did not process a card at all or would continue on transaction failure simply so they could contact the customer and get a different card.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Difference between classification and clustering in data mining?

Clustering aims at finding groups in data. “Cluster” is an intuitive concept and does not have a mathematically rigorous definition. The members of one cluster should be similar to one another and dissimilar to the members of other clusters. A clustering algorithm operates on an unlabeled data set Z and produces a partition on it.

For Classes and Class Labels, class contains similar objects, whereas objects from different classes are dissimilar. Some classes have a clear-cut meaning, and in the simplest case are mutually exclusive. For example, in signature verification, the signature is either genuine or forged. The true class is one of the two, no matter that we might not be able to guess correctly from the observation of a particular signature.

How to open a file for both reading and writing?

I have tried something like this and it works as expected:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

Where:

f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.

And:

f.write(string) writes the contents of string to the file, returning None.

Also if you open Python tutorial about reading and writing files you will find that:

'r+' opens the file for both reading and writing.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I got this error and i fixed the issue with iconv function like following:

iconv('latin5', 'utf-8', $data['index']);

PHP function to get the subdomain of a URL

this is my solution, it works with the most common domains, you can fit the array of extensions as you need:

$SubDomain = explode('.', explode('|ext|', str_replace(array('.com', '.net', '.org'), '|ext|',$_SERVER['HTTP_HOST']))[0]);

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

There is probably another table with a foreign key referencing the primary key you are trying to change.

To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section.

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

How do I use JDK 7 on Mac OSX?

I updated to Yosemite and Android Studio wouldn't clean my projects or Run them on virtual or real device because of the following error:

Failed to complete Gradle execution.Cause:Supplied javaHome is not a valid folder. You supplied: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

After some research and trouble shooting, I found that the JDK file that was being pointed to at "/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home" wasn't there; all of "JavaVirtualMachines/1.6.0.jdk/Contents/Home" was missing from "/System/Library/Java". So, I copied "JavaVirtualMachines/1.6.0.jdk/Contents/Home" over from "/Library/Java/" to "/System/Library/Java/" and cha ching! I was back in business.

Sorting HashMap by values

package SortedSet;

import java.util.*;

public class HashMapValueSort {
public static void main(String[] args){
    final Map<Integer, String> map = new HashMap<Integer,String>();
    map.put(4,"Mango");
    map.put(3,"Apple");
    map.put(5,"Orange");
    map.put(8,"Fruits");
    map.put(23,"Vegetables");
    map.put(1,"Zebra");
    map.put(5,"Yellow");
    System.out.println(map);
    final HashMapValueSort sort = new HashMapValueSort();
    final Set<Map.Entry<Integer, String>> entry = map.entrySet();
    final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            String value1 = o1.getValue();
            String value2 = o2.getValue();
            return value1.compareTo(value2);
        }
    };
    final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
    sortedSet.addAll(entry);
    final Map<Integer,String> sortedMap =  new LinkedHashMap<Integer, String>();
    for(Map.Entry<Integer, String> entry1 : sortedSet ){
        sortedMap.put(entry1.getKey(),entry1.getValue());
    }
    System.out.println(sortedMap);
}
}

In a Git repository, how to properly rename a directory?

I solved it in two steps. To rename folder using mv command you need rights to do so, if you don't have right you can follow these steps. Suppose you want to rename casesensitive to Casesensitive.

Step 1: Rename the folder (casesensitive) to something else from explorer. eg Rename casesensitive to folder1 commit this change.

Step 2: Rename this newly named folder(folder1) to the expected case sensitive name (Casesensitive ) eg. Rename folder1 to Casesensitive. Commit this change.

What is the worst real-world macros/pre-processor abuse you've ever come across?

The worst one I saw was the non-use :-)

Someone wrote a strcpy (I think that was it... over 10 years ago now) function inside of a method (because they didn't want the overhead of calling strcpy... sigh).

They clued in that it wouldn't work for Japanese characters so they added an "if" at the start to do ASCII or Unicode. At that point the code was about a screen long... likely killing cache coherency and erasing his supposed savings for the inlining of the code.

The code was identical save for the types (so should have used a macro).

Of course the strcpy that they wrote was much much much slower than the hand tuned assembler one that was in the standard library...

Of course if they had just done it all as a macro it could have been replaced with a call to strcpy...

Of course I quit the company (not directly because of that...)

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

DT[order(-x)] works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x) syntax in keeping with the set* commands like setnames, setkey

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?