Programs & Examples On #Redirecttoroute

Set "Homepage" in Asp.Net MVC

Attribute Routing in MVC 5

Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.

A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Example",
    url: "hey/now",
    defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);

Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,

public class HomeController : Controller
{
    // url is now 'index/' instead of 'home/index'
    [Route("index")]
    public ActionResult Index()
    {
        return View();
    }
    // url is now 'create/new' instead of 'home/create'
    [Route("create/new")]
    public ActionResult Create()
    {
        return View();
    }
}

How can I add spaces between two <input> lines using CSS?

You can format them as table !!

_x000D_
_x000D_
form {_x000D_
  display: table;_x000D_
}_x000D_
label {_x000D_
  display: table-row;_x000D_
}_x000D_
input {_x000D_
  display: table-cell;_x000D_
}_x000D_
p1 {_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div id="header_order_form" align="center">_x000D_
  <form id="order_header" method="post">_x000D_
    <label>_x000D_
      <p1>order_no:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>order_type:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
    <label>_x000D_
      <p1>_x000D_
        creation_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>delivery_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>billing_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
_x000D_
    <label>_x000D_
      <p1>sold_to_party:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>sop_address:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to overwrite css style

Using !important is not recommended but in this situation I think you should -

Write this in your internal CSS -

.flex-control-thumbs li {
  width: auto !important;
  float: none !important;
}

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

Find all packages installed with easy_install/pip?

pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.

How to COUNT rows within EntityFramework without loading contents?

Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.

   int count;

    using (var db = new MyDatabase()){
      string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";

      object[] myParams = {1};
      var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);

      count = cntQuery.First<int>();
    }

PHPExcel auto size column width

// Auto-size columns for all worksheets
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    foreach ($worksheet->getColumnIterator() as $column) {
        $worksheet
            ->getColumnDimension($column->getColumnIndex())
            ->setAutoSize(true);
    } 
}

"Thinking in AngularJS" if I have a jQuery background?

Listen to the podcast JavaScript Jabber: Episode #32 that features the original creators of AngularJS: Misko Hevery & Igor Minar. They talk a lot about what it's like to come to AngularJS from other JavaScript backgrounds, especially jQuery.

One of the points made in the podcast made a lot of things click for me with respects to your question:

MISKO: [...] one of the things we thought about very hardly in Angular is, how do we provide lots of escape hatches so that you can get out and basically figure out a way out of this. So to us, the answer is this thing called “Directives”. And with directives, you essentially become a regular little jQuery JavaScript, you can do whatever you want.

IGOR: So think of directive as the instruction to the compiler that tells it whenever you come across this certain element or this CSS in the template, and you keep this kind of code and that code is in charge of the element and everything below that element in the DOM tree.

A transcript of the entire episode is available at the link provided above.

So, to directly answer your question: AngularJS is -very- opinionated and is a true MV* framework. However, you can still do all of the really cool stuff you know and love with jQuery inside of directives. It's not a matter of "How do I do what I used to in jQuery?" as much as it's a matter of "How do I supplement AngularJS with all of the stuff I used to do in jQuery?"

It's really two very different states of mind.

How do I 'svn add' all unversioned files to SVN?

You can use command

svn add * force--

or

svn add <directory/file name>

If your files/directories are not adding recursively. Then check this.

Recursive adding is default property. You can see in SVN book.

Issue can be in your ignore list or global properties.

I got solution google issue tracker

Check global properties for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Properties.
  • See if you don't have a property svn:global-ignores with a value of *
  • If you have property with star(*) then it will ignore recursive adding. So remove this property.

Check global ignore pattern for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Settings > General.
  • See in Global Ignore Pattern, if you don't have set star(*) there.
  • If you found star(*), remove this property.

This guy also explained why this property added in my project.

The most like way that it got there is that someone right-clicked a file without any extension and selected TortoiseSVN -> SVN Ignore -> * (recursively), and then committed this.

You can check the log to see who committed that property change, find out what they were actually trying to do, and ask them to be more careful in future. :)

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

How to get all selected values of a multiple select box?

Check-it Out:

HTML:

<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server"  SelectionMode="Multiple" Width="100px">
    <asp:ListItem Text="Raj" Value="1"></asp:ListItem>
    <asp:ListItem Text="Karan" Value="2"></asp:ListItem>
    <asp:ListItem Text="Riya" Value="3"></asp:ListItem>
    <asp:ListItem Text="Aman" Value="4"></asp:ListItem>
    <asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>

JQUERY:

$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});

CLICK HERE TO SEE THE DEMO

WaitAll vs WhenAll

While JonSkeet's answer explains the difference in a typically excellent way there is another difference: exception handling.

Task.WaitAll throws an AggregateException when any of the tasks throws and you can examine all thrown exceptions. The await in await Task.WhenAll unwraps the AggregateException and 'returns' only the first exception.

When the program below executes with await Task.WhenAll(taskArray) the output is as follows.

19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.

When the program below is executed with Task.WaitAll(taskArray) the output is as follows.

19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.

The program:

class MyAmazingProgram
{
    public class CustomException : Exception
    {
        public CustomException(String message) : base(message)
        { }
    }

    static void WaitAndThrow(int id, int waitInMs)
    {
        Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");

        Thread.Sleep(waitInMs);
        throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
    }

    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await MyAmazingMethodAsync();
        }).Wait();

    }

    static async Task MyAmazingMethodAsync()
    {
        try
        {
            Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };

            Task.WaitAll(taskArray);
            //await Task.WhenAll(taskArray);
            Console.WriteLine("This isn't going to happen");
        }
        catch (AggregateException ex)
        {
            foreach (var inner in ex.InnerExceptions)
            {
                Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
        }
        Console.WriteLine("Done.");
        Console.ReadLine();
    }
}

Can't bind to 'routerLink' since it isn't a known property

You are missing either the inclusion of the route package, or including the router module in your main app module.

Make sure your package.json has this:

"@angular/router": "^3.3.1"

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent}
        ])
    ],

Update:

Move the AppRoutingModule to be first in the imports:

imports: [
    AppRoutingModule.
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(), // What is this?
    LayoutModule,
    UsersModule
  ],

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
  OPEN v_refcur FOR 'select * from dummy_table';
END;

SET autoprint on;

--calling the procedure
VAR vcur refcursor;
DECLARE 
BEGIN
  sps_detail_dtest(vrefcur=>:vcur);
END;

Hope this gives you an alternate solution

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Figuring out whether a number is a Double in Java

Since this is the first question from Google I'll add the JavaScript style typeof alternative here as well:

myObject.getClass().getName() // String

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

How do I collapse a table row in Bootstrap?


problem is that the collapse item (div) is nested in the table elements. The div is hidden, the tr and td of the table are still visible and some css-styles are applied to them (border and padding).
Why are you using tables? Is there a reason for? When you dont´t have to use them, dont´use them :-)

Get values from other sheet using VBA

That will be (for you very specific example)

ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value=someval

OR

someVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

So get a F1 click and read about Worksheets collection, which contains Worksheet objects, which in turn has a Cells collection, holding Cell objects...

How do I move files in node.js?

With the help of below URL, you can either copy or move your file CURRENT Source to Destination Source

https://coursesweb.net/nodejs/move-copy-file

