Programs & Examples On #System.xml

The type or namespace name 'System' could not be found

I had the same problem earlier when I tried to edit an open source project from the internet .

Solved it by just Cleaning the solution and rebuilding it .

Hope this helps.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

500.21 Bad module "ManagedPipelineHandler" in its module list

Please follow these steps:

1) Run the command prompt as administrator.

2) Type either of the two lines below in the command prompt:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

or

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

Main culprit for this error is logic which determines encoding when converting Stream or byte[] array to .NET string.

Using StreamReader created with 2nd constructor parameter detectEncodingFromByteOrderMarks set to true, will determine proper encoding and create string which does not break XmlDocument.LoadXml method.

public string GetXmlString(string url)
{
    using var stream = GetResponseStream(url);
    using var reader = new StreamReader(stream, true);
    return reader.ReadToEnd(); // no exception on `LoadXml`
}

Common mistake would be to just blindly use UTF8 encoding on the stream or byte[]. Code bellow would produce string that looks valid when inspected in Visual Studio debugger, or copy-pasted somewhere, but it will produce the exception when used with Load or LoadXml if file is encoded differently then UTF8 without BOM.

public string GetXmlString(string url)
{
    byte[] bytes = GetResponseByteArray(url);
    return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}

So, in the case of your third party library, they probably use 2nd approach to decode XML stream to string, thus the exception.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

The ideal scenario is to have <add value="default.aspx" /> in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.

We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:

<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <remove value="default.aspx" />
        <add value="default.aspx" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>

Works OK for us.

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

Could not load file or assembly '***.dll' or one of its dependencies

I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.

How to avoid a System.Runtime.InteropServices.COMException?

I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .

I hope you this concept.

Serialize an object to XML

public string ObjectToXML(object input)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(input.GetType());
        serializer.Serialize(stringwriter, input);
        return stringwriter.ToString();
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
            ex = ex.InnerException;

        return "Could not convert: " + ex.Message;
    }
}

//Usage
var res = ObjectToXML(obj)

You need to use following classes:

using System.IO;
using System.Xml;
using System.Xml.Serialization;

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace. I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!

what a trial converting from website to web application project can be!

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My issue was that the root element actually has a xmlns="abc123"

So had to make XmlRoot("elementname",NameSpace="abc123")

XDocument or XmlDocument

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument. If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

Adding attributes to an XML node

Well id isn't really the root node: Login is.

It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.

If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("Login");
        XmlElement id = doc.CreateElement("id");
        id.SetAttribute("userName", "Tushar");
        id.SetAttribute("passWord", "Tushar");
        XmlElement name = doc.CreateElement("Name");
        name.InnerText = "Tushar";
        XmlElement age = doc.CreateElement("Age");
        age.InnerText = "24";

        id.AppendChild(name);
        id.AppendChild(age);
        root.AppendChild(id);
        doc.AppendChild(root);

        doc.Save("test.xml");
    }
}

How to Deserialize XML document

I don't think .net is 'picky about deserializing arrays'. The first xml document is not well formed. There is no root element, although it looks like there is. The canonical xml document has a root and at least 1 element (if at all). In your example:

<Root> <-- well, the root
  <Cars> <-- an element (not a root), it being an array
    <Car> <-- an element, it being an array item
    ...
    </Car>
  </Cars>
</Root>

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

How can I open an Excel file in Python?

This may help:

This creates a node that takes a 2D List (list of list items) and pushes them into the excel spreadsheet. make sure the IN[]s are present or will throw and exception.

this is a re-write of the Revit excel dynamo node for excel 2013 as the default prepackaged node kept breaking. I also have a similar read node. The excel syntax in Python is touchy.

thnx @CodingNinja - updated : )

###Export Excel - intended to replace malfunctioning excel node

import clr

clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel                            C:\Program Files\Microsoft Office\Office15\EXCEL.EXE 
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import  * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0]             ##Filename
sheetName = IN[1]               ##Sheet
RowOffset= IN[2]                ##RowOffset
ColOffset= IN[3]                ##COL OFfset
Data=IN[4]                      ##Data
Overwrite=IN[5]                 ##Check for auto-overwtite
XLVisible = False   #IN[6]      ##XL Visible for operation or not?

RowOffset=0
if IN[2]>0:
    RowOffset=IN[2]             ##RowOffset

ColOffset=0
if IN[3]>0:
    ColOffset=IN[3]             ##COL OFfset

if IN[6]<>False:
    XLVisible = True #IN[6]     ##XL Visible for operation or not?

################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11                 #####define special sells value constant
################################
xls = Excel.ApplicationClass()          ####Connect with application
xls.Visible = XLVisible                 ##VISIBLE YES/NO
xls.DisplayAlerts = False               ### ALerts

import os.path

if os.path.isfile(strFileName):
    wb = xls.Workbooks.Open(strFileName, False)     ####Open the file 
else:
    wb = xls.Workbooks.add#         ####Open the file 
    wb.SaveAs(strFileName)
wb.application.visible = XLVisible      ####Show Excel
try:
    ws = wb.Worksheets(sheetName)       ####Get the sheet in the WB base

except:
    ws = wb.sheets.add()                ####If it doesn't exist- add it. use () for object method
    ws.Name = sheetName



#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[]                                  ###MESSAGE GATHERING

c=0
r=0
val=""
if Overwrite == False :                 ####Look ahead for non-empty cells to throw error
    for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
        for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
            if col.Value2 >"" :
                OUT= "ERROR- Cannot overwrite"
                raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################

for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
    for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
        ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()

##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")

Populate unique values into a VBA array from Excel

one more way ...

Sub get_unique()
Dim unique_string As String
    lr = Sheets("data").Cells(Sheets("data").Rows.Count, 1).End(xlUp).Row
    Set range1 = Sheets("data").Range("A2:A" & lr)
    For Each cel In range1
       If Not InStr(output, cel.Value) > 0 Then
           unique_string = unique_string & cel.Value & ","
       End If
    Next
End Sub

open link in iframe

Try this:

<iframe name="iframe1" src="target.html"></iframe>

<a href="link.html" target="iframe1">link</a>

The "target" attribute should open in the iframe.

How to get two or more commands together into a batch file

Try this: edited

@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

How do I load a file from resource folder?

Try:

InputStream is = MyTest.class.getResourceAsStream("/test.csv");

IIRC getResourceAsStream() by default is relative to the class's package.

As @Terran noted, don't forget to add the / at the starting of the filename

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

This works:

Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next() == 5) {
        iter.remove();
    }
}

I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove() functionality.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

This error should not happen in the managed code. This might solve the issue:

Go to Visual Studio Debugger to bypass this exception:

Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"

Hope it will help.

How do I restrict an input to only accept numbers?

Try this,

<input ng-keypress="validation($event)">

 function validation(event) {
    var theEvent = event || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }

}

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

Also make sure avoid not use [ValidateAntiForgeryToken] under [HttpGet].

  [HttpGet]
  public ActionResult MethodName()
  {
  ..
  }

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

Convert tabs to spaces in Notepad++

The easy way:

  1. Highlight a single tab area
  2. Copy
  3. Bring up find/replace
  4. Paste into the find field
  5. Click into the replace field and hit the space bar
  6. Then replace all.

How to initialize an array in one step using Ruby?

You can use an array literal:

array = [ '1', '2', '3' ]

You can also use a range:

array = ('1'..'3').to_a  # parentheses are required
# or
array = *('1'..'3')      # parentheses not required, but included for clarity

For arrays of whitespace-delimited strings, you can use Percent String syntax:

array = %w[ 1 2 3 ]

You can also pass a block to Array.new to determine what the value for each entry will be:

array = Array.new(3) { |i| (i+1).to_s }

Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]

How to get the azure account tenant Id?

The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,

https://manage.windowsazure.com/<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1

Azure Mgmt Console Active Directory

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

My problem was resolved after cleaning up some directories and files left over from the previous versions of the tools. ADT Rev 14 changes where binaries are stored. I deleted the entire bin directory, restarted Eclipse and cleaned the build and forced a rebuild. That seemed to do the trick initially but the problem came back after the next run.

I finally discovered that my bin directory was included in the project build path. I excluded bin from the build path and repeated the steps above. This resolved my problem.

Validate phone number using javascript

Here's how I do it.

_x000D_
_x000D_
function validate(phone) {_x000D_
  const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  console.log(regex.test(phone))_x000D_
}_x000D_
_x000D_
validate('1234567890')     // true_x000D_
validate(1234567890)       // true_x000D_
validate('(078)789-8908')  // true_x000D_
validate('123-345-3456')   // true
_x000D_
_x000D_
_x000D_

Find and replace with sed in directory and sub directories

For larger s&r tasks it's better and faster to use grep and xargs, so, for example;

grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'

Use ssh from Windows command prompt

Cygwin can give you this functionality.

Generate a dummy-variable

The other answers here offer direct routes to accomplish this taskā€”one that many models (e.g. lm) will do for you internally anyway. Nonetheless, here are ways to make dummy variables with Max Kuhn's popular caret and recipes packages. While somewhat more verbose, they both scale easily to more complicated situations, and fit neatly into their respective frameworks.