_x000D_
_x000D_
/*********Moves the $file to $dir2 Start *********/_x000D_
var moveFile = (file, dir2)=>{_x000D_
  //include the fs, path modules_x000D_
  var fs = require('fs');_x000D_
  var path = require('path');_x000D_
_x000D_
  //gets file name and adds it to dir2_x000D_
  var f = path.basename(file);_x000D_
  var dest = path.resolve(dir2, f);_x000D_
_x000D_
  fs.rename(file, dest, (err)=>{_x000D_
    if(err) throw err;_x000D_
    else console.log('Successfully moved');_x000D_
  });_x000D_
};_x000D_
_x000D_
//move file1.htm from 'test/' to 'test/dir_1/'_x000D_
moveFile('./test/file1.htm', './test/dir_1/');_x000D_
/*********Moves the $file to $dir2 END *********/_x000D_
_x000D_
/*********copy the $file to $dir2 Start *********/_x000D_
var copyFile = (file, dir2)=>{_x000D_
  //include the fs, path modules_x000D_
  var fs = require('fs');_x000D_
  var path = require('path');_x000D_
_x000D_
  //gets file name and adds it to dir2_x000D_
  var f = path.basename(file);_x000D_
  var source = fs.createReadStream(file);_x000D_
  var dest = fs.createWriteStream(path.resolve(dir2, f));_x000D_
_x000D_
  source.pipe(dest);_x000D_
  source.on('end', function() { console.log('Succesfully copied'); });_x000D_
  source.on('error', function(err) { console.log(err); });_x000D_
};_x000D_
_x000D_
//example, copy file1.htm from 'test/dir_1/' to 'test/'_x000D_
copyFile('./test/dir_1/file1.htm', './test/');_x000D_
/*********copy the $file to $dir2 END *********/
_x000D_
_x000D_
_x000D_

Javascript/Jquery Convert string to array

check this out :)

var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
alert(traingIds);  // alerts [1,2]
var type = typeof(traingIds);
alert(type);   // // alerts String

//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds);  // alerts 1,2        
var trainindIdArray = traingIds.split(',');

?for(i = 0; i< trainindIdArray.length; i++){
    alert(trainindIdArray[i]); //outputs individual numbers in array
    }? 

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Should I URL-encode POST data?

Above posts answers questions related to URL Encoding and How it works, but the original questions was "Should I URL-encode POST data?" which isn't answered.

From my recent experience with URL Encoding, I would like to extend the question further. "Should I URL-encode POST data, same as GET HTTP method. Generally, HTML Forms over the Browser if are filled, submitted and/or GET some information, Browsers will do URL Encoding but If an application exposes a web-service and expects Consumers to do URL-Encoding on data, is it Architecturally and Technically correct to do URL Encode with POST HTTP method ?"

Why does dividing two int not yield the right value when assigned to double?

This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.

When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).

In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).

If you'd like to keep the result as a double you're going to want to create a situation where you have double var = double result

The easiest way to do that is to force the expression on the right side of an equation to cast to double:

c = a/(double)b

Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).

After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.

AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

The Role Manager feature has not been enabled

You can do this by reading from the boolean property at:

System.Web.Security.Roles.Enabled

This is a direct read from the enabled attribute of the roleManager element in the web.config:

<configuration>
  <system.web>
    <roleManager enabled="true" />
  </system.web>
</configuration>


Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

How do you do a deep copy of an object in .NET?

The MSDN documentation seems to hint that Clone should perform a deep copy, but it is never explicitly stated:

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberWiseClone… The MemberwiseClone method creates a shallow copy…

You can find my post helpful.

http://pragmaticcoding.com/index.php/cloning-objects-in-c/

C# Version Of SQL LIKE

As aready proposed in this answer and this other answer Microsoft.VisualBasic.CompilerServices.Operators.LikeString could be a good option for simple tasks, when a RegExp is overkill. Syntax is different from RegExp and SQL LIKE operator, but it's really simple to learn (mainly because it's also very limited).

Assembly Microsoft.VisualBasic must be added as a reference to the project to use this method.

For more information see Operators.LikeString Method and for a description of the syntax see Like Operator (Visual Basic).

It can be used as an extension method to String class:

/// <summary>
/// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
/// </summary>
/// <param name="thisString"></param>
/// <param name="pattern"> ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)</param>
/// <returns>true if the string matches the pattern</returns>
public static bool Like(this string thisString, string pattern)
    => Microsoft.VisualBasic.CompilerServices.Operators
        .LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);

ASP.NET Core configuration for .NET Core console application

You can use this code snippet. It includes Configuration and DI.

public class Program
{
    public static ILoggerFactory LoggerFactory;
    public static IConfigurationRoot Configuration;

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;

        string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        if (String.IsNullOrWhiteSpace(environment))
            throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");

        Console.WriteLine("Environment: {0}", environment);

        var services = new ServiceCollection();

        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
            .AddJsonFile("appsettings.json", optional: true);
        if (environment == "Development")
        {

            builder
                .AddJsonFile(
                    Path.Combine(AppContext.BaseDirectory, string.Format("..{0}..{0}..{0}", Path.DirectorySeparatorChar), $"appsettings.{environment}.json"),
                    optional: true
                );
        }
        else
        {
            builder
                .AddJsonFile($"appsettings.{environment}.json", optional: false);
        }

        Configuration = builder.Build();

        LoggerFactory = new LoggerFactory()
            .AddConsole(Configuration.GetSection("Logging"))
            .AddDebug();

        services
            .AddEntityFrameworkNpgsql()
            .AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString), ServiceLifetime.Transient);

        services.AddTransient<IPackageFileService, PackageFileServiceImpl>();

        var serviceProvider = services.BuildServiceProvider();

        var packageFileService = serviceProvider.GetRequiredService<IPackageFileService>();

        ............
    }
}

Oh, and don't forget to add in the project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "copyToOutput": {
      "includeFiles": [
        "appsettings.json",
        "appsettings.Integration.json",
        "appsettings.Production.json",
        "appsettings.Staging.json"
      ]
    }
  },

  "publishOptions": {
    "copyToOutput": [
      "appsettings.json",
      "appsettings.Integration.json",
      "appsettings.Production.json",
      "appsettings.Staging.json"
    ]
  },
...
}

How to watch for form changes in Angular

UPD. The answer and demo are updated to align with latest Angular.


You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges property which is an Observerable instance:

this.form.valueChanges.subscribe(data => console.log('Form changes', data));

In this case you would need to construct form manually using FormBuilder. Something like this:

export class App {
  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })

    this.form.valueChanges.subscribe(data => {
      console.log('Form changes', data)
      this.output = data
    })
  }
}

Check out valueChanges in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview

git pull while not in a git directory

Using combination pushd, git pull and popd, we can achieve this functionality:

pushd <path-to-git-repo> && git pull && popd

For example:

pushd "E:\Fake Directory\gitrepo" && git pull && popd

How do I write a bash script to restart a process if it dies?

I use this for my npm Process

#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

How does the ARM architecture differ from x86?

ARM is a RISC (Reduced Instruction Set Computing) architecture while x86 is a CISC (Complex Instruction Set Computing) one.

The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.

So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.

About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86 isn't specially designed to work with a keyboard neither ARM for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.

If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:

An ARM processor is a Reduced Instruction Set Computer (RISC) processor.

Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).

RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.

ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.

An example comparing instruction set architecture:

For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86

repe cmpsb         /* repeat while equal compare string bytewise */

while on ARM shortest form might look like (without error checking etc.)

top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2    /* subtract r2 from r3 and put result into r2      */
beq  top           /* branch(/jump) if result is zero                 */

which should give you a hint on how RISC and CISC instruction sets differ in complexity.

Origin null is not allowed by Access-Control-Allow-Origin

Origin null is the local file system, so that suggests that you're loading the HTML page that does the load call via a file:/// URL (e.g., just double-clicking it in a local file browser or similar). Different browsers take different approaches to applying the Same Origin Policy to local files.

My guess is that you're seeing this using Chrome. Chrome's rules for applying the SOP to local files are very tight, it disallows even loading files from the same directory as the document. So does Opera. Some other browsers, such as Firefox, allow limited access to local files. But basically, using ajax with local resources isn't going to work cross-browser.

If you're just testing something locally that you'll really be deploying to the web, rather than use local files, install a simple web server and test via http:// URLs instead. That gives you a much more accurate security picture.

How to automatically close cmd window after batch file execution?

This works for me

cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"

start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"

exit

Add a new element to an array without specifying the index in Bash

$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest

C/C++ check if one bit is set in, i.e. int variable

Yeah, I know I don't "have" to do it this way. But I usually write:

    /* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }

template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }

E.g.:

IsBitSet( foo, BIT(3) | BIT(6) );  // Checks if Bit 3 OR 6 is set.

Amongst other things, this approach:

  • Accommodates 8/16/32/64 bit integers.
  • Detects IsBitSet(int32,int64) calls without my knowledge & consent.
  • Inlined Template, so no function calling overhead.
  • const& references, so nothing needs to be duplicated/copied. And we are guaranteed that the compiler will pick up any typo's that attempt to change the arguments.
  • 0!= makes the code more clear & obvious. The primary point to writing code is always to communicate clearly and efficiently with other programmers, including those of lesser skill.
  • While not applicable to this particular case... In general, templated functions avoid the issue of evaluating arguments multiple times. A known problem with some #define macros.
    E.g.: #define ABS(X) (((X)<0) ? - (X) : (X))
          ABS(i++);

Multiple argument IF statement - T-SQL

Not sure what the problem is, this seems to work just fine?

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        Select 'This works just fine' as Msg
    END
Else
    BEGIN
    Select 'No Lol' as Msg
    END

Check if value exists in the array (AngularJS)

U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {
                arr.splice(arr.pop(item));

            } });

        submitFields.push({"field":field,"value":value});
    };

How to write ternary operator condition in jQuery?

I'd do (added caching):

var bbx = $("#blackbox");
 bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')

wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/

I had to change the first operator as css() returns the rgb value of the color

AWS EFS vs EBS vs S3 (differences & when to use?)

Amazon EBS provides block level storage - It is used to create a filesystem on it and store files. Amazon EFS - its shared storage system similar like NAS/SAN. You need to mount it to unix server and use it. Amazon S3 - It is object based storage where each item is stored with a http URL.

One of the difference is - EBS can be attached to 1 instance at a time and EFS can be attached to multiple instances that why shared storage. S2 plain object storage cannot be mounted.

Python's time.clock() vs. time.time() accuracy?

As others have noted time.clock() is deprecated in favour of time.perf_counter() or time.process_time(), but Python 3.7 introduces nanosecond resolution timing with time.perf_counter_ns(), time.process_time_ns(), and time.time_ns(), along with 3 other functions.

These 6 new nansecond resolution functions are detailed in PEP 564:

time.clock_gettime_ns(clock_id)

time.clock_settime_ns(clock_id, time:int)

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

These functions are similar to the version without the _ns suffix, but return a number of nanoseconds as a Python int.

As others have also noted, use the timeit module to time functions and small code snippets.

MySQL: Can't create table (errno: 150)

In my case. I had problems with engine and charset because my Hosting server change settings and my new tables was MyISAM but my old tables are InnoDB. Just i changed.

How to split a dos path into its components in Python

re.split() can help a little more then string.split()

import re    
var = "d:\stuff\morestuff\furtherdown\THEFILE.txt"
re.split( r'[\\/]', var )
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

If you also want to support Linux and Mac paths, just add filter(None,result), so it will remove the unwanted '' from the split() since their paths starts with '/' or '//'. for example '//mount/...' or '/var/tmp/'

import re    
var = "/var/stuff/morestuff/furtherdown/THEFILE.txt"
result = re.split( r'[\\/]', var )
filter( None, result )
['var', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

how to pass parameter from @Url.Action to controller function

you can pass it this way :

Url.Action("CreatePerson", "Person", new RouteValueDictionary(new { id = id }));

OR can also pass this way

Url.Action("CreatePerson", "Person", new { id = id });

How to draw circle in html page?

As of 2015, you can make it and center the text with as few as 15 lines of CSS (Fiddle):

_x000D_
_x000D_
body {_x000D_
  background-color: #fff;_x000D_
}_x000D_
#circle {_x000D_
  position: relative;_x000D_
  background-color: #09f;_x000D_
  margin: 20px auto;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 200px;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  color: #fff;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <title>circle with text</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="circle">_x000D_
    <div id="text">Text in the circle</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Without any -webkit-s, this works on IE11, Firefox, Chrome and Opera, and it is valid HTML5 (experimental) and CSS3.

Same on MS Edge (2020).

Right align text in android TextView

Make sure that you are not using android:layout_width="wrap_content" if so then it won't be able to set the gravity because you are not having enough space for the text to align. Instead use android:layout_width="fill_parent"

Copying a local file from Windows to a remote server using scp

If your drive letter is C, you should be able to use

scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile

without drive letter and backslashes instead of forward slashes.

You are using putty, so you can use pscp. It is better adapted to Windows.

Delete all lines starting with # or ; in Notepad++

As others have noted, in Notepad++ 6.0 and later, it is possible to use the "Replace" feature to delete all lines that begin with ";" or "#".

Tao provides a regular expression that serves as a starting point, but it does not account for white-space that may exist before the ";" or "#" character on a given line. For example, lines that begin with ";" or "#" but are "tabbed-in" will not be deleted when using Tao's regular expression, ^(#|;).*\r\n.

Tao's regular expression does not account for the caveat mentioned in BoltClock's answer, either: variances in newline characters across systems.

An improvement is to use ^(\s)*(#|;).*(\r\n|\r|\n)?, which accounts for leading white-space and the newline character variances. Also, the trailing ? handles cases in which the last line of the file begins with # or ;, but does not end with a newline.

For the curious, it is possible to discern which type of newline character is used in a given document (and more than one type may be used): View -> Show Symbol -> Show End of Line.

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

Make sure that there is no input on the Tx/Rx pins. Then it will work.

I can't understand why this JAXB IllegalAnnotationException is thrown

The exception is due to your JAXB (JSR-222) implementation believing that there are two things mapped with the same name (a field and a property). There are a couple of options for your use case:

OPTION #1 - Annotate the Field with @XmlAccessorType(XmlAccessType.FIELD)

If you want to annotation the field then you should specify @XmlAccessorType(XmlAccessType.FIELD)

Fields.java:

package forum10795793;

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {

    @XmlElement(name = "field")
    List<Field> fields = new ArrayList<Field>();

    public List<Field> getFields() {
        return fields;
    }

    public void setFields(List<Field> fields) {
        this.fields = fields;
    }

}

Field.java:

package forum10795793;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

    @XmlAttribute(name = "mappedField")
    String mappedField;

    public String getMappedField() {
        return mappedField;
    }

    public void setMappedField(String mappedField) {
        this.mappedField = mappedField;
    }

}

OPTION #2 - Annotate the Properties

The default accessor type is XmlAccessType.PUBLIC. This means that by default JAXB implementations will map public fields and accessors to XML. Using the default setting you should annotate the public accessors where you want to override the default mapping behaviour.

Fields.java:

package forum10795793;

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "fields")
public class Fields {

    List<Field> fields = new ArrayList<Field>();

    @XmlElement(name = "field")
    public List<Field> getFields() {
        return fields;
    }

    public void setFields(List<Field> fields) {
        this.fields = fields;
    }

}

Field.java:

package forum10795793;

import javax.xml.bind.annotation.*;

public class Field {

    String mappedField;

    @XmlAttribute(name = "mappedField")
    public String getMappedField() {
        return mappedField;
    }

    public void setMappedField(String mappedField) {
        this.mappedField = mappedField;
    }

}

For More Information

How do you automatically set the focus to a textbox when a web page loads?

IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

$(document).ready(function() {
  $('input:text[value=""]:visible:enabled:first').focus();
});

Hope that helps...

Thanks...

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

Can I recover a branch after its deletion in Git?

BIG YES

if you are using GIT follow these simple steps https://confluence.atlassian.com/bbkb/how-to-restore-a-deleted-branch-765757540.html

if you are using smartgit and already push that branch go to origin, find that branch and right click then checkout

What's the idiomatic syntax for prepending to a short python list?

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list.

Android Preventing Double Click On A Button

The Best and simple solution i found is 
1. to create a boolean and set as false (default) like
private boolean itemClicked = false;

/* for a safer side you can also declare boolean false in onCreate() also. */
and at onclick() method check 
2. if(!itemClicked)
{
itemClicked = true;
// rest of your coding functionality goes here of onClick method.
}
3. last step is to set boolean false in onResume()
@override
onResume()
{
super.onResume(0);
itemClicked = false;
}