caret::dummyVars

With caret, the relevant function is dummyVars, which has a predict method to apply it on a data frame:

df <- data.frame(letter = rep(c('a', 'b', 'c'), each = 2),
                 y = 1:6)

library(caret)

dummy <- dummyVars(~ ., data = df, fullRank = TRUE)

dummy
#> Dummy Variable Object
#> 
#> Formula: ~.
#> 2 variables, 1 factors
#> Variables and levels will be separated by '.'
#> A full rank encoding is used

predict(dummy, df)
#>   letter.b letter.c y
#> 1        0        0 1
#> 2        0        0 2
#> 3        1        0 3
#> 4        1        0 4
#> 5        0        1 5
#> 6        0        1 6

recipes::step_dummy

With recipes, the relevant function is step_dummy:

library(recipes)

dummy_recipe <- recipe(y ~ letter, df) %>% 
    step_dummy(letter)

dummy_recipe
#> Data Recipe
#> 
#> Inputs:
#> 
#>       role #variables
#>    outcome          1
#>  predictor          1
#> 
#> Steps:
#> 
#> Dummy variables from letter

Depending on context, extract the data with prep and either bake or juice:

# Prep and bake on new data...
dummy_recipe %>% 
    prep() %>% 
    bake(df)
#> # A tibble: 6 x 3
#>       y letter_b letter_c
#>   <int>    <dbl>    <dbl>
#> 1     1        0        0
#> 2     2        0        0
#> 3     3        1        0
#> 4     4        1        0
#> 5     5        0        1
#> 6     6        0        1

# ...or use `retain = TRUE` and `juice` to extract training data
dummy_recipe %>% 
    prep(retain = TRUE) %>% 
    juice()
#> # A tibble: 6 x 3
#>       y letter_b letter_c
#>   <int>    <dbl>    <dbl>
#> 1     1        0        0
#> 2     2        0        0
#> 3     3        1        0
#> 4     4        1        0
#> 5     5        0        1
#> 6     6        0        1

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How can I check if my python object is a number?

Test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).

However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.

This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

SQL Query for Student mark functionality

My attempt - I'd start with the max mark and build from there

Schema:

CREATE TABLE Student (
  StudentId int,
  Name nvarchar(30),
  Details nvarchar(30)
)
CREATE TABLE Subject (
  SubjectId int,
  Name nvarchar(30)
)
CREATE TABLE Marks (
  StudentId int,
  SubjectId int,
  Mark int
)

Data:

INSERT INTO Student (StudentId, Name, Details) 
VALUES (1,'Alfred','AA'), (2,'Betty','BB'), (3,'Chris','CC')

INSERT INTO Subject (SubjectId, Name)
VALUES (1,'Maths'), (2, 'Science'), (3, 'English')

INSERT INTO Marks (StudentId, SubjectId, Mark)
VALUES 
(1,1,61),(1,2,75),(1,3,87),
(2,1,82),(2,2,64),(2,3,77),
(3,1,82),(3,2,83),(3,3,67)
GO

My query would have been:

;WITH MaxMarks AS (
  SELECT SubjectId, MAX(Mark) as MaxMark
    FROM Marks
    GROUP BY SubjectId
 )
SELECT s.Name as [StudentName], sub.Name AS [SubjectName],m.Mark
FROM MaxMarks mm
INNER JOIN Marks m 
ON m.SubjectId = mm.SubjectId 
AND m.Mark = mm.MaxMark
INNER JOIN Student s
ON s.StudentId = m.StudentId
INNER JOIN Subject sub
ON sub.SubjectId = mm.SubjectId

SQL Fiddle Example

  1. Find the max mark for each subject
  2. Join Marks, Student and Subject to find the relevant details of that highest mark

This also take care of duplicate students with the highest mark

Results:

STUDENTNAME SUBJECTNAME     MARK
Alfred  English     87
Betty   Maths           82
Chris   Maths           82
Chris   Science     83

Detecting iOS / Android Operating system

For this and other kind of client detections I suggest this js library: http://hictech.github.io/navJs/tester/index.html

For your specific answer use:

navJS.isIOS() || navJS.isAndroid()

Spark Kill Running Application

  • copy past the application Id from the spark scheduler, for instance application_1428487296152_25597
  • connect to the server that have launch the job
  • yarn application -kill application_1428487296152_25597

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

There is another issue you have to take care of it when you try mapping column which is string length, for example TK_NO nvarchar(50) you will have to map to the same length as the destination field.

.htaccess rewrite to redirect root URL to subdirectory

A little googling, gives me these results:

RewriteEngine On
RewriteBase /
RewriteRule ^index.(.*)?$ http://domain.com/subfolder/ [r=301]

This will redirect any attempt to access a file named index.something to your subfolder, whether the file exists or not.

Or try this:

RewriteCond %{HTTP_HOST} !^www.sample.com$ [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}/samlse/$1 [R=301,L]

I haven't done much redirect in the .htaccess file, so I'm not sure if this will work.

How to remove leading zeros using C#

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

What is the best way to conditionally apply attributes in AngularJS?

To get an attribute to show a specific value based on a boolean check, or be omitted entirely if the boolean check failed, I used the following:

ng-attr-example="{{params.type == 'test' ? 'itWasTest' : undefined }}"

Example usage:

<div ng-attr-class="{{params.type == 'test' ? 'itWasTest' : undefined }}">

Would output <div class="itWasTest"> or <div> based on the value of params.type

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

How to select date from datetime column?

Though all the answers on the page will return the desired result, they all have performance issues. Never perform calculations on fields in the WHERE clause (including a DATE() calculation) as that calculation must be performed on all rows in the table.

The BETWEEN ... AND construct is inclusive for both border conditions, requiring one to specify the 23:59:59 syntax on the end date which itself has other issues (microsecond transactions, which I believe MySQL did not support in 2009 when the question was asked).

The proper way to query a MySQL timestamp field for a particular day is to check for Greater-Than-Equals against the desired date, and Less-Than for the day after, with no hour specified.

WHERE datetime>='2009-10-20' AND datetime<'2009-10-21'

This is the fastest-performing, lowest-memory, least-resource intensive method, and additionally supports all MySQL features and corner-cases such as sub-second timestamp precision. Additionally, it is future proof.

how to POST/Submit an Input Checkbox that is disabled?

UPDATE: READONLY doesn't work on checkboxes

You could use disabled="disabled" but at this point checkbox's value will not appear into POST values. One of the strategy is to add an hidden field holding checkbox's value within the same form and read value back from that field

Simply change disabled to readonly

Can you target <br /> with css?

My own tests conclusively show that br tags do not like to be targeted for css.

But if you can add style then you can probably also add a scrip tag to the header of the page? Link to an external .js that does something like this:

function replaceLineBreaksWithHorizontalRulesInElement( element )
{
    elems = element.getElementsByTagName( 'br' );
    for ( var i = 0; i < elems.length; i ++ )
    {
        br = elems.item( i );
        hr = document.createElement( 'hr' );
        br.parentNode.replaceChild( hr, br );
    }
}

So in short, it's not optimal, but here is my solution.

Command not found when using sudo

Ok this is my solution: in ~/.bash_aliases just add the following:

# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
   export PATH=$PATH:/home/your_user/bin 
fi

Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.

Notice that I need to be explicit when adding my PATH since HOME for superuser is /root

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

I use this:

@var.respond_to?(:keys)

It works for Hash and ActiveSupport::HashWithIndifferentAccess.

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

Get href attribute on jQuery

Very simply, use this as the context: http://api.jquery.com/jQuery/#selector-context

var a_href = $('div.cpt', this).find('h2 a').attr('href');

Which says, find 'div.cpt' only inside this

Returning a boolean from a Bash function

It might work if you rewrite this function myfun(){ ... return 0; else return 1; fi;} as this function myfun(){ ... return; else false; fi;}. That is if false is the last instruction in the function you get false result for whole function but return interrupts function with true result anyway. I believe it's true for my bash interpreter at least.

MongoDb shuts down with Code 100

MongoDB needs a folder to store the database. Create a C:\data\db\ directory:

mkdir C:\data\db

and then start MongoDB:

C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe

Sometimes C:\data\db folder already exists due to previous installation. So if for this reason mongod.exe does not work, you may delete all the contents from C:\data\db folder and execute mongod.exeagain.

What is the default root pasword for MySQL 5.7

None of these answers worked for me on Ubuntu Server 18.04.1 and MySQL 5.7.23. I spent a bunch of time trying and failing at setting the password and auth plugin manually, finding the password in logs (it's not there), etc.

The solution is actually super easy:

sudo mysql_secure_installation

It's really important to do this with sudo. If you try without elevation, you'll be asked for the root password, which you obviously don't have.

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

How do I get currency exchange rates via an API such as Google Finance?

If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564

require 'faraday'
require 'faraday_middleware'
require 'json'

# Debug: 
# require "pry"


country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")

currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash

dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')

puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Difference is first one returns an MvcHtmlString but second (Render..) outputs straight to the response.

Python IndentationError unindent does not match any outer indentation level

I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.

However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.

Commenting out code blocks in Atom

On an belgium keyboard asserted on the mac command + shift + / is the keystroke for commenting out a block.

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

display Java.util.Date in a specific format

This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());