How to catch curl errors in PHP

    $responseInfo = curl_getinfo($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($response, $header_size);
    $result=array();
    $result['httpCode']=$httpCode;
    $result['body']=json_decode($body);
    $result['responseInfo']=$responseInfo;
    print_r($httpCode); 
     print_r($result['body']); exit;
    curl_close($ch);
    if($httpCode == 403)
    {
        print_r("Access denied");
        exit;
    }   
    else
     {
         //catch more errors 
     }

Aliases in Windows command prompt

If you're just going for some simple commands, you could follow these steps:

  1. Create a folder called C:\Aliases
  2. Add C:\Aliases to your path (so any files in it will be found every time)
  3. Create a .bat file in C:\Aliases for each of the aliases you want

Maybe overkill, but unlike the (otherwise excellent) answer from @Argyll, this solves the problem of this loading every time.

For instance, I have a file called dig2.bat with the following in it:

@echo off
echo.
dig +noall +answer %1

Your np file would just have the following:

@echo off
echo.
notepad++.exe %1

Then just add the C:\Aliases folder to your PATH environment variable. If you have CMD or PowerShell already opened you will need to restart it.

FWIW, I have about 20 aliases (separate .bat files) in my C:\Aliases directory - I just create new ones as necessary. Maybe not the neatest, but it works fine.

UPDATE: Per an excellent suggestion from user @Mav, it's even better to use %* rather than %1, so you can pass multiple files to the command, e.g.:

@echo off
echo.
notepad++.exe %*

That way, you could do this:

np c:\temp\abc.txt c:\temp\def.txt c:\temp\ghi.txt

and it will open all 3 files.

window.onload vs <body onload=""/>

It is a accepted standard to have content, layout and behavior separate. So window.onload() will be more suitable to use than <body onload=""> though both do the same work.

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

You can do the following with Unnamed Columns:

  1. Delete unnamed columns
  2. Rename them (if you want to use them)

file.csv

,A,B,C
0,1,2,3
1,4,5,6
2,7,8,9

#read file df = pd.read_csv('file.csv')

Method 1: Delete Unnamed Columns

# delete one by one like column is 'Unnamed: 0' so use it's name
df.drop('Unnamed: 0', axis=1, inplace=True)

#delete all Unnamed Columns in a single code of line using regex
df.drop(df.filter(regex="Unnamed"),axis=1, inplace=True)

Method 2: Rename Unnamed Columns

df.rename(columns = {'Unnamed: 0':'Name'}, inplace = True)

If you want to write out with a blank header as in the input file, just choose 'Name' above to be ''.

Removing element from array in component state

You can use this function, if you want to remove the element (without index)

removeItem(item) {
  this.setState(prevState => {
    data: prevState.data.filter(i => i !== item)
  });
}

Server configuration is missing in Eclipse

From project explorer ,just make sure that Servers is not closed enter image description here

Can I scale a div's height proportionally to its width using CSS?

You could assign both the width and height of the element using either vw or vh. For example:

#anyElement {
    width: 20vh;
    height: 20vh;
}

This would set both the width and height to 20% of the browser's current height, retaining the aspect ratio. However, this only works if you want to scale proportionate to the viewport dimensions.

How do I read the file content from the Internal storage - Android App

Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

To read data from internal storage you need your app files folder and read content from here

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );

Also you can use this approach

FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}

Preferred way to create a Scala list

ListBuffer is a mutable list which has constant-time append, and constant-time conversion into a List.

List is immutable and has constant-time prepend and linear-time append.

How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.

For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List and do prepends. Whether you'll do so with a tail-recursive function, foldLeft, or something else is not really relevant.

If you get the elements in the same order you use them, then a ListBuffer is most likely a preferable choice, if performance is critical.

But, if you are not on a critical path and the input is low enough, you can always reverse the list later, or just foldRight, or reverse the input, which is linear-time.

What you DON'T do is use a List and append to it. This will give you much worse performance than just prepending and reversing at the end.

Does Java have something like C#'s ref and out keywords?

Java passes parameters by value and doesn't have any mechanism to allow pass-by-reference. That means that whenever a parameter is passed, its value is copied into the stack frame handling the call.

The term value as I use it here needs a little clarification. In Java we have two kinds of variables - primitives and objects. A value of a primitive is the primitive itself, and the value of an object is its reference (and not the state of the object being referenced). Therefore, any change to the value inside the method will only change the copy of the value in the stack, and will not be seen by the caller. For example, there isn't any way to implement a real swap method, that receives two references and swaps them (not their content!).

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Linq Query Group By and Selecting First Items

var result = list.GroupBy(x => x.Category).Select(x => x.First())

How do you perform address validation?

As mentioned there are many services out there, if you are looking to truly validate the entire address then I highly recommend going with a Web Service type service to ensure that changes can quickly be recognized by your application.

In addition to the services listed above, webservice.net has this US Address Validation service. http://www.webservicex.net/WCF/ServiceDetails.aspx?SID=24

How can I exclude multiple folders using Get-ChildItem -exclude?

I wanted a solution that didn't involve looping over every single item and doing ifs. Here's a solution that is just a simple recursive function over Get-ChildItem. We just loop and recurse over directories.


function Get-RecurseItem {
    [Cmdletbinding()]
    param (
        [Parameter(ValueFromPipeline=$true)][string]$Path,
        [string[]]$Exclude = @(),
        [string]$Include = '*'
    )
    Get-ChildItem -Path (Join-Path $Path '*') -Exclude $Exclude -Directory | ForEach-Object {
        @(Get-ChildItem -Path (Join-Path $_ '*') -Include $Include -Exclude $Exclude -File) + ``
        @(Get-RecurseItem -Path $_ -Include $Include -Exclude $Exclude)
    }
}

How can I get the console logs from the iOS Simulator?

You can view the console for the iOS Simulator via desktop Safari. It's similar to the way you use desktop Safari to view the console for physical iOS devices.

Whenever the simulator is running and there's a webpage open, there'll be an option under the Develop menu in desktop safari that lets you see the iOS simulator console:

Develop -> iPhone Simulator -> site name

Image resolution for new iPhone 6 and 6+, @3x support added?

I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.

Create different versions of an image in your asset catalog such that the image itself tells you what version it is:

enter image description here

Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.

The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed: and assigning into an image view.

(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:.)

Windows 7, 64 bit, DLL problems

This contribution does not really answer the initial question, but taking into account the hit-rate of this thread I assume that there are quite a few people dealing with the problem that API-MS-WIN-CORE- libraries cannot be found.

I was able to solve a problem where my application refused to start with the error message that API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL is not found by simply updating Visual Studio.

I don't think that my build environment (Windows 7 Pro SP1, Visual Studio Ultimate 2012) was messed up completely, it worked fine for most of my projects. But under some very specific circumstances I got the error message (see below).

After updating Visual Studio 11 from the initial CD-Version (I forgot to look up the version number) to version 11.0.61030.00 Update 4 also the broken project was running again.

Error message at application startup

jQuery override default validation error message display (Css) Popup/Tooltip like

If you could provide some reason as to why you need to replace the label with a div, that would certainly help...

Also, could you paste a sample that'd be helpful ( http://dpaste.com/ or http://pastebin.com/)

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

Variable is accessed within inner class. Needs to be declared final

You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later.

Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.

I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.

How to display text in pygame?

There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.

Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.

You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

Sort arrays of primitive types in descending order