Accessing Google Account Id /username via Android

if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
  Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
  String userid=currentPerson.getId(); //BY THIS CODE YOU CAN GET CURRENT LOGIN USER ID
}

error TS2339: Property 'x' does not exist on type 'Y'

I was getting this error on Vue 3. It was because defineComponent must be imported like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "HelloWorld",
    props: {
        msg: String,
    },
    created() {
        this.testF();
    },
    methods: {
        testF() {
            console.log("testF");
        },
    },
});
</script>

Load a bitmap image into Windows Forms using open file dialog

You should try to:

  • Create the picturebox visually in form (it's easier)
  • Set Dock property of picturebox to Fill (if you want image to fill form)
  • Set SizeMode of picturebox to StretchImage

Finally:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open Image";
    dlg.Filter = "bmp files (*.bmp)|*.bmp";
    if (dlg.ShowDialog() == DialogResult.OK)
    {                     
        PictureBox1.Image = Image.FromFile(dlg.Filename);
    }
    dlg.Dispose();
}

for or while loop to do something n times

This is lighter weight than xrange (and the while loop) since it doesn't even need to create the int objects. It also works equally well in Python2 and Python3

from itertools import repeat
for i in repeat(None, 10):
    do_sth()

Using filesystem in node.js with async / await

Node.js 8.0.0

Native async / await

Promisify

From this version, you can use native Node.js function from util library.

const fs = require('fs')
const { promisify } = require('util')

const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)

const run = async () => {
  const res = await readFileAsync('./data.json')
  console.log(res)
}

run()


Promise Wrapping

const fs = require('fs')

const readFile = (path, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.readFile(path, opts, (err, data) => {
      if (err) reject(err)
      else resolve(data)
    })
  })

const writeFile = (path, data, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.writeFile(path, data, opts, (err) => {
      if (err) reject(err)
      else resolve()
    })
  })

module.exports = {
  readFile,
  writeFile
}

...


// in some file, with imported functions above
// in async block
const run = async () => {
  const res = await readFile('./data.json')
  console.log(res)
}

run()

Advice

Always use try..catch for await blocks, if you don't want to rethrow exception upper.

How to capture a list of specific type with mockito

Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:

@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
    ArgumentCaptor.forClass(List.class);

Full example here and corresponding passing CI build and test run here.

Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.

Is there an opposite to display:none?

The best answer for display: none is

display:inline

or

display:normal

How to change current Theme at runtime in Android

i got the same problem but i found the solution.

public class EditTextSmartPhoneActivity extends Activity implements DialogInterface.OnClickListener
{
    public final static int CREATE_DIALOG  = -1;
    public final static int THEME_HOLO_LIGHT  = 0;
    public final static int THEME_BLACK  = 1;

    int position;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        position = getIntent().getIntExtra("position", -1);

        switch(position)
        {
        case CREATE_DIALOG:
            createDialog();
            break;
        case THEME_HOLO_LIGHT:
            setTheme(android.R.style.Theme_Holo_Light);
            break;
        case THEME_BLACK:
            setTheme(android.R.style.Theme_Black);
            break;
        default:
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    }

    private void createDialog()
    {
        /** Options for user to select*/
        String choose[] = {"Theme_Holo_Light","Theme_Black"};

        AlertDialog.Builder b = new AlertDialog.Builder(this);

        /** Setting a title for the window */
        b.setTitle("Choose your Application Theme");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(choose, 0, null);

        /** Setting a positive button and its listener */
        b.setPositiveButton("OK",this);

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** show dialog*/
        d.show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        AlertDialog alert = (AlertDialog)dialog;
        int position = alert.getListView().getCheckedItemPosition();

        finish();
        Intent intent = new Intent(this, EditTextSmartPhoneActivity.class);
        intent.putExtra("position", position);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

Open new popup window without address bars in firefox & IE

In internet explorer, if the new url is from the same domain as the current url, the window will be open without an address bar. Otherwise, it will cause an address bar to appear. One workaround is to open a page from the same domain and then redirect from that page.

Log all queries in mysql

Enable the log for table

mysql> SET GLOBAL general_log = 'ON';
mysql> SET global log_output = 'table';

View log by select query

select * from mysql.general_log

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

PowerShell array initialization

If I don't know the size up front, I use an arraylist instead of an array.

$al = New-Object System.Collections.ArrayList
for($i=0; $i -lt 5; $i++)
{
    $al.Add($i)
}

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

Callback after all asynchronous forEach callbacks are completed

Array.forEach does not provide this nicety (oh if it would) but there are several ways to accomplish what you want:

Using a simple counter

function callback () { console.log('all done'); }

var itemsProcessed = 0;

[1, 2, 3].forEach((item, index, array) => {
  asyncFunction(item, () => {
    itemsProcessed++;
    if(itemsProcessed === array.length) {
      callback();
    }
  });
});

(thanks to @vanuan and others) This approach guarantees that all items are processed before invoking the "done" callback. You need to use a counter that gets updated in the callback. Depending on the value of the index parameter does not provide the same guarantee, because the order of return of the asynchronous operations is not guaranteed.

Using ES6 Promises

(a promise library can be used for older browsers):

  1. Process all requests guaranteeing synchronous execution (e.g. 1 then 2 then 3)

    function asyncFunction (item, cb) {
      setTimeout(() => {
        console.log('done with', item);
        cb();
      }, 100);
    }
    
    let requests = [1, 2, 3].reduce((promiseChain, item) => {
        return promiseChain.then(() => new Promise((resolve) => {
          asyncFunction(item, resolve);
        }));
    }, Promise.resolve());
    
    requests.then(() => console.log('done'))
    
  2. Process all async requests without "synchronous" execution (2 may finish faster than 1)

    let requests = [1,2,3].map((item) => {
        return new Promise((resolve) => {
          asyncFunction(item, resolve);
        });
    })
    
    Promise.all(requests).then(() => console.log('done'));
    

Using an async library

There are other asynchronous libraries, async being the most popular, that provide mechanisms to express what you want.

Edit

The body of the question has been edited to remove the previously synchronous example code, so i've updated my answer to clarify. The original example used synchronous like code to model asynchronous behaviour, so the following applied:

array.forEach is synchronous and so is res.write, so you can simply put your callback after your call to foreach:

  posts.foreach(function(v, i) {
    res.write(v + ". index " + i);
  });

  res.end();

What is polymorphism, what is it for, and how is it used?

I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:

Treating a derived type as if it were it's base type.

There are plenty of examples above that show this in action, but I feel this is a good concise answer.

Static Block in Java

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

can you add HTTPS functionality to a python flask web server?

  • To run https functionality or SSL authentication in flask application you first install "pyOpenSSL" python package using:

     pip install pyopenssl
    
  • Next step is to create 'cert.pem' and 'key.pem' using following command on terminal :

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • Copy generated 'cert.pem' and 'kem.pem' in you flask application project

  • Add ssl_context=('cert.pem', 'key.pem') in app.run()

For example:

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/')

    def index():

        return 'Flask is running!'


    @app.route('/data')

    def names():

        data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}

        return jsonify(data)

  if __name__ == '__main__':

        app.run(ssl_context=('cert.pem', 'key.pem'))

Replace line break characters with <br /> in ASP.NET MVC Razor view

Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!

<span style="white-space: pre-line">@Model.CommentText</span>

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):

 public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
    {
        Form form = new Form();
        Label label = new Label();
        TextBox textBox = new TextBox();
        Button button_1 = new Button();
        Button button_2 = new Button();
        Button button_3 = new Button();

        int buttonStartPos = 228; //Standard two button position


        if (button3 != null)
            buttonStartPos = 228 - 81;
        else
        {
            button_3.Visible = false;
            button_3.Enabled = false;
        }


        form.Text = title;

        // Label
        label.Text = promptText;
        label.SetBounds(9, 20, 372, 13);
        label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);

        // TextBox
        if (value == null)
        {
        }
        else
        {
            textBox.Text = value;
            textBox.SetBounds(12, 36, 372, 20);
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
        }

        button_1.Text = button1;
        button_2.Text = button2;
        button_3.Text = button3 ?? string.Empty;
        button_1.DialogResult = DialogResult.OK;
        button_2.DialogResult = DialogResult.Cancel;
        button_3.DialogResult = DialogResult.Yes;


        button_1.SetBounds(buttonStartPos, 72, 75, 23);
        button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
        button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);

        label.AutoSize = true;
        button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

        form.ClientSize = new Size(396, 107);
        form.Controls.AddRange(new Control[] { label, button_1, button_2 });
        if (button3 != null)
            form.Controls.Add(button_3);
        if (value != null)
            form.Controls.Add(textBox);

        form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.StartPosition = FormStartPosition.CenterScreen;
        form.MinimizeBox = false;
        form.MaximizeBox = false;
        form.AcceptButton = button_1;
        form.CancelButton = button_2;

        DialogResult dialogResult = form.ShowDialog();
        value = textBox.Text;
        return dialogResult;
    }