Your implementation (the one in the question) is faster than e.g. wrapping with toList() and using a comparator-based method. Auto-boxing and running through comparator methods or wrapped Collections objects is far slower than just reversing.

Of course you could write your own sort. That might not be the answer you're looking for, but note that if your comment about "if the array is already sorted quite well" happens frequently, you might do well to choose a sorting algorithm that handles that case well (e.g. insertion) rather than use Arrays.sort() (which is mergesort, or insertion if the number of elements is small).

How can I roll back my last delete command in MySQL?

Rollback normally won't work on these delete functions and surely a backup only can save you.

If there is no backup then there is no way to restore it as delete queries ran on PuTTY,Derby using .sql files are auto committed once you fire the delete query.

How to center text vertically with a large font-awesome icon?

Well, this question was asked years ago. I think technology has changed quite a bit and browser compatibility is much better. You could use vertical-align but I would consider that some what less scaleable and less reusable. I would recommend a flexbox approach.

Here is the same example the original poster used but with flexbox. It styles a single element. If a button size changes for whatever reason, it will continue to be vertically and horizontally centered.

.button {
    border: 1px solid #ccc;
    height: 40px;
    margin: 60px;
    padding: 4px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

Example: JsFiddle

How to add an extra column to a NumPy array

A bit late to the party, but nobody posted this answer yet, so for the sake of completeness: you can do this with list comprehensions, on a plain Python array:

source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)

Question mark and colon in statement. What does it mean?

string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");

can be translated to:

string requestUri="";
if ((OperationURL[1] == "GET")
{
    requestUri = _apiURL + "?e=" + GetRequestSignature();
}
else
{
   requestUri = _apiURL + "?e=";
}

How to define hash tables in Bash?

There's parameter substitution, though it may be un-PC as well ...like indirection.

#!/bin/bash

# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY="${animal%%:*}"
    VALUE="${animal##*:}"
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"

The BASH 4 way is better of course, but if you need a hack ...only a hack will do. You could search the array/hash with similar techniques.

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

PHP Fatal error: Cannot access empty property

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

"query function not defined for Select2 undefined error"

I also had this problem make sure that you don't initialize the select2 twice.

Warning: Found conflicts between different versions of the same dependent assembly

Here's the solution, .NET Core 3.0 style: https://github.com/HTD/ref-check

When you find what conflicts, maybe you would be able to resolve the conflicts. If the conflicting references are from other packages, you either out of luck, or you need to use sources instead.

In my case, the packages conflicting are often of my own, so I can fix dependency problems and republish them.

SSIS Connection Manager Not Storing SQL Password

Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.

Iterate through string array in Java

Those algorithms are both incorrect because of the comparison:

for( int i = 0; i < elements.length - 1; i++)

or

for(int i = 0; i + 1 < elements.length; i++) {

It's true that the array elements range from 0 to length - 1, but the comparison in that case should be less than or equal to. Those should be:

for(int i = 0; i < elements.length; i++) {

or

for(int i = 0; i <= elements.length - 1; i++) {

or

for(int i = 0; i + 1 <= elements.length; i++) {

The array ["a", "b"] would iterate as:

i = 0 is < 2: elements[0] yields "a"

i = 1 is < 2: elements[1] yields "b"

then exit the loop because 2 is not < 2.

The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.

How to implement authenticated routes in React Router 4?

I know it's been a while but I've been working on an npm package for private and public routes.

Here's how to make a private route:

<PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>

And you can also make Public routes that only unauthed user can access

<PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

I hope it helps!

Node.js project naming conventions for files & folders

Node.js doesn't enforce any file naming conventions (except index.js). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.

Create MSI or setup project with Visual Studio 2012

Have a look at the article Visual Studio Installer Deployment. It will surely help you.

You can choose the correct version of .NET framework on the page. So for you, make it .NET 4.5. I guess that would be there for Visual Studio 2012.

Creating java date object from year,month,day

That's my favorite way prior to Java 8:

Date date = new GregorianCalendar(year, month - 1, day).getTime();

I'd say this is a cleaner approach than:

calendar.set(year, month - 1, day, 0, 0);

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Can I obtain method parameter name using Java reflection?

see org.springframework.core.DefaultParameterNameDiscoverer class

DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] params = discoverer.getParameterNames(MathUtils.class.getMethod("isPrime", Integer.class));

Javascript - Track mouse position

Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

var period = 100,
    tracking;

window.addEventListener("mousemove", function(e) {
    if (!tracking) {
        return;
    }

    console.log("mouse location:", e.clientX, e.clientY)
    schedule();
});

schedule();

function schedule() {
    tracking = false;

    setTimeout(function() {
        tracking = true;
    }, period);
}

This tracks & acts on the mouse position, but only every period milliseconds.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

How best to read a File into List<string>

var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);

Since logFile is an array, you can pass it to the List<T> constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.

Actual constructor implementation:

public List(IEnumerable<T> collection)
{
        ...
        ICollection<T> c = collection as ICollection<T>;
        if( c != null) {
            int count = c.Count;
            if (count == 0)
            {
                _items = _emptyArray;
            }
            else {
                _items = new T[count];
                c.CopyTo(_items, 0);
                _size = count;
            }
        }   
        ...
} 

How to concatenate strings in a Windows batch file?

Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:

@echo off
setlocal enabledelayedexpansion
set myvar=the list: 
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%

Also consider the following restriction (MSDN):

The maximum individual environment variable size is 8192bytes.

Difference between using Throwable and Exception in a try catch

Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

How to use an array list in Java?

A three line solution, but works quite well:

int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
    target_list.add(random_array[i]);
}

How to set the width of a RaisedButton in Flutter?

In my case I used margin to be able to change the size:

Container(


     margin: EdgeInsets.all(10),

    // or margin: EdgeInsets.only(left:10, right:10),



        child: RaisedButton(
          padding: EdgeInsets.all(10),

          shape: RoundedRectangleBorder(borderRadius: 
BorderRadius.circular(20)),
          onPressed: () {},
          child: Text("Button"),
        ),
      ),

Regex for parsing directory and filename

A very late answer, but hope this will help

^(.+?)/([\w]+\.log)$

This uses lazy check for /, and I just modified the accepted answer

http://regex101.com/r/gV2xB7/1

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!

Important part of chrome extension source:

var port = chrome.runtime.connectNative("your.app.id"); 
      port.onMessage.addListener(onNativeMessage); 
      port.onDisconnect.addListener(onDisconnected);
      port.postMessage("send some data to STDIO");

permission file:

{
      "name": "your.app.id",
      "description": "Name of your extension",
      "path": "myapp.exe",
      "type": "stdio",
      "allowed_origins": [
            "chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
      ]
}

and windows registry settings:

HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json

How can I remove an SSH key?

I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.

Adding div element to body or document in JavaScript

You can make your div HTML code and set it directly into body(Or any element) with following code:

var divStr = '<div class="text-warning">Some html</div>';
document.getElementsByTagName('body')[0].innerHTML += divStr;

"Couldn't read dependencies" error with npm

I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install resolved my issue.

Disable a textbox using CSS

Another way is by making it readonly:

<input type="text" id="txtDis" readonly />

Converting byte array to string in javascript

That string2Bin can be written even more succinctly, and without any loops, to boot!

function string2Bin ( str ) {
    return str.split("").map( function( val ) { 
        return val.charCodeAt( 0 ); 
    } );
}

Different color for each bar in a bar chart; ChartJS

After looking into the Chart.Bar.js file I've managed to find the solution. I've used this function to generate a random color:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

I've added it to the end of the file and i called this function right inside the "fillColor:" under

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

                    datasetObject.bars.push(new this.BarClass({
                        value : dataPoint,
                        label : data.labels[index],
                        datasetLabel: dataset.label,
                        strokeColor : dataset.strokeColor,
                        fillColor : getRandomColor(),
                        highlightFill : dataset.highlightFill || dataset.fillColor,
                        highlightStroke : dataset.highlightStroke || dataset.strokeColor
                    }));
                },this);

and it works I get different color for each bar.

How do I execute a stored procedure once for each row returned by query?

try to change your method if you need to loop!

within the parent stored procedure, create a #temp table that contains the data that you need to process. Call the child stored procedure, the #temp table will be visible and you can process it, hopefully working with the entire set of data and without a cursor or loop.

this really depends on what this child stored procedure is doing. If you are UPDATE-ing, you can "update from" joining in the #temp table and do all the work in one statement without a loop. The same can be done for INSERT and DELETEs. If you need to do multiple updates with IFs you can convert those to multiple UPDATE FROM with the #temp table and use CASE statements or WHERE conditions.

When working in a database try to lose the mindset of looping, it is a real performance drain, will cause locking/blocking and slow down the processing. If you loop everywhere, your system will not scale very well, and will be very hard to speed up when users start complaining about slow refreshes.

Post the content of this procedure you want call in a loop, and I'll bet 9 out of 10 times, you could write it to work on a set of rows.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

One solution is to reset_index (and get back to df) and use pivot_table.

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

Determine file creation date in Java

in java1.7+ You can use this code to get file`s create time !

private static LocalDateTime getCreateTime(File file) throws IOException {
        Path path = Paths.get(file.getPath());
        BasicFileAttributeView basicfile = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr = basicfile.readAttributes();
        long date = attr.creationTime().toMillis();
        Instant instant = Instant.ofEpochMilli(date);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

Sublime 3 - Set Key map for function Goto Definition

I'm using Sublime portable version (for Windows) and this (placing the mousemap in SublimeText\Packages\User folder) did not work for me.

I had to place the mousemap file in SublimeText\Data\Packages\User folder to get it to work where SublimeText is the installation directory for my portable version. Data\Packages\User is where I found the keymap file as well.

Xcode 6.1 Missing required architecture X86_64 in file

My solution was connect my iPhone 6, build on it and I got the project running successfully.

Because I was building for iPhone 6 Simulator.

RegEx: Grabbing values between quotation marks

A supplementary answer for the subset of Microsoft VBA coders only one uses the library Microsoft VBScript Regular Expressions 5.5 and this gives the following code

Sub TestRegularExpression()

    Dim oRE As VBScript_RegExp_55.RegExp    '* Tools->References: Microsoft VBScript Regular Expressions 5.5
    Set oRE = New VBScript_RegExp_55.RegExp

    oRE.Pattern = """([^""]*)"""


    oRE.Global = True

    Dim sTest As String
    sTest = """Foo Bar"" ""Another Value"" something else"

    Debug.Assert oRE.test(sTest)

    Dim oMatchCol As VBScript_RegExp_55.MatchCollection
    Set oMatchCol = oRE.Execute(sTest)
    Debug.Assert oMatchCol.Count = 2

    Dim oMatch As Match
    For Each oMatch In oMatchCol
        Debug.Print oMatch.SubMatches(0)

    Next oMatch

End Sub

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

How to uninstall jupyter

When you $ pip install jupyter several dependencies are installed. The best way to uninstall it completely is by running:

  1. $ pip install pip-autoremove
  2. $ pip-autoremove jupyter -y

Kindly refer to this related question.

pip-autoremove removes a package and its unused dependencies. Here are the docs.

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

How to Force New Google Spreadsheets to refresh and recalculate?

What worked for me is inserting a column before the first column and deleting it immediately. Basically, do a change that will affect all the cells in the worksheet that will trigger recalculation.

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Putty: Getting Server refused our key Error

In the case of mine it was a wrong user:group attribution. I solved setting the right user and group:

sudo chown [user]:[group] -R /home/[user]

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Paying tribute to IgorBeaz, you need to stop running the current container. For that you are going to know current CONTAINER ID:

$ docker container ls

You get something like:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
12a32e8928ef        friendlyhello       "python app.py"     51 seconds ago      Up 50 seconds       0.0.0.0:4000->80/tcp   romantic_tesla   

Then you stop the container by:

$ docker stop 12a32e8928ef

Finally you try to do what you wanted to do, for example:

$ docker run -p 4000:80 friendlyhello

Zookeeper connection error

I was having the same error when I was trying to connect my broker with my Zookeeper ensemble using A records to point to Zookeeper IPs. The problem was in my zookeepers. My zookeepers were not able to bind to port 2181 because I was pointing my A records to public IP. This was preventing the zookeeper ensemble to choose a leader and communicate with each other. Pointing A records to private IP enabled the zookeeper ensemble to choose a leader and the cluster became active. After this when I tried to connect one of my brokers to the ensemble, it connected successfully.

Filter values only if not null using lambda in Java8

You can do this in single filter step:

requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));

If you don't want to call getName() several times (for example, it's expensive call), you can do this:

requiredCars = cars.stream().filter(c -> {
    String name = c.getName();
    return name != null && name.startsWith("M");
});

Or in more sophisticated way:

requiredCars = cars.stream().filter(c -> 
    Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());

How to insert values in two dimensional array programmatically?

Try to code below,

String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
  for(int y = 0; y < 3; y++)
  {
    shades[i][y] = value;
  }
}

Get the value in an input text box

Try this. It will work for sure.

var userInput = $('#txt_name').attr('value')

How to make a WPF window be on top of all other windows of my app (not system wide)?

use the Activate() method. This attempts to bring the window to the foreground and activate it. e.g. Window wnd = new xyz(); wnd.Activate();

socket.emit() vs. socket.send()

socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

Guid is all 0's (zeros)?

Use the static method Guid.NewGuid() instead of calling the default constructor.

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = Guid.NewGuid()
});

How can I use pointers in Java?

Not really, no.

Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.

Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

How to import data from text file to mysql database

If your table is separated by others than tabs, you should specify it like...

LOAD DATA LOCAL 
    INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport 
    COLUMNS TERMINATED BY '\t'  ## This should be your delimiter
    OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here

Beautiful Soup and extracting a div and its contents by ID

I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".

This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.

The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.

This is my code, where I just try to print the number of tags "div" with class "fcontent":

from BeautifulSoup import BeautifulSoup 
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f) 
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

How can I get the browser's scrollbar sizes?

if you are looking for a simple operation, just mix plain dom js and jquery,

var swidth=(window.innerWidth-$(window).width());

returns the size of current page scrollbar. (if it is visible or else will return 0)

Not able to start Genymotion device

I think you should configure your VirtualBox network adapter:

The adapter's IP address has to be in the same network (192.168.56.0/24 by default) as DHCP server's IP address and DHCP's IP address bounds. If all those addresses are not in the same network, then your Genymotion virtual device might not be able to start.

https://cloud.genymotion.com/page/faq/#collapse-blank

Or check log files to get a clue:

For each platform, the log files are stored here:
Windows Vista/7/8: C:\Users\USER\AppData\Local\Genymobile
Windows XP: C:\Documents and Settings\USER\Local settings\Application Data\Genymobile
Linux: /home/USER/.Genymobile
Mac: /Users/USER/.Genymobile

https://cloud.genymotion.com/page/faq/#collapse-logs

Convert a List<T> into an ObservableCollection<T>

ObervableCollection have constructor in which you can pass your list. Quoting MSDN:

 public ObservableCollection(
      List<T> list
 )

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

How to convert / cast long to String?

String longString = new String(""+long);

or

String longString = new Long(datelong).toString();

Setting user agent of a java URLConnection

HTTP Servers tend to reject old browsers and systems.

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

Using Python, how can I access a shared folder on windows network?

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

How can I make my string property nullable?

As others have pointed out, string is always nullable in C#. I suspect you are asking the question because you are not able to leave the middle name as null or blank? I suspect the problem is with your validation attributes, most likely the RegEx. I'm not able to fully parse RegEx in my head but I think your RegEx insists on the first character being present. I could be wrong - RegEx is hard. In any case, try commenting out your validation attributes and see if it works, then add them back in one at a time.

How can I test a PDF document if it is PDF/A compliant?

The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.

  • PDF/A1-a
  • PDF/A2-a
  • PDF/A2-b
  • PDF/A1-b
  • PDF/A2-u

Vertically align an image inside a div with responsive height

You can center an image, both horizontally and vertically, using margin: auto and absolute positioning. Also:

  1. It is possible to ditch extra markup by using pseudo elements.
  2. It is possible to display the middle portion of LARGE images by using negative left, top, right and bottom values.

_x000D_
_x000D_
.responsive-container {_x000D_
  margin: 1em auto;_x000D_
  min-width: 200px;       /* cap container min width */_x000D_
  max-width: 500px;       /* cap container max width */_x000D_
  position: relative;     _x000D_
  overflow: hidden;       /* crop if image is larger than container */_x000D_
  background-color: #CCC; _x000D_
}_x000D_
.responsive-container:before {_x000D_
  content: "";            /* using pseudo element for 1:1 ratio */_x000D_
  display: block;_x000D_
  padding-top: 100%;_x000D_
}_x000D_
.responsive-container img {_x000D_
  position: absolute;_x000D_
  top: -999px;            /* use sufficiently large number */_x000D_
  bottom: -999px;_x000D_
  left: -999px;_x000D_
  right: -999px;_x000D_
  margin: auto;           /* center horizontally and vertically */_x000D_
}
_x000D_
<p>Note: images are center-cropped on &lt;400px screen width._x000D_
  <br>Open full page demo and resize browser.</p>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/400/400/sports/9/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/400/200/sports/8/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/200/400/sports/7/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
  <img src="http://lorempixel.com/200/200/sports/6/">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath.

/html/body/div[1]/section/div/div[2]/div/form/div[2]/input[3]

Relative Xpath: Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.

Below is the example of a relative XPath.

//input[@name=’email’]

Styling Form with Label above Inputs

10 minutes ago i had the same problem of place label above input

then i got a small ugly resolution

<form>
    <h4><label for="male">Male</label></h4>
    <input type="radio" name="sex" id="male" value="male">
</form>

The disadvantage is that there is a big blank space between the label and input, of course you can adjust the css

Demo at: http://jsfiddle.net/bqkawjs5/

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:

 Naming.rebind("rmi://localhost:8080/AddService"
   ,addService); 

Thus the server binds both the IP = 127.0.0.1 and the port 8080.

But on the client side I had used:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
                        +"/AddService");

Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
                        +"/AddService");

and everything worked fine.

How to open link in new tab on html?

Use one of these as per your requirements.

Open the linked document in a new window or tab:

 <a href="xyz.html" target="_blank"> Link </a>

Open the linked document in the same frame as it was clicked (this is default):

 <a href="xyz.html" target="_self"> Link </a>

Open the linked document in the parent frame:

 <a href="xyz.html" target="_parent"> Link </a>

Open the linked document in the full body of the window:

 <a href="xyz.html" target="_top"> Link </a>

Open the linked document in a named frame:

 <a href="xyz.html" target="framename"> Link </a>

See MDN

Dataframe to Excel sheet

Or you can do like this:

your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
                  sheet_name= 'your_sheet_name'
                )

How can I export Excel files using JavaScript?

If you can generate the Excel file on the server, that is probably the best way. With Excel you can add formatting and get the output to look better. Several Excel options have already been mentioned. If you have a PHP backend, you might consider phpExcel.

If you are trying to do everything on the client in javascript, I don't think Excel is an option. You could create a CSV file and create a data URL to allow the user to download it.

I created a JSFiddle to demonstrate: http://jsfiddle.net/5KRf6/3/

This javascript (assuming you are using jQuery) will take the values out of input boxes in a table and build a CSV formatted string:

var csv = "";
$("table").find("tr").each(function () {
    var sep = "";
    $(this).find("input").each(function () {
        csv += sep + $(this).val();
        sep = ",";
    });
    csv += "\n";
});

If you wish, you can drop the data into a tag on the page (in my case a tag with an id of "csv"):

$("#csv").text(csv);

You can generate a URL to that text with this code:

window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);

Finally, this will add a link to download that data:

$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');

Making a DateTime field in a database automatic?

Just right click on that column and select properties and write getdate()in Default value or binding.like image:

enter image description here

If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:

[Databasegenerated(Databaseoption.computed)]

this attributes can found in System.ComponentModel.Dataannotion.Schema.

In my opinion first one is better:))

PHP __get and __set magic methods

I'd recommend to use an array for storing all values via __set().

class foo {

    protected $values = array();

    public function __get( $key )
    {
        return $this->values[ $key ];
    }

    public function __set( $key, $value )
    {
        $this->values[ $key ] = $value;
    }

}

This way you make sure, that you can't access the variables in another way (note that $values is protected), to avoid collisions.

How do you redirect HTTPS to HTTP?

all the above did not work when i used cloudflare, this one worked for me:

RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and this one definitely works without proxies in the way:

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Easy way to dismiss keyboard?

A slightly more robust method I needed to use recently:

- (void) dismissKeyboard {
    NSArray *windows = [UIApplication sharedApplication].windows;

    for(UIWindow *window in windows) [window endEditing:true];

    //  Or if you're only working with one UIWindow:

    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

I found some of the other "global" methods didn't work (for example, UIWebView & WKWebView refused to resign).

Get commit list between tags in git

FYI:

git log tagA...tagB

provides standard log output in a range.

What is the difference between display: inline and display: inline-block?

display: inline; is a display mode to use in a sentence. For instance, if you have a paragraph and want to highlight a single word you do:

<p>
    Pellentesque habitant morbi <em>tristique</em> senectus
    et netus et malesuada fames ac turpis egestas.
</p>

The <em> element has a display: inline; by default, because this tag is always used in a sentence. The <p> element has a display: block; by default, because it's neither a sentence nor in a sentence, it's a block of sentences.

An element with display: inline; cannot have a height or a width or a vertical margin. An element with display: block; can have a width, height and margin.
If you want to add a height to the <em> element, you need to set this element to display: inline-block;. Now you can add a height to the element and every other block style (the block part of inline-block), but it is placed in a sentence (the inline part of inline-block).

Ranges of floating point datatype in C?

These numbers come from the IEEE-754 standard, which defines the standard representation of floating point numbers. Wikipedia article at the link explains how to arrive at these ranges knowing the number of bits used for the signs, mantissa, and the exponent.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Microsoft Visual C++ Compiler for Python 3.4

For the different python versions:

Visual C++ |CPython
--------------------
14.0       |3.5
10.0       |3.3, 3.4
9.0        |2.6, 2.7, 3.0, 3.1, 3.2

Source: Windows Compilers for py

Also refer: this answer

How to use Git for Unity3D source control?

I suggest that you make a .gitignore file that includes everything other than the assets folder (all the other files that are originally inside a unity project). Next, you should place all your game projects in one folder. Next, duplicate the .gitignore in every single project folder for your games. This will exclude the libraries and unnecessary folders inside your projects other than the assets. If you have any projects you don't want, then put them in a new .gitignore inside where your game projects are stored. Note: You can have multiple .gitignore's and .gitignore is based on relative paths. I hope that helped!

Java Round up Any Number

I don't know why you are dividing by 100 but here my assumption int a;

int b = (int) Math.ceil( ((double)a) / 100);

or

int b = (int) Math.ceil( a / 100.0);

Removing spaces from a variable input using PowerShell 4.0

The Replace operator means Replace something with something else; do not be confused with removal functionality.

Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.

To remove all spaces, use 'Replace any space symbol with empty string'

$string = $string -replace '\s',''

To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use

$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '

or the more native System.String method

$string = $string.Trim()

Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.

Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care

'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033

UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

JavaScript displaying a float to 2 decimal places

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

round(1.005, 2); // return 1.01

round(1.004, 2); // return 1 instead of 1.00

The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/

Checking for empty result (php, pdo, mysql)

$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");

$sql->execute();

$fetch = $sql->fetch(PDO::FETCH_ASSOC);

// if not empty result
if (is_array($fetch))  {
    $_SESSION["userMember"] = $fetch["username"];
    $_SESSION["password"] = $fetch["password"];
    echo 'yes this member is registered'; 
}else {
    echo 'empty result!';
}

String.equals() with multiple conditions (and one action on result)

Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal() calls and ||.

How to create PDFs in an Android app?

It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.

We use three libraries:

(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,

(2) iTextPDF (itextpdf-5.5.0.jar),

(3) XMLWorker (xmlworker-5.5.1.jar).

public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
    final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
    File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
    if ( !path.exists() ){ path.mkdir(); }
    File file = new File(path, fileName);

    try{

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    document.open();

    // ?????????????? HTML
    String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
    InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );

    // ???????? ???????? PDF
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
        inputStream, null, Charset.defaultCharset(), new MyFont());

    document.close();
    return true;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (DocumentException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } 

The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:

public class MyFont implements FontProvider{
    private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
    private static final String FONT_ALIAS = "my_font";

    public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }

    @Override
    public Font getFont(String fontname, String encoding, boolean embedded,
        float size, int style, BaseColor color){

        return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H, 
            BaseFont.EMBEDDED, size, style, color);
    }

    @Override
    public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}

Here we use the standard Android font Droid Sans, which is located in the system folder:

private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";

What's the difference between '$(this)' and 'this'?

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

how to create dynamic two dimensional array in java?

List<Integer>[] array;  
array = new List<Integer>[10]; 

this the second case in @TofuBeer's answer is incorrect. because can't create arrays with generics. u can use:

List<List<Integer>> array = new ArrayList<>();

How to temporarily disable a click handler in jQuery?

I just barely ran into this problem when trying to display a loading spinner while I waited for a function to complete. Because I was appending the spinner into the HTML, the spinner would be duplicated each time the button was clicked, if you're not against defining a variable on the global scale, then this worked well for me.

    var hasCardButtonBeenClicked = '';
    $(".js-mela-card-button").on("click", function(){  
        if(!hasCardButtonBeenClicked){
            hasCardButtonBeenClicked = true;
            $(this).append('<i class="fa fa-circle-o-notch fa-spin" style="margin-left: 3px; font-size: 15px;" aria-hidden="true"></i>');
        }    
    });

Notice, all I'm doing is declaring a variable, and as long as its value is null, the actions following the click will occur and then subsequently set the variables value to "true" (it could be any value, as long as it's not empty), further disabling the button until the browser is refreshed or the variable is set to null.

Looking back it probably would have made more sense to just set the hasCardButtonBeenClicked variable to "false" to begin with, and then alternate between "true" and "false" as needed.

Remove leading comma from a string

In this specific case (there is always a single character at the start you want to remove) you'll want:

str.substring(1)

However, if you want to be able to detect if the comma is there and remove it if it is, then something like:

if (str[0] == ',') { 
  str = str.substring(1);
}

Find all CSV files in a directory using Python

Use the python glob module to easily list out the files we need.

import glob
path_csv=glob.glob("../data/subfolrder/*.csv")

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked

How do I Sort a Multidimensional Array in PHP

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    // replace 0 with the field's index/key
    $dates[$key]  = $row[0];
}

array_multisort($dates, SORT_DESC, $mdarray);

For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);

Android: How to enable/disable option menu item on button click?

simplify @Vikas version

@Override
public boolean onPrepareOptionsMenu (Menu menu) {

    menu.findItem(R.id.example_foobar).setEnabled(isFinalized);
    return true;
}

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

How to add Google Maps Autocomplete search box?

Just copy and paste the sameple code below.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
    </head>
    <body>
        <label for="locationTextField">Location</label>
        <input id="locationTextField" type="text" size="50">

        <script>
            function init() {
                var input = document.getElementById('locationTextField');
                var autocomplete = new google.maps.places.Autocomplete(input);
            }

            google.maps.event.addDomListener(window, 'load', init);
        </script>
    </body>
</html>

Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

Calculating width from percent to pixel then minus by pixel in LESS CSS

Or, you could use the margin attribute like this:

    {
    background:#222;
    width:100%;
    height:100px;
    margin-left: 10px;
    margin-right: 10px;
    display:block;
    }

CSS: Control space between bullet and <li>

If your list-style is inside then you could remove the bullet and create your own ... e.g. (in scss!)

            li {
                list-style: none;
                &:before {
                    content: '- ';
                }
            }

And if you list style is outside then you could do something like this:

            li { 
                padding-left: 10px;
                list-style: none;
                &:before {
                    content: '* '; /* use any character you fancy~! */
                    position: absolute;
                    margin-left: -10px;
                }
            }

How to make the tab character 4 spaces instead of 8 spaces in nano?

For anyone who may stumble across this old question ...

There is one thing that I think needs to be addressed.

~/.nanorc is used to apply your user specific settings to nano, so if you are editing files that require the use of sudo nano for permissions then this is not going to work.

When using sudo your custom user configuration files will not be loaded when opening a program, as you are not running the program from your account so none of your configuration changes in ~/.nanorc will be applied.

If this is the situation you find yourself in (wanting to run sudo nano and use your own config settings) then you have three options :

  • using command line flags when running sudo nano
  • editing the /root/.nanorc file
  • editing the /etc/nanorc global config file

Keep in mind that /etc/nanorc is a global configuration file and as such it affects all users, which may or may not be a problem depending on whether you have a multi-user system.

Also, user config files will override the global one, so if you were to edit /etc/nanorc and ~/.nanorc with different settings, when you run nano it will load the settings from ~/.nanorc but if you run sudo nano then it will load the settings from /etc/nanorc.

Same goes for /root/.nanorc this will override /etc/nanorc when running sudo nano

Using flags is probably the best option unless you have a lot of options.

How to read from input until newline is found using scanf()?

I am too late, but you can try this approach as well.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i=0, j=0, arr[100];
    char temp;
    while(scanf("%d%c", &arr[i], &temp)){
        i++;
        if(temp=='\n'){
            break;
        }
    }
    for(j=0; j<i; j++) {
        printf("%d ", arr[j]);
    }

    return 0;
}

How is a tag different from a branch in Git? Which should I use, here?

From the theoretical point of view:

  • tags are symbolic names for a given revision. They always point to the same object (usually: to the same revision); they do not change.
  • branches are symbolic names for line of development. New commits are created on top of branch. The branch pointer naturally advances, pointing to newer and newer commits.

From the technical point of view:

  • tags reside in refs/tags/ namespace, and can point to tag objects (annotated and optionally GPG signed tags) or directly to commit object (less used lightweight tag for local names), or in very rare cases even to tree object or blob object (e.g. GPG signature).
  • branches reside in refs/heads/ namespace, and can point only to commit objects. The HEAD pointer must refer to a branch (symbolic reference) or directly to a commit (detached HEAD or unnamed branch).
  • remote-tracking branches reside in refs/remotes/<remote>/ namespace, and follow ordinary branches in remote repository <remote>.

See also gitglossary manpage:

branch

A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch.

tag

A ref pointing to a tag or commit object. In contrast to a head, a tag is not changed by a commit. Tags (not tag objects) are stored in $GIT_DIR/refs/tags/. [...]. A tag is most typically used to mark a particular point in the commit ancestry chain.

tag object

An object containing a ref pointing to another object, which can contain a message just like a commit object. It can also contain a (PGP) signature, in which case it is called a "signed tag object".

Delete forked repo from GitHub

I had also faced this issue. NO it will not affect your original repo by anyway. just simply delete it by entering the name of forked repo