Get last n lines of a file, similar to tail

S.Lott's answer above almost works for me but ends up giving me partial lines. It turns out that it corrupts data on block boundaries because data holds the read blocks in reversed order. When ''.join(data) is called, the blocks are in the wrong order. This fixes that.

def tail(f, window=20):
    """
    Returns the last `window` lines of file `f` as a list.
    f - a byte file-like object
    """
    if window == 0:
        return []
    BUFSIZ = 1024
    f.seek(0, 2)
    bytes = f.tell()
    size = window + 1
    block = -1
    data = []
    while size > 0 and bytes > 0:
        if bytes - BUFSIZ > 0:
            # Seek back one whole BUFSIZ
            f.seek(block * BUFSIZ, 2)
            # read BUFFER
            data.insert(0, f.read(BUFSIZ))
        else:
            # file too small, start from begining
            f.seek(0,0)
            # only read what was not read
            data.insert(0, f.read(bytes))
        linesFound = data[0].count('\n')
        size -= linesFound
        bytes -= BUFSIZ
        block -= 1
    return ''.join(data).splitlines()[-window:]

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

How do I retrieve an HTML element's actual width and height?

Just in case it is useful to anyone, I put a textbox, button and div all with the same css:

width:200px;
height:20px;
border:solid 1px #000;
padding:2px;

<input id="t" type="text" />
<input id="b" type="button" />
<div   id="d"></div>

I tried it in chrome, firefox and ie-edge, I tried with jquery and without, and I tried it with and without box-sizing:border-box. Always with <!DOCTYPE html>

The results:

                                                               Firefox       Chrome        IE-Edge    
                                                              with   w/o    with   w/o    with   w/o     box-sizing

$("#t").width()                                               194    200    194    200    194    200
$("#b").width()                                               194    194    194    194    194    194
$("#d").width()                                               194    200    194    200    194    200

$("#t").outerWidth()                                          200    206    200    206    200    206
$("#b").outerWidth()                                          200    200    200    200    200    200
$("#d").outerWidth()                                          200    206    200    206    200    206

$("#t").innerWidth()                                          198    204    198    204    198    204
$("#b").innerWidth()                                          198    198    198    198    198    198
$("#d").innerWidth()                                          198    204    198    204    198    204

$("#t").css('width')                                          200px  200px  200px  200px  200px  200px
$("#b").css('width')                                          200px  200px  200px  200px  200px  200px
$("#d").css('width')                                          200px  200px  200px  200px  200px  200px

$("#t").css('border-left-width')                              1px    1px    1px    1px    1px    1px
$("#b").css('border-left-width')                              1px    1px    1px    1px    1px    1px
$("#d").css('border-left-width')                              1px    1px    1px    1px    1px    1px

$("#t").css('padding-left')                                   2px    2px    2px    2px    2px    2px
$("#b").css('padding-left')                                   2px    2px    2px    2px    2px    2px
$("#d").css('padding-left')                                   2px    2px    2px    2px    2px    2px

document.getElementById("t").getBoundingClientRect().width    200    206    200    206    200    206
document.getElementById("b").getBoundingClientRect().width    200    200    200    200    200    200
document.getElementById("d").getBoundingClientRect().width    200    206    200    206    200    206

document.getElementById("t").offsetWidth                      200    206    200    206    200    206
document.getElementById("b").offsetWidth                      200    200    200    200    200    200
document.getElementById("d").offsetWidth                      200    206    200    206    200    206

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Keytool in Java 6 does have this capability: Importing private keys into a Java keystore using keytool

Here are the basic details from that post.

  1. Convert the existing cert to a PKCS12 using OpenSSL. A password is required when asked or the 2nd step will complain.

    openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root
    
  2. Convert the PKCS12 to a Java Keystore File.

    keytool -importkeystore -deststorepass [new_keystore_pass] -destkeypass [new_key_pass] -destkeystore [keystore.jks] -srckeystore [keystore.p12] -srcstoretype PKCS12 -srcstorepass [pass_used_in_p12_keystore] -alias [alias_used_in_p12_keystore]
    

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

Measuring code execution time

If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime Property which you can get under System.Diagnostics namespace.

TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);

Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above

Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.

How do you get the currently selected <option> in a <select> via JavaScript?

var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );

SQLAlchemy: print the actual query

I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:

borrowed from: https://gist.github.com/gsakkis/4572159

The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:

# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime

from sqlalchemy.orm import Query


try:
    basestring
except NameError:
    basestring = str


def render_query(statement, dialect=None):
    """
    Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement.
    WARNING: This method of escaping is insecure, incomplete, and for debugging
    purposes only. Executing SQL statements with inline-rendered user values is
    extremely insecure.
    Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
    """
    if isinstance(statement, Query):
        if dialect is None:
            dialect = statement.session.bind.dialect
        statement = statement.statement
    elif dialect is None:
        dialect = statement.bind.dialect

    class LiteralCompiler(dialect.statement_compiler):

        def visit_bindparam(self, bindparam, within_columns_clause=False,
                            literal_binds=False, **kwargs):
            return self.render_literal_value(bindparam.value, bindparam.type)

        def render_array_value(self, val, item_type):
            if isinstance(val, list):
                return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
            return self.render_literal_value(val, item_type)

        def render_literal_value(self, value, type_):
            if isinstance(value, long):
                return str(value)
            elif isinstance(value, (basestring, date, datetime, timedelta)):
                return "'%s'" % str(value).replace("'", "''")
            elif isinstance(value, list):
                return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
            return super(LiteralCompiler, self).render_literal_value(value, type_)

    return LiteralCompiler(dialect, statement).process(statement)

Tested to two levels of nested arrays.

/bin/sh: pushd: not found

pushd is a bash enhancement to the POSIX-specified Bourne Shell. pushd cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd command might do the chdir(2) call and then start a new shell, but ... it wouldn't be very usable.) pushd is a shell builtin, just like cd.

So, either change your script to start with #!/bin/bash or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash.

Nodejs - Redirect url

It's possible to use:

res.redirect('your/404/path.html');

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

Combating AngularJS executing controller twice

My issue was really difficult to track down. In the end, the problem was occurring when the web page had missing images. The src was missing a Url. This was happening on an MVC 5 Web Controller. To fix the issue, I included transparent images when no real image is available.

<img alt="" class="logo" src="">

Iterate through <select> options

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

how to insert datetime into the SQL Database table?

myConn.Execute "INSERT INTO DayTr (dtID, DTSuID, DTDaTi, DTGrKg) VALUES (" & Val(txtTrNo) & "," & Val(txtCID) & ", '" & Format(txtTrDate, "yyyy-mm-dd") & "' ," & Val(Format(txtGross, "######0.00")) & ")"

Done in vb with all text type variables.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

Add items to comboBox in WPF

Scenario 1 - you don't have a data-source for the items
You can just populate the ComboBox with static values as follows -
From XAML:

<ComboBox Height="23" Name="comboBox1" Width="120">
        <ComboBoxItem Content="X"/>
        <ComboBoxItem Content="Y"/>
        <ComboBoxItem Content="Z"/>
</ComboBox>  

Or, from CodeBehind:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Add("X");
    comboBox1.Items.Add("Y");
    comboBox1.Items.Add("Z");
}  

Scenario 2.a - you have a data-source, and the items never get changed
You can use the data-source to populate the ComboBox. Any IEnumerable type can be used as the data-source. You need to assign it to the ItemsSource property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable).

Scenario 2.b - you have a data-source, and the items might get changed
You should use an ObservableCollection<T> as the data-source and assign it to the ItemsSource property of the ComboBox (it's up to you how you populate the ObservableCollection<T>). Using an ObservableCollection<T> ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.

How do I negate a condition in PowerShell?

If you are like me and dislike the double parenthesis, you can use a function

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example

What does @media screen and (max-width: 1024px) mean in CSS?

It's limiting the styles defined there to the screen (e.g. not print or some other media) and is further limiting the scope to viewports which are 1024px or less in width.

http://www.css3.info/preview/media-queries/

Check if character is number?

Use combination of isNaN and parseInt functions:

var character = ... ; // your character
var isDigit = ! isNaN( parseInt(character) );

Another notable way - multiplication by one (like character * 1 instead of parseInt(character)) - makes a number not only from any numeric string, but also a 0 from empty string and a string containing only spaces so it is not suitable here.

how to output every line in a file python

You probably want something like:

if data.find('!masters') != -1:
     f = open('masters.txt')
     lines = f.read().splitlines()
     f.close()
     for line in lines:
         print line
         sck.send('PRIVMSG ' + chan + " " + str(line) + '\r\n')

Don't close it every iteration of the loop and print line instead of lines. Also use readlines to get all the lines.

EDIT removed my other answer - the other one in this discussion is a better alternative than what I had, so there's no reason to copy it.

Also stripped off the \n with read().splitlines()

Enter triggers button click

It is important to read the HTML specifications to truly understand what behavior is to be expected:

The HTML5 spec explicitly states what happens in implicit submissions:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).

Edit to add:

The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.

How to pass arguments to addEventListener listener function?

Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop

for (var key in catalog){
    document.getElementById(key).my_id = key
    document.getElementById(key).addEventListener('click', function(e) {
        editorContent.loadCatalogEntry(e.srcElement.my_id)
    }, false);
}

It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers

I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D

How to make a div with a circular shape?

.circle {
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background: red;
}

<div class="circle"></div>

see this FIDDLE

Error using eclipse for Android - No resource found that matches the given name

I actually has this problem once with a path issue referring another project :

I had this in my default.properties:

android.library.reference.1=..\\MyProject_Core\\

Which I fixed like this:

android.library.reference.1=../MyProject_Core/

My colleague created the above with Windows but only the version below worked on my Mac.

UTF-8 encoding problem in Spring MVC

Also add to your beans :

   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
        </bean></bean>

For @ExceptionHandler :

enter code<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
    <property name="messageConverters">
        <array>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </array>
    </property>
</bean>

If you use <mvc:annotation-driven/> it should be after beans.

Richtextbox wpf binding

Create a UserControl which has a RichTextBox named RTB. Now add the following dependency property:

    public FlowDocument Document
    {
        get { return (FlowDocument)GetValue(DocumentProperty); }
        set { SetValue(DocumentProperty, value); }
    }

    public static readonly DependencyProperty DocumentProperty =
        DependencyProperty.Register("Document", typeof(FlowDocument), typeof(RichTextBoxControl), new PropertyMetadata(OnDocumentChanged));

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBoxControl control = (RichTextBoxControl) d;
        FlowDocument document = e.NewValue as FlowDocument;
        if (document  == null)
        {
            control.RTB.Document = new FlowDocument(); //Document is not amused by null :)
        }
        else
        {
            control.RTB.Document = document;
        }
    }

This solution is probably that "proxy" solution you saw somewhere.. However.. RichTextBox simply does not have Document as DependencyProperty... So you have to do this in another way...

HTH

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

The first method checks if a string is null or a blank string. In your example you can risk a null reference since you are not checking for null before trimming

1- string.IsNullOrEmpty(text.Trim())

The second method checks if a string is null or an arbitrary number of spaces in the string (including a blank string)

2- string .IsNullOrWhiteSpace(text)

The method IsNullOrWhiteSpace covers IsNullOrEmpty, but it also returns true if the string contains white space.

In your concrete example you should use 2) as you run the risk of a null reference exception in approach 1) since you're calling trim on a string that may be null

Facebook API: Get fans of / people who like a page

For s3m3n's answer, Facebook fans plugin (e.g. LAMODA) has limitation now, you get less and less new fans on continuous requests. You may try my modified PHP script to visualize results: https://gist.github.com/liruqi/7f425bd570fa8a7c73be#file-facebook_fans_by_plugin-php

Another approach is Facebook graph search. On search result page: People who like pages named "Lamoda" , open Chrome console and run JavaScript:

var run = 0;
var mails = {}
total = 3000; //????,??????????

function getEmails (cont) {
    var friendbutton=cont.getElementsByClassName("_ohe");
    for(var i=0; i<friendbutton.length; i++) {
        var link = friendbutton[i].getAttribute("href");

        if(link && link.substr(0,25)=="https://www.facebook.com/") {
            var parser = document.createElement('a');
            parser.href = link;
            if (parser.pathname) {
                path = parser.pathname.substr(1);
                if (path == "profile.php") {
                    search = parser.search.substr(1);
                    var args = search.split('&');
                    email = args[0].split('=')[1] + "@facebook.com\n";
                } else {
                    email = parser.pathname.substr(1) + "@facebook.com\n";
                }
                if (mails[email] > 0) {
                    continue;
                }
                mails[email] = 1;
                console.log(email);
            }
        }
    }
}

function moreScroll() {
    var text="";
    containerID = "BrowseResultsContainer"
    if (run > 0) {
        containerID = "fbBrowseScrollingPagerContainer" + (run-1);
    }
    var cont = document.getElementById(containerID);
    if (cont) {
        run++;
        var id = run - 2;
        if (id >= 0) {
            setTimeout(function() {
                containerID = "fbBrowseScrollingPagerContainer" + (id);
                var delcont = document.getElementById(containerID);
                if (delcont) {
                getEmails(delcont);
                delcont.parentNode.removeChild(delcont);
                }
                window.scrollTo(0, document.body.scrollHeight - 10);
            }, 1000);
        }
    } else {
        console.log("# " + containerID);
    }
    if (run < total) {
        window.scrollTo(0, document.body.scrollHeight + 10);
    }
    setTimeout(moreScroll, 2000);
}//1000?????,?????????

moreScroll();

It would load new fans and print user id/email, remove old DOM nodes to avoid page crash. You may find this script here

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

Fixed positioning in Mobile Safari

This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.

// css
#sticky.stick {
    width:100%;
    height:50px;
    position: fixed;
    top: 0;
    z-index: 1;
}

// jquery 
//sticky nav
    function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;

      if (window_top > div_top)
        $('#sticky').addClass('stick');
      else
        $('#sticky').removeClass('stick');
     }

$(window).scroll(function(event){

    // sticky nav css NON mobile way
       sticky_relocate();

       var st = $(this).scrollTop();

    // sticky nav iPhone android mobile way iOS<5

       if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
            //do nothing uses sticky_relocate() css
       } else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {

            var window_top = $(window).scrollTop();
            var div_top = $('#sticky-anchor').offset().top;

            if (window_top > div_top) {
                $('#sticky').css({'top' : st  , 'position' : 'absolute' });
            } else {
                $('#sticky').css({'top' : 'auto' });
            }
        };

Find a pair of elements from an array whose sum equals a given number

Just attended this question on HackerRank and here's my 'Objective C' Solution:

-(NSNumber*)sum:(NSArray*) a andK:(NSNumber*)k {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    long long count = 0;
    for(long i=0;i<a.count;i++){

        if(dict[a[i]]) {
            count++;
            NSLog(@"a[i]: %@, dict[array[i]]: %@", a[i], dict[a[i]]);
        }
        else{
            NSNumber *calcNum = @(k.longLongValue-((NSNumber*)a[i]).longLongValue);
            dict[calcNum] = a[i];
        }

    }
    return @(count);
}

Hope it helps someone.

Vertical alignment of text and icon in button

There is one rule that is set by font-awesome.css, which you need to override.

You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline; by default and which I've corrected here:

<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:

enter image description here

I've downsized the font-size of the icon above in this instance to 30px, as it feels too big at 40px for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:

enter image description here

How to copy folders to docker image from Dockerfile?

As mentioned in your ticket:

You have COPY files/* /test/ which expands to COPY files/dir files/file1 files/file2 files/file /test/.
If you split this up into individual COPY commands (e.g. COPY files/dir /test/) you'll see that (for better or worse) COPY will copy the contents of each arg dir into the destination directory. Not the arg dir itself, but the contents.

I'm not thrilled with that fact that COPY doesn't preserve the top-level dir but its been that way for a while now.

so in the name of preserving a backward compatibility, it is not possible to COPY/ADD a directory structure.

The only workaround would be a series of RUN mkdir -p /x/y/z to build the target directory structure, followed by a series of docker ADD (one for each folder to fill).
(ADD, not COPY, as per comments)

open() in Python does not create a file if it doesn't exist

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.

How to trigger a phone call when clicking a link in a web page on mobile phone

The proper URL scheme is tel:[number] so you would do

_x000D_
_x000D_
<a href="tel:5551234567"><img src="callme.jpg" /></a>
_x000D_
_x000D_
_x000D_

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

alt text

Alternatively

[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

Username and password in command for git push

It is possible but, before git 2.9.3 (august 2016), a git push would print the full url used when pushing back to the cloned repo.
That would include your username and password!

But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 71076e1, 08 Aug 2016)

push: anonymize URL in status output

Commit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.

The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.

Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.

But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.

PHP - check if variable is undefined

An another way is simply :

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Will return :

"Yes 3"

The best way is to use isset(), otherwise you can have an error like "undefined $test".

You can do it like this :

if( isset($test) && ($test!==null) )

You'll not have any error because the first condition isn't accepted.

How to kill a nodejs process in Linux?

pkill is the easiest command line utility

pkill -f node

or

pkill -f nodejs

whatever name the process runs as for your os

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

How to set corner radius of imageView?

Layer draws out of clip region, you need to set it to mask to bounds:

self.mainImageView.layer.masksToBounds = true

From the docs:

By default, the corner radius does not apply to the image in the layerā€™s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

Best way to store chat messages in a database?

You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).

The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).

Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.

How can I get the source code of a Python function?

The inspect module has methods for retrieving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.


The following tests inspect.getsource(foo) using Python 3.6:

import inspect

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

source_foo = inspect.getsource(foo)  # foo is normal function
print(source_foo)

source_max = inspect.getsource(max)  # max is a built-in function
print(source_max)

This first prints:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

Then fails on inspect.getsource(max) with the following error:

TypeError: <built-in function max> is not a module, class, method, function, traceback, frame, or code object

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

How to create a release signed apk file using Gradle?

For Groovy (build.gradle)

You should not put your signing credentials directly in the build.gradle file. Instead the credentials should come from a file not under version control.

Put a file signing.properties where the module specific build.gradle is found. Don't forget to add it to your .gitignore file!

signing.properties

storeFilePath=/home/willi/example.keystore
storePassword=secret
keyPassword=secret
keyAlias=myReleaseSigningKey

build.gradle

android {
    // ...
    signingConfigs{
        release {
            def props = new Properties()

            def fileInputStream = new FileInputStream(file('../signing.properties'))
            props.load(fileInputStream)
            fileInputStream.close()

            storeFile = file(props['storeFilePath'])
            storePassword = props['storePassword']
            keyAlias = props['keyAlias']
            keyPassword = props['keyPassword']
        }
    }

    buildTypes {
        release {
            signingConfig signingConfigs.release
            // ...
        }
    }
}

Find Active Tab using jQuery and Twitter Bootstrap

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active")

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
  activeTab = e.target;
})

How do I list all loaded assemblies?

Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.

foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){                      
            System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
            foreach(Type type in asm.GetTypes()){   
                //PROPERTIES
                foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
                    if (property.CanRead){
                        Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);       
                    }
                }
                //METHODS
                var methods = type.GetMethods();
                foreach (System.Reflection.MethodInfo method in methods){               
                    Response.Write("<br><b>" + an.ToString() + "."  + type.ToString() + "." + method.Name  + "</b>");   
                    foreach (System.Reflection.ParameterInfo param in method.GetParameters())
                    {
                        Response.Write("<br><i>Param=" + param.Name.ToString());
                        Response.Write("<br>  Type=" + param.ParameterType.ToString());
                        Response.Write("<br>  Position=" + param.Position.ToString());
                        Response.Write("<br>  Optional=" + param.IsOptional.ToString() + "</i>");
                    }
                }
            }
        }

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in ā€œSheet1ā€ to a range of precedent cells in ā€œSheet2.ā€ Click the ā€œSheet2ā€ tab.

Step 2

Determine the precedent rangeā€™s width in columns and height in rows. In this example, assume cells A1 through A4 on ā€œSheet2ā€ contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the ā€œSheet1ā€ tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type ā€œ=,ā€ the worksheet name containing the precedent cells, ā€œ!,ā€ the top left cell of the precedent range, ā€œ:ā€ and the bottom right cell of the precedent range. Press ā€œCtrl,ā€ ā€œShiftā€ and ā€œEnterā€ simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range thatā€™s in the same respective location within the range. In this example, type ā€œ=Sheet2!A1:A4ā€ and press ā€œCtrl,ā€ ā€œShiftā€ and ā€œEnterā€ simultaneously. Cells C1 through C4 on ā€œSheet1ā€ now contain the array formula ā€œ{=Sheet2!A1:A4}ā€ surrounded by curly brackets, and show the same data as the precedent cells in ā€œSheet2.ā€

Good Luck !!!

Make page to tell browser not to cache/preserve input values

From a Stack Overflow reference

It did not work with value="" if the browser already saves the value so you should add.

For an input tag there's the attribute autocomplete you can set:

<input type="text" autocomplete="off" />

You can use autocomplete for a form too.

Listing all extras of an Intent

You can do it in one line of code:

Log.d("intent URI", intent.toUri(0));

It outputs something like:

"#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10a00000;component=com.mydomain.myapp/.StartActivity;sourceBounds=12%20870%20276%201167; l.profile=0; end"

At the end of this string (the part that I bolded) you can find the list of extras (only one extra in this example).

This is according to the toUri documentation: "The URI contains the Intent's data as the base URI, with an additional fragment describing the action, categories, type, flags, package, component, and extras."

Elegant Python function to convert CamelCase to snake_case?

Lightely adapted from https://stackoverflow.com/users/267781/matth who use generators.

def uncamelize(s):
    buff, l = '', []
    for ltr in s:
        if ltr.isupper():
            if buff:
                l.append(buff)
                buff = ''
        buff += ltr
    l.append(buff)
    return '_'.join(l).lower()

How to restart counting from 1 after erasing table in MS Access?

You can use:

CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"

I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.

Why are C++ inline functions in the header?

The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.

Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)

How do I perform a JAVA callback between classes?

In this particular case, the following should work:

serverConnectionHandler = new ServerConnections(_address) {
    public void newConnection(Socket _socket) {
        System.out.println("A function of my child class was called.");
    }
};

It's an anonymous subclass.

In git, what is the difference between merge --squash and rebase?

Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.

Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.

When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.

Hope that was clear!

How to run a script file remotely using SSH

I was able to invoke a shell script using this command:

ssh ${serverhost} "./sh/checkScript.ksh"

Of course, checkScript.ksh must exist in the $HOME/sh directory.

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

Set UILabel line spacing

My solution was to patch the font file itself and fix its line height definitely. http://mbauman.net/geek/2009/03/15/minor-truetype-font-editing-on-a-mac/

I had to modify 'lineGap', 'ascender', 'descender' in the 'hhea' block (as in the blog example).

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

Convert InputStream to BufferedReader

A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);

Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

Can I hide/show asp:Menu items based on role?

To find menu items in content page base on roles

 protected void Page_Load(object sender, EventArgs e)
{
   if (Session["AdminSuccess"] != null)
        {
           Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");

    //you must know the index of items to be removed first
    mainMenu.Items.RemoveAt(1);

    //or you try to hide menu and list items inside menu with css 
    // cssclass must be defined in style tag in .aspx page
    mainMenu.CssClass = ".hide";

        }   

}

<style type="text/css">
.hide
    {
        visibility: hidden;
     }
  </style>  

Unknown Column In Where Clause

try your task using IN condition or OR condition and also this query is working on spark-1.6.x

 SELECT  patient, patient_id FROM `patient` WHERE patient IN ('User4', 'User3');

or

SELECT  patient, patient_id FROM `patient` WHERE patient = 'User1' OR patient = 'User2';

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
        pb.directory(dir);
        Process p = pb.start();

Setting log level of message at runtime in slf4j

Try switching to Logback and use

ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));

I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.

Remember to set the log level back after you're done.

Implementing a simple file download servlet

Try with Resource

File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
   ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
         String.format("attachment; filename=\"%s\"", file.getName()));

OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
}
out.flush();

Copy Notepad++ text with formatting?

It is worth mentioning that 64-bit Notepad++ does not support Plugin Manager and NPPExport, so they won't be shown in Plugins menu. If you will try to add NPPExport plugin manually, most likely you'll see :

"NPPExport plugin is not supported with 64bit Notepad++"

Fortunately, there is NPP_Export plugin to download from here which works well with 64-bit Notepad++ (v7.2.2 in my case) and support for Plugin Manager is underway (check GitHub for updates).

Reading HTML content from a UIWebView

The second question is actually easier to answer. Look at the stringWithContentsOfURL:encoding:error: method of NSString - it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:

NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL 
                                                encoding:NSASCIIStringEncoding
                                                   error:&error];

After running this code, googlePage will contain the HTML for www.google.com, and error will contain any errors encountered in the fetch. (You should check the contents of error after the fetch.)

Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You'll have to pull the request from the view, then do the fetch as before:

NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL 
                                          encoding:NSASCIIStringEncoding
                                             error:&error];

EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its stringByEvaluatingJavascriptFromString: method, as such:

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: 
                                         @"document.body.innerHTML"];

This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.

Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let's say you take the second example above, where you have NSString *page as the result of a call to stringWithContentsOfURL:encoding:error:. You can then push that string into the web view using loadHTMLString:baseURL:, assuming you also held on to the NSURL you requested:

[yourWebView loadHTMLString:page baseURL:requestURL];

I'm not sure, however, if this will run JavaScript found in the page you load (the method name, loadHTMLString, is somewhat ambiguous, and the docs don't say much about it).

For more info:

Create instance of generic type in Java?

If you mean new E() then it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor? But you can always delegate creation to some other class that knows how to create an instance - it can be Class<E> or your custom code like this

interface Factory<E>{
    E create();
}    

class IntegerFactory implements Factory<Integer>{    
  private static int i = 0; 
  Integer create() {        
    return i++;    
  }
}

C++ for each, pulling from vector elements

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>

using namespace std;

int main() 
{
  int total = 0;

  vector<int> v(6);
  v[0] = 10; v[1] = 20; v[2] = 30;
  v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
    total += i;
  }

  cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.

What is the best way to get the minimum or maximum value from an Array of numbers?

Unless the array is sorted, that's the best you're going to get. If it is sorted, just take the first and last elements.

Of course, if it's not sorted, then sorting first and grabbing the first and last is guaranteed to be less efficient than just looping through once. Even the best sorting algorithms have to look at each element more than once (an average of O(log N) times for each element. That's O(N*Log N) total. A simple scan once through is only O(N).

If you are wanting quick access to the largest element in a data structure, take a look at heaps for an efficient way to keep objects in some sort of order.

What is the difference between a port and a socket?

There seems to be a lot of answers equating socket with the connection between 2 PC's..which I think is absolutely incorrect. A socket has always been the endpoint on 1 PC, that may or may not be connected - surely we've all used listener or UDP sockets* at some point. The important part is that it's addressable and active. Sending a message to 1.1.1.1:1234 is not likely to work, as there is no socket defined for that endpoint.

Sockets are protocol specific - so the implementation of uniqueness that both TCP/IP and UDP/IP uses* (ipaddress:port), is different than eg., IPX (Network, Node, and...ahem, socket - but a different socket than is meant by the general "socket" term. IPX socket numbers are equivalent to IP ports). But, they all offer a unique addressable endpoint.

Since IP has become the dominant protocol, a port (in networking terms) has become synonomous with either a UDP or TCP port number - which is a portion of the socket address.

  • UDP is connection-less - meaning no virtual circuit between the 2 endpoints is ever created. However, we still refer to UDP sockets as the endpoint. The API functions make it clear that both are just different type of sockets - SOCK_DGRAM is UDP (just sending a message) and SOCK_STREAM is TCP (creating a virtual circuit).

  • Technically, the IP header holds the IP Address, and the protocol on top of IP (UDP or TCP) holds the port number. This makes it possible to have other protocols (eg. ICMP that have no port numbers, but do have IP addressing information).

Multiple radio button groups in MVC 4 Razor

all you need is to tie the group to a different item in your model

@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")

@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")

webpack is not recognized as a internal or external command,operable program or batch file

I had this issue when upgrading to React 16.12.0.

I had two errors one regarding webpack and the other regarding the store when rendering the DOM.

Webpack Error:

webpack is not recognized as a internal or external command,operable program or batch file

Webpack Solution:

  1. Close related VS Solution
  2. Delete node_modules folder
  3. Deleted package-lock.json
  4. npm install
  5. npm rebuild
  6. Repeated this 2-3 times

Store Error:

Type Store<()> is not assignable to type Store<any, AnyAction>

Store Solution:

Suggestions to update my React version didn't fix this error for me, but irrespective I would recommend doing it.

My code ended up looking like this:

ReactDOM.render(
        <Provider store={store as any}>
            <ConnectedApp />
        </Provider>,
        document.getElementById('app')
    );

As per this solution

Connect Bluestacks to Android Studio

  1. Goto Blustacks settings > Preferences > Check Enable Android Debug Bridge (ADB)
  2. Restart Bluestacks and Start Android Studio
  3. Done

How to kill MySQL connections

mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id  | User | Host            | db   | Command | Time | State | Info      |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds  | Query   |    0 | init  | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds  | Sleep   |    4 |       | NULL      |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)

mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)

USER 192 :

mysql> SELECT * FROM exept;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):

bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
               "~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));

And angular app would appear in bundle unmodified.

Angular 2 Sibling Component Communication

A directive can make sense in certain situations to 'connect' components. In fact the things being connected don't even need to be full components, and sometimes it's more lightweight and actually simpler if they aren't.

For example I've got a Youtube Player component (wrapping Youtube API) and I wanted some controller buttons for it. The only reason the buttons aren't part of my main component is that they're located elsewhere in the DOM.

In this case it's really just an 'extension' component that will only ever be of use with the 'parent' component. I say 'parent', but in the DOM it is a sibling - so call it what you will.

Like I said it doesn't even need to be a full component, in my case it's just a <button> (but it could be a component).

@Directive({
    selector: '[ytPlayerPlayButton]'
})
export class YoutubePlayerPlayButtonDirective {

    _player: YoutubePlayerComponent; 

    @Input('ytPlayerVideo')
    private set player(value: YoutubePlayerComponent) {
       this._player = value;    
    }

    @HostListener('click') click() {
        this._player.play();
    }

   constructor(private elementRef: ElementRef) {
       // the button itself
   }
}

In the HTML for ProductPage.component, where youtube-player is obviously my component that wraps the Youtube API.

<youtube-player #technologyVideo videoId='NuU74nesR5A'></youtube-player>

... lots more DOM ...

<button class="play-button"        
        ytPlayerPlayButton
        [ytPlayerVideo]="technologyVideo">Play</button>

The directive hooks everything up for me, and I don't have to declare the (click) event in the HTML.

So the directive can nicely connect to the video player without having to involve ProductPage as a mediator.

This is the first time I've actually done this, so not yet sure how scalable it might be for much more complex situations. For this though I'm happy and it leaves my HTML simple and responsibilities of everything distinct.

Eclipse Workspaces: What for and why?

Basically the scope of workspace(s) is divided in two points.

First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.

And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.

Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!

command/usr/bin/codesign failed with exit code 1- code sign error

You almost made it on your own, but in the end there seems to be something wrong with your profile.

First I would recommend a tool to "look inside" the profile to make sure it's the right one: http://furbo.org/2013/11/02/a-quick-look-plug-in-for-provisioning/

This will just add some more information about the profile, when selecting it in Finder and pressing space (Quick Look).


Check your Xcode Preferences:

  1. Xcode Perferences (CMD + ,)
  2. Accounts
  3. Select your account on the left
  4. Select view details on the bottom right
  5. Refresh (using the small button on the bottom left)

Xcode Settings

Xcode stores the profiles in ~/Library/MobileDevice/Provisioning Profiles

If your distribution profile is not in there, double click on it.

Then it should appear in that folder, but with a hashed name, e.g. 1edf8f42-fd1c-48a9-8938-754cdf6f7f41.mobileprovision at this point the Quick Look plugin comes in handy :-)


Next, check your Project Settings:

  1. select the target (not project) you want to build in Xcode
  2. switch to build settings
  3. look for the "Code Signing" section
  4. check if the correct profile is selected under "Provisioning Profile" => "Release"

Build Settings


Next, check your Scheme Settings:

  1. select Product menu
  2. open scheme submenu
  3. select edit scheme...
  4. select "Archive" on the left
  5. Build configuration should be set to "Release"

Scheme Settings


Next, check the Keychain Access Trust settings:

  1. open keychain access (spotlight => keychain)
  2. select login
  3. click on Certificates
  4. look for iPhone Distribution: Elena Carrasco (8HE2MJLM25) on the right
  5. right click, select "Get Info"
  6. open "Trust" section
  7. set to "Use System Defaults"
  8. repeat steps 5 to 7 for Apple Worldwide Developer Relations Certificate Authority

Keychain


Next, check the Keychain Access private key Access Control:

  1. repeat steps 1 to 4 from previous check
  2. expand the profile to make your private key visible
  3. right click on the private key, select "Get Info"
  4. switch to "Access Control"
  5. select "Confirm before allowing access"
  6. use the "+" button to add "codesign" (normally located in /usr/bin/codesign)
    Hint: if it doesn't show up in the file browser, use cmd + shift + g to enter the path manually
  7. when using Carthage: add /usr/bin/productbuild here as well (thx to DesignatedNerd)
  8. "Save Changes"

Keychain 2

Hope one of this does trick for you!


Update (4/22/16):

I just found a very nice explanation about the whole code sign process (it's really worth reading): https://www.objc.io/issues/17-security/inside-code-signing/

Changing the URL in react-router v4 without using Redirect or Link

Try this,

this.props.router.push('/foo')

warning works for versions prior to v4

and

this.props.history.push('/foo')

for v4 and above

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Saving ssh key fails

Your method should work fine on a Mac, but on Windows, two additional steps are necessary.

  1. Create a new folder in the desired location and name it ".ssh." (note the closing dot - this will vanish, but is required to create a folder beginning with ".")
  2. When prompted, use the file path format C:/Users/NAME/.ssh/id_rsa (note no closing dot on .ssh).

Saving the id_rsa key in this location should solve the permission error.

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

C# list.Orderby descending

list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();

Which works for me to show the time sorted in descending order.

Pass array to where in Codeigniter Active Record

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

http://msdn.microsoft.com/en-us/library/ms186862.aspx

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

How to perform Unwind segue programmatically?

bradleygriffith's answer was great. I took step 10 and made a screenshot for simplification. This is a screenshot in Xcode 6.

  1. Control-drag from the orange icon to the red Exit icon to create an unwind without any actions/buttons in the view.

enter image description here

  1. Then select the unwind segue in the sidebar:

enter image description here

  1. Set a Segue Identifier string:

enter image description here

  1. Access that identifier from code:
[self performSegueWithIdentifier:@"unwindIdentifier" sender:self];

database attached is read only

Giving the sql service account 'NT SERVICE\MSSQLSERVER' "Full Control" of the database files

If you have access to the server files/folders you can try this solution that worked for me:

SQL Server 2012 on Windows Server 2008 R2

  1. Right click the database (mdf/ldf) file or folder and select "Properties".
  2. Select "Security" tab and click the "Edit" button.
  3. Click the "Add" button.
  4. Enter the object name to select as 'NT SERVICE\MSSQLSERVER' and click "Check Names" button.
  5. Select the MSSQLSERVER (RDN) and click the "OK" button twice.
  6. Give this service account "Full control" to the file or folder.
  7. Back in SSMS, right click the database and select "Properties".
  8. Under "Options", scroll down to the "State" section and change "Database Read-Only" from "True" to "False".

show all tables in DB2 using the LIST command

select * from syscat.tables where type = 'T'

you may want to restrict the query to your tabschema

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

What's the difference between text/xml vs application/xml for webservice response

According to this article application/xml is preferred.


EDIT

I did a little follow-up on the article.

The author claims that the encoding declared in XML processing instructions, like:

<?xml version="1.0" encoding="UTF-8"?>

can be ignored when text/xml media type is used.

They support the thesis with the definition of text/* MIME type family specification in RFC 2046, specifically the following fragment:

4.1.2.  Charset Parameter

   A critical parameter that may be specified in the Content-Type field
   for "text/plain" data is the character set.  This is specified with a
   "charset" parameter, as in:

     Content-type: text/plain; charset=iso-8859-1

   Unlike some other parameter values, the values of the charset
   parameter are NOT case sensitive.  The default character set, which
   must be assumed in the absence of a charset parameter, is US-ASCII.

   The specification for any future subtypes of "text" must specify
   whether or not they will also utilize a "charset" parameter, and may
   possibly restrict its values as well.  For other subtypes of "text"
   than "text/plain", the semantics of the "charset" parameter should be
   defined to be identical to those specified here for "text/plain",
   i.e., the body consists entirely of characters in the given charset.
   In particular, definers of future "text" subtypes should pay close
   attention to the implications of multioctet character sets for their
   subtype definitions.

According to them, such difficulties can be avoided when using application/xml MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

Multiple -and -or in PowerShell Where-Object statement

You're using curvy-braces when you should be using parentheses.

A where statement is kept inside a scriptblock, which is defined using curvy baces { }. To isolate/wrap you tests, you should use parentheses ().

I would also suggest trying to do the filtering on the remote computer. Try:

Invoke-Command -computername SERVERNAME {
    Get-ChildItem -path E:\dfsroots\datastore2\public |
    Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

std::enable_if to conditionally compile a member function

One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.

template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};

template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};

template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
    typedef FooImpl<T, boost::is_integer<T> > inherited;

    // you will need to use "inherited::" if you want to name any of the 
    // members of those inherited classes.
};

The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.

Ex:

template<class T, bool condition> class Goo;
// repeat pattern above.

template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
    typedef Goo<T, boost::test<T> > inherited:
    // etc. etc.
};

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

UPDATE

From later versions, there is no need to manually install gulp-util.

Check the new getting started page.

If you still hit this problem try reinstalling your project's local packages:

rm -rf node_modules/
npm install

OUTDATED ANSWER

You also need to install gulp-util:

 npm install gulp-util --save-dev

From gulp docs- getting started (3.5):

Install gulp and gulp-util in your project devDependencies

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to rollback a specific migration?

In Addition

When migration you deployed long ago does not let you migrate new one.

What happened is, I work in a larger Rails app with more than a thousand of migration files. And, it takes a month for us to ship a medium-sized feature. I was working on a feature and I had deployed a migration a month ago then in the review process the structure of migration and filename changed, now I try to deploy my new code, the build failed saying

ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "my_new_field" of relation "accounts" already exists

none of the above-mentioned solutions worked for me because the old migration file was missing and the field I intended to create in my new migration file already existed in the DB. The only solution that worked for me is:

  1. I scped the file to the server
  2. I opened the rails console
  3. I required the file in the IRB session
  4. then AddNewMyNewFieldToAccounts.new.down

then I could run the deploy build again.

Hope it helps you too.

How to change the text of a button in jQuery?

    $( "#btnAddProfile" ).on( "click",function(event){
    $( event.target ).html( "Save" );
});

&& (AND) and || (OR) in IF statements

Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.

An interesting fact is that Java also uses the & and | as logic operands (they are overloaded, with int types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.

Can you run GUI applications in a Docker container?

Yet another answer in case you already built the image:

  1. invoke docker w/o sudo (How to fix docker: Got permission denied issue)

  2. share the same USER & home & passwd between host and container share (tips: use user id instead of user name)

  3. the dev folder for driver dependent libs to work well

  4. plus X11 forward.

    docker run --name=CONTAINER_NAME --network=host --privileged \
      -v /dev:/dev \
      -v `echo ~`:/home/${USER} \
      -p 8080:80 \
      --user=`id -u ${USER}` \
      --env="DISPLAY" \
      --volume="/etc/group:/etc/group:ro" \
      --volume="/etc/passwd:/etc/passwd:ro" \
      --volume="/etc/shadow:/etc/shadow:ro" \
      --volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
      --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
      -it REPO:TAG /bin/bash

you may ask, whats the point to use docker if so many things are the same? well, one reason I can think of is to overcome the package depency hell (https://en.wikipedia.org/wiki/Dependency_hell).

So this type of usage is more suitable for developer I think.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Working on .Net Core 2.2 and 3.0 as of now.

To get the projects root directory within a Controller:

  • Create a property for the hosting environment

    private readonly IHostingEnvironment _hostingEnvironment;
    
  • Add Microsoft.AspNetCore.Hosting to your controller

    using Microsoft.AspNetCore.Hosting;
    
  • Register the service in the constructor

    public HomeController(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }
    
  • Now, to get the projects root path

    string projectRootPath = _hostingEnvironment.ContentRootPath;
    

To get the "wwwroot" path, use

_hostingEnvironment.WebRootPath

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Extract specific columns from delimited file using Awk

Others have answered your earlier question. For this:

As an addendum, is there any way to extract directly with the header names rather than with column numbers?

I haven't tried it, but you could store each header's index in a hash and then use that hash to get its index later on.

for(i=0;i<$NF;i++){
    hash[$i] = i;
}

Then later on, use it:

j = hash["header1"];
print $j;

Inserting into Oracle and retrieving the generated sequence ID

There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:

insert into table(batch_id, ...) values(my_sequence.nextval, ...)

...to return the next number. To find out the last created sequence nr (in your session), you would use:

my_sequence.currval

This site has several complete examples on how to use sequences.

Running a script inside a docker container using shell script

You can run a command in a running container using docker exec [OPTIONS] CONTAINER COMMAND [ARG...]:

docker exec mycontainer /path/to/test.sh

And to run from a bash session:

docker exec -it mycontainer /bin/bash

From there you can run your script.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Try to create an javax.mail.Authenticator Object, and send that in with the properties object to the Session object.

Authenticator edit:

You can modify this to accept a username and password and you can store them there, or where ever you want.

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {

    super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username, password);
    }

    return null;
}

In your class where you send the email:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties, authenticator));

How do you Make A Repeat-Until Loop in C++?

do
{
  //  whatever
} while ( !condition );

Importing two classes with same name. How to handle?

I hit this issue when, for example, mapping one class to another (such as when switching to a new set of classes to represent person data). At that point, you need both classes because that is the whole point of the code--to map one to the other. And you can't rename the classes in either place (again, the job is to map, not to go change what someone else did).

Fully qualified is one way. It appears you can't actually include both import statements, because Java gets worried about which "Person" is meant, for example.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I am just adding this answer for an awkward situation from DB provider.

what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.

so please check in the configuration settings for database status which may help you.

Autoplay an audio with HTML5 embed tag while the player is invisible

"Sensitive" era

Modern browsers today seem to block (by default) these autoplay features. They are somewhat treated as pop-ops. Very intrusive. So yeah, users now have the complete control on when the sounds are played. [1,2,3]

HTML5 era

<audio controls autoplay loop hidden>
    <source src="audio.mp3" type="audio/mpeg">
</audio>

Early days of HTML

<embed src="audio.mp3" style="visibility:hidden" />

References

  1. Jer Noble, New <video> Policies for iOS, WebKit, link
  2. Allow or block media autoplay in Firefox, FireFox Help, link
  3. Mounir Lamouri, Unified autoplay, Chromium Blog, link
  4. Embedded content, World Wide Web Consortium, link

How to create .pfx file from certificate and private key?

You need to use the makecert tool.

Open a command prompt as admin and type the following:

makecert -sky exchange -r -n "CN=<CertificateName>" -pe -a sha1 -len 2048 -ss My "<CertificateName>.cer"

Where <CertifcateName> = the name of your cert to create.

Then you can open the Certificate Manager snap-in for the management console by typing certmgr.msc in the Start menu, click personal > certificates > and your cert should be available.

Here is an article.

https://azure.microsoft.com/documentation/articles/cloud-services-certs-create/

Where should I put <script> tags in HTML markup?

Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).

How to order by with union in SQL?

Order By is applied after union, so just add an order by clause at the end of the statements:

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like '%a%'
Order By name

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake