text:
Q: ORA-01031: insufficient privileges as sysdba for sys (even after giving orapwd command) I have installed an oracle 11g instance on a linux machine. After doing a DB bounce by issuing shutdown immediate and startup. Not able to login as sys/password@sid as sysdba. Even issued a
orapwd file=orapwsid  password=password entries=30 force=y

command, which created a pwd file also.
But still not able to login as sys. I can connect to the DB by scott and other users created but not as a sysdba.
Request you to help me.

A: I got into same issue but did not know that I have to switch to oracle user to get dba access.
$ cd ORACLE_HOME/xe/bin
$ ls -la oracle
-rwsr-s--x 1 oracle dba 165700472 Aug 28  2011 oracle
$ su oracle
$ sqlplus sys as sysdba

You should be able to login without any issues

A: Make sure you are a dba!
[bb@limbo] ~/ $ . oraenv
ORACLE_SID = [XE] ? XE
ORACLE_BASE environment variable is not being set since this
information is not available for the current user ID bb.
You can set ORACLE_BASE manually if it is required.

[bb@limbo] ~/ $ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Fri Jan 16 19:02:11 2015

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

sys@XE> exit

Disconnected from Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

[bb@limbo] ~/ $ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Fri Jan 16 19:05:56 2015

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

ERROR:
ORA-01031: insufficient privileges

Enter user-name:
[bb@limbo] ~/ $ su -c "usermod -G dba bb"

Password:

[bb@limbo] ~/ $ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Fri Jan 16 19:06:29 2015

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

sys@XE>

A: I managed to resolved this issue by making sure the instance name case sensitive in listener file. Also the orapw file. If the SID are small case, I make sure all related files using the smaller case intance name.

A: > $ORACLE_HOME/bin/sqlplus as sysdba

this would work if your $ORACLE_HOME is set correctly
to check your $ORACLE_HOME run
> echo $ORACLE_HOME

this will display oracle home path


text:
Q: How to set default Save as type option to xlsx while using radgrid ExportToExcel() I have a radgrid, whose data i am exporting to excel (xls) format using radGrid.MasterTableView.ExportToExcel(), export is working as expected, but when I open the exported xls file and click "Save as", the "Save as type:" is set to "Web Page(.htm.html)", it is expected to be "Excel Workbook(*.xlsx)". The export code is as below,
        radGrid.ExportSettings.FileName = "Export";
        radGrid.ExportSettings.HideStructureColumns = true;
        radGrid.ExportSettings.OpenInNewWindow = true;
        radGrid.ExportSettings.ExportOnlyData = true;
        radGrid.MasterTableView.GroupsDefaultExpanded = true;
        radGrid.MasterTableView.Caption = string.Empty;
        radGrid.MasterTableView.ExportToExcel();

This is the save as type being selected - Web Page(.htm.html)
Please suggest.Thank you.

A: *

*Try setting the desired format as well through radGrid.ExportSettings.Excel.Format

*Compare your setup with the demo: http://demos.telerik.com/aspnet-ajax/grid/examples/functionality/exporting/excel-export/defaultcs.aspx

*Try clearing the response before export
radGrid.Page.Response.ClearHeaders();
radGrid.Page.Response.Cache.SetCacheability(HttpCacheability.Private);
radGrid.MasterTableView.ExportToExcel();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java button's appearance style during holding down // plain green button
flatButton.setBorderPainted (false);
flatButton.setBackground (Color.green);
flatButton.setSize (100, 75);

While holding the button, its color change to blue.
How to make keep green color during holding down?

A: flatButton.setContentAreaFilled( false );


text:
Q: XPath not working in JQuery selector (JQuery version 1.7.1) Below is a jQuery selector that works, and the value is set correctly into the text box.  Why doesn't the XPath code within the jQuery selector work?  I thought jQuery supported XPath.
jQuery code working:
$('html > body > form > div:nth-child(4) > label > input').val('hello world');

jQuery code not working:
$('/html/body/form/div[4]/label/input[1]').val('hello world');

Documentation here:
http://docs.jquery.com/DOM/Traversing/Selectors
... search for this code in the documentation above .... $("/html/body//p")

A: jQuery does not support XPath syntax for selectors out of the box anymore.
If you look at that documentation you link to, you'll see it's for version 1.1.2, something from more than 5 years ago. It also says, in a great big red box with centered text:

This is an old version of the Selectors API:
View the Current API

A: When the Xpath selectors were removed (in JQuery 1.2) the functionality was moved to a plugin, http://archive.plugins.jquery.com/project/xpath


text:
Q: Connecting to SQL Server over network using ADO from Excel VBA I need to connect to a SQL Server DB running on my laptop from another computer on a network. I am doing this both from a C# app as well as in a VBA macro. Both run perfectly on my laptop and the C# app runs perfectly over the network. However I cannot connect using VBA over the network. This is my connection string:
ConnectionString = "Driver={SQL Server};Server=MY-LAPTOP; DAtabase=SAFEXlive; UID = MyUsername; PWD=MyPassword"
Aside from the 'Driver={SQL Server}' this is the same as the connection string I am using in the C# app which works.
I am then using the following code (With a reference to Microsoft ActiveX Data Objects 6.0 Library in VBE) to open the connection:
Dim oConnection As Connection
Set oConnection = New Connection
oConnection.ConnectionString = strConnectionString
oConnection.Open

This works correctly if I run it on my laptop but if I run it on another computer on the network I get the error: "Run-time error '-2147217843 (80040e4d) [Microsoft][ODBC Server Driver][SQL Server]Login failed for user..." and the user it specifies it the windows log in for the computer.
Are there some security settings I need to set in code or in excel? Or am I constructing the connection string incorrectly? What am I doing wrong?

A: Solved. The answer is rather infuriating. The problem is in fact with the connection string, with the UID. Believe it or not changing ...UID= MyUsername;... to ..UID=MyUsername;..., i.e. removing the space character, was all it took! Thanks for suggestions though.

A: Try this Connection string,
ConnectionString = "Provider=SQLOLEDB;Data Source=MY-LAPTOP;Initial Catalog=SAFEXlive;User ID=MyUsername;Password=MyPassword"

Is this an AD Domain login? Make sure you have appended the domain to the username e.g, domain\user .
I suggest using integrated security instead of this.


text:
Q: Post Json and audio file with php (curl) to a laravel API I am posting json and audio file to my api built on laravel with the code below
     $endPoint = 'http://localhost:9000/api/audio/send';
     $apiKey = 'anvx7P7ackndaD8MvXlufSaG4uJ901raoWIwMPGZ93dkH';
     $url = $endPoint . '?key=' . $apiKey;
     $curlFile = new \CURLFile('/Users/desktop/myapp/public/Voice/aaaah.wav');
     $data = array("request" =>
     json_encode(array("test" => "First audio ",'recipient' =>['442342342', '35345242'])) . ";
     type=application/json","file" => "@d8696c304d09eb1.wav;type=audio/wav");

                $ch = curl_init();
                $headers = array();
                $headers[] = "Content-Type: application/json";
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                $result = curl_exec($ch);
                $result = json_decode($result, TRUE);
                curl_close($ch);
            return $result;

When i submit my json to the api, it returns null from the api. Meaning no data is being posted to my api. Is there any error with how i am posting my json and audio file to the laravel api please?
PS: Beginner in PHP

A: You cannot post files in a JSON!.
A normal POST request is needed (the one that gets generated from the <form> element) for posting a file.
If you are bound to send the file using JSON, base64_encode it and send. On the other end though, the server will need to base64_decode it first.


text:
Q: Why not all labels are showing in matplotlib legend? I am trying to visualize feature embeddings of dataset with 20 classes in a 2-d space using t-sne method, but my matplotlib legend is missing most of the labels. It should show all the labels in y but only showing first 7 labels. What I am missing here?

Here is my code:

tsne_model = TSNE(n_iter=2000, n_components=2, random_state=123, perplexity=50)
tsne_transformed = tsne_model.fit_transform(pca_result_50)

sns.set_style('white')
f = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
sc = plt.scatter(tsne_transformed[:, 0], tsne_transformed[:, 1], c=labels, cmap='tab20')
handles, _ = sc.legend_elements(prop='colors')

y = ['0 - Original', '1 - Original', '2 - Original', '3 - Original', '4 - Original', '5 - Original',
'6 - Original', '7 - Original', '8 - Original', '9 - Original','0 - Generated', '1 - Generated',
'2 - Generated', '3 - Generated', '4 - Generated', '5 - Generated',
'6 - Generated', '7 - Generated', '8 - Generated', '9 - Generated']

plt.legend(handles, y, loc='best')

plt.xlabel('t-sne 1')
plt.ylabel('t-sne 2')

plt.xlim(-25, 25)
plt.ylim(-25, 25)
ax.axis('tight')


text:
Q: Combine scrolling of Horizontal recyclerview which is inside Vertical RecyclerAdapter Here parent having vertical recyclerview  scroll and child having horizontal recyclerview ,I just wants to scroll all child together not individually currently child scrolling individually that's a problem I am facing .I hope I  explained well .If anyone have some suggestion or solution please provide I shall be really thankful to you.Check attached image
`
Parent view
     <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/appointments_recycler"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:paddingLeft="@dimen/_10ssp"
                    android:paddingRight="@dimen/_10ssp">

                </android.support.v7.widget.RecyclerView>
 </RelativeLayout>

Adapter View containing horizontal recyclerview.
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

            <com.app.barber.views.CustomTextView
                android:id="@+id/time_slot"
                android:layout_width="@dimen/_40ssp"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:paddingTop="@dimen/_2sdp"
                android:paddingRight="@dimen/_2sdp"
                android:paddingBottom="@dimen/_2sdp"
                android:text="9:00 AM"
                android:textSize="@dimen/_10ssp"
                android:textStyle="bold" />

        <View
            android:layout_width="0.001sp"
            android:layout_height="match_parent"
            android:background="@color/color_light_grey_blue" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/days_recyclar"
                android:layout_width="@dimen/_500sdp"
                android:layout_height="wrap_content"
                android:visibility="visible" />

        </LinearLayout>
    </LinearLayout>


text:
Q: Getting data from a task to a connection with asyncio So this should be fairly simple, i have a client that connects to a server, and it can receive messages from the server just fine. However i need to be able to send messages to the server. I am using asyncio to handle these asynchronously but i have a problem with that. How do i get the user input to my client so it can use its transport to send the data up to the server. Heres the code.
import asyncio, zen_utils, json
from struct import *

class ChatClient(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        self.address = transport.get_extra_info('peername')
        self.data = b''
        print('Accepted connection from {}'.format(self.address))

        self.username = b'jacksonm'
        json_name = b'{"USERNAME": "'+self.username+b'"}'
        length = len(json_name)
        code_len = pack(b'!I', length)
        message = code_len + json_name
        self.json_loaded = False
        self.next_length = -1
        self.transport.write(message)

    def data_received(self, data):
        self.data += data

        if (self.json_loaded == False):
            self.compile_server_data(data)
        elif(self.json_loaded):
            if (len(self.data) > 4 and self.next_length == -1):
                self.next_length = self.data[:4]
                self.next_length = unpack(b'!I', self.next_length)[0]
                print("LENGTH: ", self.next_length)

            elif (len(self.data) >= self.next_length):
                self.data = self.data[4:]
                print("MESSAGE: ", self.data)
                self.next_length = -1

    def compile_server_data(self, data):
        if (self.data.find(b'}') != -1):
            start_index = self.data.find(b'{')
            end_index = self.data.find(b'}')

            self.json_data = self.data[start_index:end_index + 1]
            self.data = self.data[end_index + 1:]

            self.json_data = self.json_data.decode('ascii')
            self.json_data = json.loads(self.json_data)
            self.json_loaded = True

            self.print_server_status()

    def send_message(self, message):
        message = message.encode('ascii')
        length = len(message)
        code_len = pack(b'!I', length)
        message = code_len + message

    def parse_message(self, raw_message):
        message = {}
        message['SRC'] = self.username
        message['DEST'] = b'ALL'
        message['TIMESTAMP'] = int(time.time())
        message['CONTENT'] = b'test_message'

        json_message = json.loads(message)
        print (json_message)

    def print_server_status(self):
        print ("USERS:")
        for user in self.json_data["USER_LIST"]:
            print(user)
        print()
        print("MESSAGES:")
        for message in self.json_data["MESSAGES"][-10:]:
            print ("From: ", message[0], "     ", "To: ", message[1])
            print ("Message: ", message[3])
            print()

    def get_inital_data(self):
        pass

    def connection_lost(self, exc):
        if exc:
            print('Client {} error: {}'.format(self.address, exc))
        elif self.data:
            print('Client {} sent {} but then closed'
                  .format(self.address, self.data))
        else:
            print('Client {} closed socket'.format(self.address))

@asyncio.coroutine
def handle_user_input(loop):
    """reads from stdin in separate thread

    if user inputs 'quit' stops the event loop
    otherwise just echos user input
    """
    while True:
        message = yield from loop.run_in_executor(None, input, "> ")
        if message == "quit":
            loop.stop()
            return
        print(message)

if __name__ == '__main__':
    address = zen_utils.parse_command_line('asyncio server using callbacks')
    loop = asyncio.get_event_loop()
    coro = loop.create_connection(ChatClient, *address)
    server = loop.run_until_complete(coro)

    # Start a task which reads from standard input
    asyncio.async(handle_user_input(loop))

    print('Listening at {}'.format(address))
    try:
        loop.run_forever()
    finally:
        server.close()
        loop.close()

A: This is working in my tests by changing one line, using Python 3.4:
Change the run_until_complete() call to receive a (transport,protocol) pair instead of a single value.
Specifically, change server = loop.run_until_complete(coro) to transport, protocol = loop.run_until_complete(coro), because the call executes the coroutine and returns its value which is a pair of items.  The first item is the server object, and the second entry is a protocol object which is an instance of ChatClient.
Run the server then the client in different command windows.
Client code:
import asyncio, json #, zen_utils
from struct import *

class ChatClient(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        self.address = transport.get_extra_info('peername')
        self.data = b''
        print('Accepted connection from {}'.format(self.address))

    def data_received(self, data):
        pass

    def compile_server_data(self, data):
        pass

    def send_message(self, message):
        message = message.encode('ascii')
        self.transport.write(message)

    def parse_message(self, raw_message):
        pass

    def print_server_status(self):
        pass

    def get_inital_data(self):
        pass

    def connection_lost(self, exc):
        if exc:
            print('Client {} error: {}'.format(self.address, exc))
        elif self.data:
            print('Client {} sent {} but then closed'
                  .format(self.address, self.data))
        else:
            print('Client {} closed socket'.format(self.address))

@asyncio.coroutine
def handle_user_input(loop, protocol):
    """reads from stdin in separate thread

    if user inputs 'quit' stops the event loop
    otherwise just echos user input
    """
    while True:
        message = yield from loop.run_in_executor(None, input, "> ")
        if message == "quit":
            loop.stop()
            return
        print(message)
        protocol.send_message(message)

if __name__ == '__main__':
    address = "127.0.0.1"
    port = 82

    loop = asyncio.get_event_loop()
    coro = loop.create_connection(ChatClient, address, port) #*address
    transport, protocol = loop.run_until_complete(coro)

    # Start a task which reads from standard input
    asyncio.async(handle_user_input(loop,protocol))

    print('Listening at {}'.format(address))
    try:
        loop.run_forever()
    finally:
        transport.close()
        loop.close()

Server code, credit goes to this site:
import socket

host = ''        # Symbolic name meaning all available interfaces
port = 82     # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    if not data: break

    print( 'Received ', repr(data) )
    if repr(data)=="stop": break

    conn.sendall(data)
conn.close()


text:
Q: Embedding Javascript in Javascript (I'm serious)? I'm working on a project where players can place graphical objects on a website and animate them with scripts. As the scripts are going to be shared to all participating clients, the scripting environment must be sandboxed, so that users can't ultimately destroy other users experience for all parts of the page.
It is crucial that the scripts can access shared visual content. Therefore I can't isolate them in iframes entirely - besides that I'm wondering if there's a smoother approach to separate contexts.
I have been dabbling with a native version, where I used separate contexts using the V8 javascript engine, but now I want to bring this to the browser - even if it's just Google Chrome only.
Got any ideas?

A: Sandboxing JavaScript is inherently difficult, chances are that the script will manage to break out no matter how hard you try. A better course of action might be loading the scripts into an iframe without direct access to the main frame and allowing it to communicate with the main frame via window.postMessage(). You could then define an API that the frame is allowed to use this way without being given too much power.
Edit: Same thing is possible with Web Workers as noted in Is It Possible to Sandbox JavaScript Running In the Browser?, browser support for web workers isn't quite as widespread as for window.postMessage() however (compare http://caniuse.com/#search=postMessage and http://caniuse.com/#search=workers).


text:
Q: How to send structure using named pipe I´m planning to use named pipes to communicate between two process but I´d like to send a simple structure from one program to other (in the same machine):
typedef struct Env_var      {
  string Objcet;
  string Attrib;
  double  value;
  } Var_amb;

How can I send it and receive it correctly on the other side ?
I use the followuing code to write:
 DWORD numBytesWritten = 0;
    result = WriteFile(
        pipe, // handle to our outbound pipe
       buffer, // data to send
       sizeof(buffer), // length of data to send (bytes)
         &numBytesWritten, // will store actual amount of data sent
         NULL // not using overlapped IO
      );

Any help I´d appreciate in advance.
Thanks
andre.nudel@gmail.com


text:
Q: Autofac using Constructor I use unit of work pattern with entityFramework code first. Now I want to use Autofac to register UnitOfWork, Repositories and My dbContext.
This Is my UnitOfWork code:
public class UnitOfWork : IUnitOfWork
{
    private readonly DbContext _context;

    public UnitOfWork(DbContext context)
    {
        _context = context;

        Contact = new ContractRepository(context);
    }

    public void Dispose()
    {
        _context.Dispose();
        GC.SuppressFinalize(_context);
    }

    public IContactRepository Contact { get; private set; }

    public int Complete()
    {
        return _context.SaveChanges();
    }
}

and this is my repository:
public class Repository<Entity> : IRepository<Entity> where Entity : class
{
    protected readonly DbContext _noteBookContext;
    public Repository(DbContext noteBookContext)
    {
        _noteBookContext = noteBookContext;
    }
    public void Add(Entity entity)
    {
        _noteBookContext.Set<Entity>().Add(entity);
    }
}

and this is one of my repositories:
public  class ContractRepository: Repository<Contact>,IContactRepository
{
    public ContractRepository(DbContext noteBookContext) : base(noteBookContext)
    {

    }

    public DbContext NotebookContext
    {
        get
        {
            return _noteBookContext;
        }
    }
}

and this is my db context class:
public class NoteBookContext:DbContext
{
    public NoteBookContext(string connectionstring):base(connectionstring)
    {

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ContactConfig());
        modelBuilder.Configurations.Add(new PhoneConfig());
        modelBuilder.Configurations.Add(new PhoneTypeConfig());
        modelBuilder.Configurations.Add(new GroupConfig());
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<Phone> Phones { get; set; }

    public DbSet<Group> Groups { get; set; }

    public DbSet<PhoneType> PhoneTypes { get; set; }
}

Now I want to register UnitOfWork with constructor (a constructor like this: )
var uow = new UnitOfWork(new NotebookdbContext("connectionstring"));

Note that NoteBookContext is my entity framework model.
I write registration but I got Error:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
       .As<DbContext>();
builder.RegisterType<UnitOfWork>()
       .UsingConstructor(typeof(DbContext))
       .As<IUnitOfWork>();

builder.RegisterGeneric(typeof(Repository<>))
       .As(typeof(IRepository<>))
       .InstancePerLifetimeScope();

Container container = builder.Build();

This is my error:

An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
  Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'DataLayer.NoteBookContext' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.String connectionstring' of
  constructor 'Void .ctor(System.String)'.

Edit 2 :
after help from Cyril Durand's answer I write following registering config:
 var builder = new ContainerBuilder();
        builder.RegisterType<ConnectionStringProvider>().As<IConnectionStringProvider>();
        builder.RegisterType<NoteBookContext>().As<DbContext>().WithParameter((pi, c) => pi.Name == "connectionstring",
                                                                              (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);
        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
        builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

and In my code :
using (var scope = DependencyInjection.Container.BeginLifetimeScope())
        {
            var ConnectionString = scope.Resolve<IConnectionStringProvider>();
            ConnectionString.ConnectionString = "Context";

            var uw = scope.Resolve<IUnitOfWork>();
            var a =uw.Contact.GetAll();

        }

but I got Error again:

An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: An exception was thrown while invoking the
  constructor 'Void .ctor(System.String)' on type 'NoteBookContext'.

can everyone help me?

A: The error message :

An unhandled exception of type Autofac.Core.DependencyResolutionException occurred in Autofac.dll
  Additional information: None of the constructors found with Autofac.Core.Activators.Reflection.DefaultConstructorFinder on type DataLayer.NoteBookContext can be invoked with the available services and parameters:
Cannot resolve parameter System.String connectionstring of constructor Void .ctor(System.String).

tells you that Autofac can't create a NoteBookContext because it can't resolve a parameter named connectionstring of type String.
Your NoteBookContext implementation needs a connectionstring, Autofac can't know it without you telling it. When you register the NoteBookContext you will have to specify the connectionstring :
builder.RegisterType<NoteBookContext>()
       .As<DbContext>()
       .WithParameter("connectionstring", "XXX");

Another solution with dynamic resolution and a IConnectionStringProvider interface :
public interface IConnectionStringProvider
{
    public String ConnectionString { get; }
}

and registration :
builder.RegisterType<ConnectionStringProvider>()
       .As<IConnectionStringProvider>()
       .InstancePerLifetimeScope();
builder.RegisterType<NoteBookContext>()
       .As<DbContext>()
       .WithParameter((pi, c) => pi.Name == "connectionstring",
                      (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
       .InstancePerLifetimeScope();

A: It's hard to tell without seeing error. But You don't need to use UsingConstructor.
//Make DbContext per request, if your app is web app (which has http request).
builder.RegisterType<NoteBookContext>()
       .As<DbContext>().WithParameter("connectionstring","ConnectionStringValue").InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();

builder.RegisterGeneric(typeof(Repository<>))
       .As(typeof(IRepository<>))
       .InstancePerLifetimeScope();

Container = builder.Build();

A: Is there a reason you want to pass the connection string to your context? Create an interface for your unitofwork and do something like this:
public class NoteBookContext:DbContext
{
    //Change connectionstring below with the name of your connection string in web.config
    public NoteBookContext():base("name=connectionstring")
    {

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ContactConfig());
        modelBuilder.Configurations.Add(new PhoneConfig());
        modelBuilder.Configurations.Add(new PhoneTypeConfig());
        modelBuilder.Configurations.Add(new GroupConfig());
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<Phone> Phones { get; set; }

    public DbSet<Group> Groups { get; set; }

    public DbSet<PhoneType> PhoneTypes { get; set; }
}

And register like this:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
       .As<DbContext>()
       .InstancePerLifetimeScope();

builder.RegisterType<UnitOfWork>()
       .As<IUnitOfWork>()
       .InstancePerLifetimeScope();

builder.RegisterGeneric(typeof(Repository<>))
       .As(typeof(IRepository<>))
       .InstancePerLifetimeScope();

Container container = builder.Build();


text:
Q: Display a number of textboxes based on count and insert into database Asp.net C# I'm trying to display a set of textboxes based on the amount that was selected from from a drop down list. Say I select 5 then it should display 5 textboxes; the textbox is displayed however on page load it clears the boxes. Additionally I would like to enter those data entered into database table.
protected void ddlCount_SelectedIndexChanged(object sender, EventArgs e)
{
    ContentPlaceHolder1.Controls.Clear();
    for (int i = 0; i < Convert.ToInt32(ddlCount.SelectedItem.Value); i++)
    {

        TextBox tx = new TextBox();
        tx.ID = "tx" + i;
        ContentPlaceHolder1.Controls.Add(tx);
        ContentPlaceHolder1.Controls.Add(new LiteralControl("     "));
    }
}

Button Click
  protected void btnPrint_Click(object sender, EventArgs e)
   foreach (Control ctrl in ContentPlaceHolder1.Controls)
                    {
                        SqlCommand comm = new SqlCommand();
                        {
                        Label ll = (Label)ContentPlaceHolder1.FindControl("Label5");
                        comm.CommandType = CommandType.StoredProcedure;
                            comm.CommandText = "PP_CreateUserNumber";
                            comm.Connection = con;
                            comm.Parameters.Add("@sealNumber", SqlDbType.NVarChar).Value = 11;
                            comm.ExecuteNonQuery();
                        }
                    }
 }


text:
Q: How do I report a bug in te language support preferences? I installed my system using US English, but as my native tongue is Norwegian (Bokmål) I would like to use that on a daily basis on my system. More important, I want to use the Norwegian number formats.
However, in the language support settings, only Norwegian Nynorsk is available. I know there is Norwegian Bokmål support, as my home computer is installed with it. But it's not available from the "install/remove languages" dialog.

A: try this in a terminal:
sudo apt-get install language-pack-nb language-pack-nb-base language-pack-gnome-nb language-pack-gnome-nb-base

this installs four packages. the latter two are only for the case you are using gnome. For KDE e.g. gnome should be replaced by kde.
After that you can hopefully select Bokmal language support.


text:
Q: Autoclicker on Java(Android Studio) enter image description here
2 buttons, 2 counters for each of them, and switch button.
When switch is ON it needs automatically click on any button(random)
sleep = 100
It'be really great if someone could help with that.
Here is the code of MainActivity:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button button1;
    private Button button2;

    private TextView text2;
    private Switch switch1;
    private TextView text4;
    private TextView text3;
    private TextView text5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = findViewById(R.id.buttonRed);
        button2 = findViewById(R.id.buttonBlue);

        text2 = findViewById(R.id.textViewBlueScore);
        switch1 = findViewById(R.id.switch1);
        text3 = findViewById(R.id.textViewRedScore);

        final int[] text4 = {0};
        final int[] text5 = {0};

        View.OnClickListener onClickListenerRed = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text5[0] += 1;
                text3.setText(text5[0] + "");
            }
        };
        View.OnClickListener onClickListenerBlue = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text4[0] += 1;
                text2.setText(text4[0] + "");
            }
        };
        button2.setOnClickListener(onClickListenerBlue);
        button1.setOnClickListener(onClickListenerRed);
    }
}

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button button1;
    private Button button2;

    private TextView text2;
    private Switch switch1;
    private TextView text4;
    private TextView text3;
    private TextView text5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = findViewById(R.id.buttonRed);
        button2 = findViewById(R.id.buttonBlue);

        text2 = findViewById(R.id.textViewBlueScore);
        switch1 = findViewById(R.id.switch1);
        text3 = findViewById(R.id.textViewRedScore);

        final int[] text4 = {0};
        final int[] text5 = {0};

        View.OnClickListener onClickListenerRed = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text5[0] += 1;
                text3.setText(text5[0] + "");
            }
        };
        View.OnClickListener onClickListenerBlue = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text4[0] += 1;
                text2.setText(text4[0] + "");
            }
        };
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int temp = new Random().nextInt()%2;
                View click  =temp == 0 ? button2 : button1;
                if (click != null)
                    click.performClick();
            }
        },100,100);

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked)
                    timer.cancel();

            }
        });
        button2.setOnClickListener(onClickListenerBlue);
        button1.setOnClickListener(onClickListenerRed);
    }
}

So i don't really get why it crashes
fffffffffffffffff

A: Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            int temp = new Random().nextInt()%2;
            View click  =temp == 0 ? button2 : button1;
            if (click != null)
                click.performClick();
        }
    },100,100);
    Switch sw;
    sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isChecked)
                timer.cancel();
            else
                //make timer work
        }
    });

just do it man.
Is this something you need?


text:
Q: странное поведение при долгом зажатии клавиши в консоли Вообщем, дело такое: пишу игру в консоли и там вроде бы все нормально происходит, при нажатии клавиши игрок передвигается со сменой кадров, при отжатии стоит с кадром стояния. Но происходит странная вещь: когда я нажимаю и удерживаю кнопку, то происходит вот что: игрок перемещается, затем застывает, а потом начинает спокойно перемещаться, пока я клавишу не отожму соре за качество

Так вот, я подумал, что это у меня какие-то проблемы в цикле. Решил наклипать более простой проект с одним персонажем-символом нуля, который тоже перемещается влево и вправо. Вот сам код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;

namespace test
{
    class player
    {
        public int x = 1;
        public int previousX = 1;
        public void SetPosition()
        {
            Console.SetCursorPosition(previousX, 5);
            Console.Write(' ');
            Console.SetCursorPosition(x, 5);
            Console.Write('0');
            previousX = x;
        }
    }
    class Program
    {
        static void Main()
        {
            Console.CursorVisible = false;

            player p1 = new player();
            p1.x = 1;
            p1.previousX = 1;

            while (true)
            {
                p1.SetPosition();

                while (Console.KeyAvailable == false) { }
                if (Console.KeyAvailable == true)
                    p1.x = ChangePlayerPossition(Console.ReadKey(true).Key, p1.x);
            }
        }

        // Изменение координат
        static int ChangePlayerPossition(ConsoleKey key, int x)
        {
            switch (key)
            {
                case ConsoleKey.LeftArrow:
                    if (x - 1 > 5) { x--; }
                    break;
                case ConsoleKey.RightArrow:
                    if (x + 1 < 70) { x++; }
                    break;
            }

            return x;
        }

    }
}

Может выглядит криво, не спорю. Я думал, что тут этой штуки не будет. Как бы не так

игрок передвигается на 1 позицию вперед, застывает, а потом начинает двигаться, пока не отожму клавишу...
Может тут дело в реализации и нужно в потоки лезть? Или тут уже ничего не поможет? Вам лично было бы нормально играть в игру с такой темой (как на первой гифке? (тип, может так оставить? :D))


text:
Q: Advantages and disadvantages of using Storyboarding? I've been writing iOS apps for a while now and gradually went from doing the UI entirely programmatically to using the Interface Builder intensively. I'm now thinking about using the new Storyboarding feature for some of my new projects, but I don't have enough experience or knowledge with it to calculate the advantages and disadvantages of doing so.
Can anybody give some examples or information about when using Storyboarding payed off and when it was a waste of time?

A: Another disadvantage with Storyboarding not mentioned is that merges can be very difficult if not impossible if there are conflicts.
Update: It also occurred to me that it puts logic in two places.  If your segue is not doing the right thing it might be because of an error in prepareForSegue or it might be because you named your segue incorrectly.  Doing things programmatically is, in the end, not that hard.

A: At the latest WWDC (2013) Apple Devs strongly recommend using storyboard and built in IB stuff to do most of your code for you instead of writing it by hand because you are much more likely to avoid deprecation and take advantage of feature updates via automated conversions.
The lone disadvantage is the difficulty in allowing git collaboration on storyboards, as there will be conflicts on virtually every commit.
If you are a solo programmer, you should always be using storyboards.

A: Advantages of Storyboarding

*

*It's cool - suave way to design interfaces

*Use of StoryBoardSegues to identify navigation/modal relationships

*If your app supports multiple devices, good way to organize different views (by storyboard file rather than naming, etc)

*Nice for prototyping

*Prototype UITableViewCell can save time

Disadvantages of Storyboarding

*

*It's a runtime feature, so I believe it is only available in iOS 5

*StoryBoardSegues are kind of rigid in my experience and you may make use of prepareForSegue a lot

*Like IB, not very friendly with other display engines and toolkits

*Makes it hard to share designs for a single view or set of views - you have to send all or nothing

These seem kind of superficial, I guess I haven't given it much thought... At first I was gung-ho about story boards, but now I've reverted to IB or even just programatic view configuration... The more I use them, the less I like them, and the more they feel like a gimmick/waste of time.
Edit
I wrote this answer a few years ago. I have left it the same as before for posterity, although some points are likely no longer relevant (ie the fact that it requires iOS 5+).
After some time, my opinion hasn't changed on storyboards. As others have mentioned, they're okay if you are working solo on an app with few views to manage, but they become a real pain with source control & collaboration. In addition, I prefer one-file-one-object, and storyboards obviously bundle stuff together (as does IB, but to a lesser extent).
If I were writing an app meant to be maintained for any serious length of time, I would go with programmatic view configuration over IB, but definitely IB over storyboards.

A: I have a similar background to you - I started with mostly building my iOS UI programmatically since IB was not really user-friendly, but lately decided to use IB more and more, since it is better for designing the UI and works fine for standard-elements.
With the new Xcode I switched to Storyboard, since they provide a full view of the application. It is possible to generate the complete UI (with all views) in a single File, which can be used for prototyping and which I can view my colleagues before writing the first code line. It is far better and easier than designing with photoshop or similar tools.
However if you use a lot of your own UI elements/controls or something using a different "engine" (cocos2d, OpenGL, etc.) it is usually better to generate the UI programmatically, since these "engines" are not really integrated with IB/Storyboards.

A: I have learn the storyboarding by following the tutorials from the raywenderlich's website and there is a lot of stuff about the storyboard.
Here is the link to site: http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
Advantages of storyboard:
1) Before you start developing app you can see all the screens of the app.
2) You can visually see the relationship between each screen.
3) It can help to reduce the amount of the code specially in case of UITableView you can use prototype cells and static cells to design your TableView in storyboard.
4) In case if you have to work on someone else code you can get the better understanding of the flow of the app by viewing storyboard in short time.
5) You can setup the user interface for iPhone 4 and iPhone 5 by applying the retina form factor from storyboard, without running the app again and again.
6) If you are doing client based work then some clients want to see the prototype of the app before start developing it, here storyboard helps you a lot.
Disadvantages of storyboard:
1) For storyboard you will need a big screen specially in case of iPad.
2) I also experience a difficulty while copying views from other apps to storyboard.
3) I also experience problems in storyboard when multiple developers work on the same project by using git repository.
By reading and understanding the advantages and disadvantages you can judge your self when to use storyboard.

A: One Word (DON'T)
One of the biggest disadvantages of storyboard aside from the git conflicts that make it impossible for two or more persons to work on it. but also if the project went so big and you have +40 screens , if you insane enough to move anything just one pixel in any view controller you have in the storyboard, you'll have a very huge compilation time, that you can build your app and make it run in more than 5 minutes, and of course don't let me start with archiving to give some one adhoc of the app .
after this painful experience I totally fell back to the oldy goldy great xib files and deleted the storyboard file in a huge fire celeberation .


text:
Q: PowerShell+MSI. How to release opened database? I have VB Script:
.....
Set oInstaller  = CreateObject("WindowsInstaller.Installer")
Set otempDB = oInstaller.OpenDatabase(sMsiFullPathTemp, 1)
.......
Set otempDB = Nothing

At this string it releases database: Set otempDB = Nothing.
I need to make PowerShell script like this VBS to work with MSI.
PowerShell:
....
function Invoke-Method ($Object, $MethodName, $ArgumentList) {
    return $Object.GetType().InvokeMember($MethodName, 'Public, Instance, InvokeMethod', $null, $Object, $ArgumentList)
}
$oInstaller = New-Object -ComObject WindowsInstaller.Installer
$otempDB = Invoke-Method $oInstaller OpenDatabase  @($tempmsi, 1)

But how I can release MSI database until script haven't finished work?
I mean something like: Set otempDB = Nothing
Could someone help me with it?
Thanks

A: you can always assign the variable to $null:
$otempDB = $null

However for COM objects this often results in the object just being shuffled off to limbo somewhere. Better is to explicitly relese the object and clean up the memory:
([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$otempDB) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Somewhere I came across a function for this some time ago (if someone knows who originally posted this function please leave a comment and I will attribute it). I use it pretty much any time that I work with COM objects:
function Release-Ref ($ref) {

    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()

}


text:
Q: url routing webforms conflict Im just getting into Global.asax and the way to do url routing in WebForms. Here Im having a bit of a conflict with my default.aspx and my other files.
I want all my files to have the friendly url ie. mysite.com/welcome/ etc and Im achieving this by doing:
routes.MapPageRoute("root_pages", "{file}/{*action}", "~/{file}.aspx");

by this I can write mysite.com/welcome.aspx into mysite.com/welcome/ and have a default action if I want. But then my conflict occurs between my default routing:
routes.MapPageRoute("default", "{*action}", "~/default.aspx");

I also want to access some action on my default.aspx - but it seems I cant when Im doing it like this?
It will pick the file line and go with that, so I cant do mysite.com/logout/ which is a function on my default.aspx page, it will ofcouse look for a file in this case.. Is there any other way to do what I want? So I can use both routes?
Hope you can help me out
Kind regards

A: It will always take the first route and go with it. In your case, it will look for logout.aspx which doesn't exist. The only option is to use the URL mysite.com/default/logout.
We can consider this as a limitation of URL Routing in WebForms.
You can check my blog series for URL Routing in Web forms at following URL.
http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-1.html
http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-2.html
There are more articles in this series.


text:
Q: Filter by index of nested array in javascript I have an array in javascript which contains a number of nested arrays
let data = [
  ["Apple","Fruit","Red"],
  ["Pear","Fruit","Green"],
  ["Orange","Fruit","Orange"],
  ["Carrot","Vegetable","Orange"],
  ["Pea","Vegetable","Green"],
  ["Pumpkin","Vegetable","Orange"]
]

From this array, I wish to create two new arrays. Arr1 is the unique food types (index2) and Arr2is the unique colors (Index 3).
My new arrays should be:
Arr1 = ["Fruit","Vegetable"]
Arr2 = ["Red","Green","Orange"]

I have managed to achieve this by using for each, where I've pushed every second object to an array. I then filter this new array for unique values. This is the code I'm using to do this:
var Foods = []
var Colors = []

for (var key in data) {
          Foods.push(data[key][1]);
}

for (var key in data) {
          Colors.push(data[key][2]);
}

let Arr1 = [...new Set(Foods)]
let Arr2 = [...new Set(Colors)]

console.log(Arr1)
console.log(Arr2)

Although this works well, as a javascript beginner, I thought there may be a more elegant way to achieve.
For example is it not possible to filter all the unique values of data with an index of [2]?

A: Reduce the array to two Sets, and then destructure the Sets, and spread each into the respective array:

const data = [["Apple","Fruit","Red"],["Pear","Fruit","Green"],["Orange","Fruit","Orange"],["Carrot","Vegetable","Orange"],["Pea","Vegetable","Green"],["Pumpkin","Vegetable","Orange"]]

const [s1, s2] = data.reduce((acc, arr) => {
  acc.forEach((s, i) => s.add(arr[i + 1]))

  return acc
}, [new Set(), new Set()])

const Arr1 = [...s1]
const Arr2 = [...s2]

console.log({ Arr1, Arr2 })

A: Your code is fine as it is, the only improvement would be to replace loops with map:
let foods  = [...new Set(data.map(d => d[1]))]
let colors = [...new Set(data.map(d => d[2]))]

There's absolutely no need to overcomplicate matters with reduce, destructuring and so on.
If you want it to look slightly more elegant, you can define two utility functions
const item = i => a => a[i]
const uniq = a => [...new Set(a)]

and then
let foods  = uniq(data.map(item(1)))
let colors = uniq(data.map(item(2)))

Another option:
const uniq = a => [...new Set(a)]
const zip = (...args) => args[0].map((_, i) => args.map(a => a[i]))

let [_, foods, colors] = zip(...data).map(uniq)

A: Create an object with foods and colors as keys and loop through inserting the appropriate element index each iteration

let data = [
  ["Apple","Fruit","Red"],
  ["Pear","Fruit","Green"],
  ["Orange","Fruit","Orange"],
  ["Carrot","Vegetable","Orange"],
  ["Pea","Vegetable","Green"],
  ["Pumpkin","Vegetable","Orange"]
]

const uniques = {
   foods:new Set(),
   colors: new Set()

}
data.forEach(a => uniques.foods.add(a[1]) && uniques.colors.add(a[2]) )

// just for demo logs
Object.entries(uniques).forEach(([k,set])=> console.log(k,':', ...set))

A: You could take a single loop and get the unique values for all items of the nested arrays.

const
    getUnique = array => array
        .reduce((r, a) => a.map((v, i) => (r[i] || new Set).add(v)), [])
        .map(s => [...s]),
    data = [["Apple", "Fruit", "Red"], ["Pear", "Fruit", "Green"], ["Orange", "Fruit", "Orange"], ["Carrot", "Vegetable", "Orange"], ["Pea", "Vegetable", "Green"], ["Pumpkin", "Vegetable", "Orange"]],
    [, types, colors] = getUnique(data);

console.log(types);
console.log(colors);


text:
Q: Function that prints reverse of a string/char array in C I am rather new to the C language right now and I am trying some practice on my own to help me understand how C works. The only other language I know proficiently is Java. Here is my code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * reverse(char word[]);

const char * reverse(char word[]) {
    char reverse[sizeof(word)];
    int i, j;

    for (i = sizeof(word - 1); i <= 0; i--) {
        for (j = 0; j > sizeof(word - 1); j++) {
            reverse[i] = word[j];
        }
    }
    return reverse;
}

int main() {
    char word[100];

    printf("Enter a word: ");
    scanf("%s", word);

    printf("%s backwards is %s\n", word, reverse(word));

    return 0;
}

When the user enters a word, the program successfully prints it out when i store it but when i call the reverse function I made it doesnt return anything. It says on my editor the address of the memory stack is being returned instead and not the string of the array I am trying to create the reverse of in my function. Can anyone offer an explanation please :(

A: sizeof(word) is incorrect. When the word array is passed to a function, it is passed as a pointer to the first char, so you are taking the size of the pointer (presumably 4 or 8, on 32- or 64-bit machines). Confirm by printing out the size. You need to use strlen to get the length of a string.
There are other problems with the code. For instance, you shouldn't need a nested loop to reverse a string. And sizeof(word-1) is even worse than sizeof(word). And a loop that does i-- but compares i<=0 is doomed: i will just keep getting more negative.

A: There are multiple problems with your reverse function. C is very different from Java. It is a lot simpler and has less features.

*

*Sizes of arrays and strings don't propagate through parameters like you think. Your sizeof will return wrong values.

*reverse is an identifier that is used twice (as function name and local variable).

*You cannot return variables that are allocated on stack, because this part of stack might be destroyed after the function call returns.

*You don't need two nested loops to reverse a string and the logic is also wrong.

What you probably look for is the function strlen that is available in header string.h. It will tell you the length of a string. If you want to solve it your way, you will need to know how to allocate memory for a string (and how to free it).
If you want a function that reverses strings, you can operate directly on the parameter word. It is already allocated outside the reverse function, so it will not vanish.
If you just want to output the string backwards without really reversing it, you can also output char after char from the end of the string to start by iterating from strlen(word) - 1 to 0.

A: Edit: Changed my reverse() function to avoid pointer arithmetic and to allow reuse of word.

*

*Don't return const values from a function; the return value cannot be assigned to, so const doesn't make sense. Caveat: due to differences between the C and C++ type system, you should return strings as const char * if you want the code to also compile as C++.

*Arrays passed as params always "decay" to a pointer.

*You can't return a function-local variable, unless you allocate it on the heap using malloc(). So we need to create it in main() and pass it as a param.

*Since the args are pointers, with no size info, we need to tell the function the size of the array/string: sizeof won't work.

*To be a valid C string, a pointer to or array of char must end with the string termination character \0.

*Must put maximum length in scanf format specifier (%99s instead of plain %s — leave one space for the string termination character \0), otherwise vulnerable to buffer overflow.

   #include <stdio.h>  // size_t, scanf(), printf()
   #include <string.h> // strlen()

// 1.         // 2.       // 3.                // 4.
   char *reverse(char *word, char *reversed_word, size_t size);

   char *reverse(char *word, char *reversed_word, size_t size)
   {
           size_t index = 0;

           reversed_word[size] = '\0'; // 5.

           while (size-- > index) {
                   const char temp = word[index];
                   reversed_word[index++] = word[size];
                   reversed_word[size]    = temp;
           }

           return reversed_word;
   }

   int main() {
           char word[100];
           size_t size = 0;

           printf("Enter a word: ");
           scanf("%99s", word); // 6.

           size = strlen(word);

           printf("%s backwards is %s\n", word, reverse(word, word, size));

           return 0;
   }


text:
Q: How do I apply Devexpress themes to a basic html table? I'm using Devexpress's MVC exctensions within my MVC3 w/razor project. I have data grids using Devexpress's MVC extensions and also basic html tables without any styling.
Is there a way to apply the devexpress styles to my html tables for a consistent look?

A: You can use css to style a grid then follow the same principle for a table. Here is a style for a grid I created then styles for a similar looking table
/************************GRID STYLE************************************/
.mGrid
{
width: 100%;
background-color: #fff;
margin: 5px 0 5px 0;
border: solid 1px #525252;
border-collapse: collapse;
font-size: 13px; /*width: 820px;*/
text-align: center;
}
.mGrid td
{
padding: 2px;
border: solid 1px #c1c1c1;
color: #717171;
height: 20px;
}
.mGrid th
{
padding: 4px 2px;
color: #fff;
background: #424242 url(images/grd_head.png) repeat-x top;
border-left: solid 1px #525252;
height: 20px; /*font-size: 15px; */
}
.mGrid .alt
{
background: #fcfcfc url(images/grd_alt.png) repeat-x top;
}
.mGrid .pgr
{
background: #424242 url(images/grd_pgr.png) repeat-x top;
text-align: left;
}
.mGrid .pgr table
{
margin: 5px 0;
}
.mGrid .pgr td
{
border-width: 0;
padding: 0 6px;
border-left: solid 1px #666;
font-weight: bold;
color: #fff;
line-height: 12px;
}
.mGrid .pgr a
{
color: #666;
text-decoration: none;
font-size: 13px;
}
.mGrid .pgr a:hover
{
color: #AED434;
text-decoration: none;
font-size: 13px;
}

/************************END GRID STYLE************************************/

/************************mGrid Table Look alike STYLE************************************/
 .mGridLookAlikeTable
{
width: 100%;
background-color: #fff;
margin: 5px 0 5px 0;
border: solid 1px #525252;
border-collapse: collapse;
font-size: 13px;
/*width: 820px;*/
text-align: center;
 }

 .mGridLookAlikeTable td
 {
padding: 2px;
border: solid 1px #c1c1c1;
color: #717171;
height: 20px;
 }
 .mGridLookAlikeTable th
 {
padding: 4px 2px;
color: #fff;
background: #424242 url(images/grd_head.png) repeat-x top;
border-left: solid 1px #525252;
height: 20px; /*font-size: 15px; */
 }

 /************************END mGrid Table Look alike STYLE************************************/


text:
Q: keybd_event function hold key issue I am currently building a c# application which uses keybd_event to send key strokes to some other application. However it is not working as I expect it to be.
My press and release methods are like this:
public void PressKey(string key)
{
    var keyCode = Keycodes.StringToInt(key);
    keybd_event((byte)keyCode, 0, 0x0001 | 0, 0);
}

public void ReleaseKey(string key)
{
    var keyCode = Keycodes.StringToInt(key);
    keybd_event((byte)keyCode, 0, 0x0001 | 0x0002, 0);
}

They are working properly as far as typing a letter to the other application. However when I try to hold a key, wierd behaviour occurs.
For example if I write:
PressKey("LeftShift");

I get the expected result. As the application runs, shift is pressed all the time.
However when I try this:
PressKey("W");

I expect to see infinite amount of "w"s typed. But instead I only get a single "w".
So my question here is that, why keybd_event does not treat all buttons the same? Or I am missing something in my methods?

A: In this particular project I ended up using a 3rd party library InputManager and it worked as expected.


text:
Q: How to find optimal solution that maximizes summation of sinusoidals over amplitude and phase designers. We have a function:
$$
f(x,y,z) = x\cos{(\omega\:t+y+\phi_1)} + z\cos{(\omega\:t+y+\phi_2)}.
$$
I want to solve the following maximization problems:
$$
\max_{x,y,z} {\max_tf(x,y,z)}\qquad\text{or}\qquad\max_{x,y,z}\int_{<T>} f(x,y,z) dt.
$$
Surely, $x$ and $z$ are nonnegative, and $y$ is in $[0,2\pi)$.
Can someone give me hints for solving the problem, or let me know some references to solve this types of problem?

A: The first problem, the pointwise maximisation $$ \max_{x,y,z} \max_{t} f(x,y,z) $$ has not a solution: indeed, whatever $t$ and $y$ you select, the target function will diverge as $x$ and $z$ $\to \infty$, as the two cosine functions will return values bounded by $0$ and $1$, and their argument do not depend on $x,z$.
A similar line of thought is valid for the second problem too.Whatever candidate parameters $x,y,z$ you consider, you could increase the target function by increasing say $x$, which does not affect the period.
For the problem to be interesting, some constraint on $x,z$ might be considered.
In any case, both the problem are akin to maximising a function over three or four unknowns (as you can always solve the integral, for the second case): setting partial derivative to zero would be a good starting point. You woul find stationary points, and then you would have to check the stationary points corresponds to maxima.


text:
Q: Netbeans: Like XML Syntax-Highlighting How could I say to Netbeans that it should highlight *.tmx files like they were xml files?

A: You could try creating a mapping between Fileextension "tmx" and "XML Files" in Tool - Options - Misc - Files.


text:
Q: how input redirection works? On my understanding, any command that reads from standard input (i.e keyboard), that it gets its input from a file.
$echo < text_content.txt

$

But echo command does not read and display the text_content.txt on the terminal. what's wrong here?

A: stdin and Commands

On my understanding, any command that reads from standard input (i.e keyboard), that it gets its input from a file.

Effectively, yes. As I've discussed in my answer on What characterizes a file in Linux/Unix?, a file is any object on which you can execute standard operations such as read(), open(), write(), close(). stdin being represented via file descriptor 0 is effectively a file in that regard, and any command/process in Linux gets 3 standard file descriptors - stdin,stdout,stderr - when that process is started. What are the actual files behind those file descriptors ? The command doesn't care and shouldn't, as long as it can do operations on it.

But echo command does not read and display the text_content.txt on the terminal. what's wrong here?

Now, command is free to do what it will with those file descriptors1. In case of echo it only deals with stdout and doesn't perform any action on stdin at all. So there's nothing wrong with the command itself.
< redirection will open() the file text_content.txt for reading, and it still will assign file descriptor ( for example 3 ) returned from open() call to file descriptor 0, and if a command is concerned with stdin - it will read from file descriptor 0 as if nothing happened.In fact, you will see that in action, if you run strace -f -e dup2,write,openat bash -c 'echo < text_content.txt
openat(AT_FDCWD, "/etc/passwd", O_RDONLY) = 3
dup2(3, 0)                              = 0
write(1, "\n", 1
)                       = 1
dup2(10, 0)                             = 0
+++ exited with 0 +++

Notice the dup2() system call. That's how file descriptor 3 (the file) is assigned/redirected. In sort of cp original copy syntax, dup2(3,0) makes a copy of file descriptor 3 to file descriptor 0, and they point to same file.
Notice also that write() output a newline to file descriptor 1. That's the default behavior. If we do strace -f -e dup2,write,openat bash -c 'echo FOO < /etc/passwd' here's what we will see
dup2(3, 0)                              = 0
write(1, "FOO\n", 4FOO
)                    = 4
dup2(10, 0)                             = 0
+++ exited with 0 +++

So again, nothing wrong here - redirections are performed properly and echo does its job of writing stuff to stdout which is file descriptor 1.

How to actually read a file
Now, lets address something else. How can we read a file in shell ? Well, for that there exists cat command, which accepts arguments, so you can do just cat file.txt. Can you do cat < file.txt ? Sure. But that means shell will have to do that dup2() call, whereas cat file.txt doesn't - so there's less unnecessary syscalls is what I'm saying.
In complex cases, such as when you need to perform an action on each line of the file, you would do
while IFS= read -r line || [ -n "$line" ]; do
    # command to process line variable here
done < /etc/passwd

Now, for the whole loop file descriptor 0 will be a copy of whatever file descriptor is returned from opening /etc/passwd.  Of course, if you can use cat or another specific command to the job of reading a file - do that. Shell is slow method and has a lot of pitfalls. See also, Why is using a shell loop to process text considered bad practice?

1. Some applications still might care about what they can do with stdin or detect if stdin is a file or pipeline. When stdin file descriptor is assigned as read-end of pipeline (which is also a file descriptor) the output is not seekable (meaning that application written in C or another language cannot use seek() syscall to quickly navigate to specific byte offset in a file). A good example of that is given in the question titled What is the difference between "cat file | ./binary" and "./binary < file"?
Sidenote: on Linux it's not exactly keyboard from where stdin gets its input. If you do
$ ls -l /proc/self/fd/0
lrwx------ 1 serg serg 64 Feb 23 16:45 /proc/self/fd/0 -> /dev/pts/0

you will see in the output that it is /dev/pts/0 terminal device to which stdin points initially. The terminal device then interfaces with keyboard, or it could as well be serial cable.
Additionally, if file is not very large, you could take advantage of bash's mapfile builtin to read lines into array:
mapfile  -t  < /etc/passwd
for i in "${MAPFILE[@]}"; do echo "$i"; done


text:
Q: sql rounding value I have been successful at rounding my value to one decimal point, but I would like to trim off the multitude of trailing zeros.  For example, this:
ROUND(SUM(Duration),1)

...ends up giving me:
16.9000000000000000

how do I trim all those trailing zeros.
mssql

A: The round function rounds the number, but it leaves the data type unchanged:
ROUND(3.14,1) --> 3.10

By casting a number to numeric(x,1), you both round it and change it's data type to single digit precision:
CAST(3.14 as numeric(6,1)) --> 3.1

For your query, such a cast could look like:
select cast(sum(duration) as numeric(6,1))

But the eventual display format depends on the client.  SQL Server Management Studio will display numeric(x,1) with one digit behind the dot, but it is free to display it in another way.  Formatting a number is best done client side, outside of SQL.

A: Use:
CONVERT(Decimal(9, 1), ROUND(SUM(duration), 1))

The second parameter of the DECIMAL data type is the precision - 1 will give you a single digit after the decimal point.


text:
Q: Are left adjoints a left adjoint? Let $\mathcal C$ be a strict, locally small 2-category.
Consider a subcategory $\mathcal L$ of $\mathcal C$ such that $\mathcal L$ has the same objects as $\mathcal C$, and the arrows of $\mathcal L$ are the left adjoints in the 2-category $\mathcal C$. Let $U:\mathcal L\to\mathcal C$ be the inclusion functor.
When is $U$ a (left or right) adjoint?

A: Your question is impossible to answer in full generality. There are, however, some interesting special cases. I shall focus on your motivating example (I think, I have written about this on many occasions, but cannot recall the exact sources at the moment).
If $\mathbb{C}$ is a (finitely complete, locally small) regular category, then you may construct a category $\mathit{Rel}(\mathbb{C})$ of canonical internal relations in $\mathbb{C}$. Moreover, $\mathit{Rel}(\mathbb{C})$ has a 2-categorical structure induced by the natural ordering of monomorphisms, and $\mathbb{C}$ is equivalent to the (2-)subcategory of $\mathit{Rel}(\mathbb{C})$ consisting of morphisms that have right adjoint.
On the other hand, the inclusion:
$$J \colon \mathbb{C} \rightarrow \mathit{Rel}(\mathbb{C})$$
has a right adjoint:
$$P \colon \mathit{Rel}(\mathbb{C}) \rightarrow \mathbb{C}$$
iff $\mathbb{C}$ is an elementary topos. Indeed, one may easily verify, that $P$ has to be the internal power functor:
$$\hom_{\mathit{Rel}(\mathbb{C})}(A, B) \approx \hom_\mathbb{C}(A, P(B))$$
More generally, if $p$ is a regular fibration, then under some mild conditions, $p$ has a generic object iff the canonical embedding:
$$J \colon \mathit{Map}(\mathit{Rel}(p)) \rightarrow \mathit{Rel}(p)$$
has a right adjoint, where $\mathit{Rel}(p)$ is the category of $p$-internal relations, and $\mathit{Map}(\mathit{Rel}(p))$ is the subcategory of $\mathit{Rel}(p)$ consitiong of morphisms that have right adjoints.
The link with the previous example appears, when we consider for $p$ the canonical subobject fibration $\mathit{sub}_\mathbb{C}$ of a regular category $\mathbb{C}$ (the canonical subobject fibration of a regular category is regular, and the generic object of a subobject fibration corresponds to the subobject classifier of the category). Another interesting case, is when instead of a subobject fibration, we consider a fibration of regular subobjects --- which leads to the definition of a quasitopos.
Another view of the above generalization is to consider an allegory $\mathbb{A}$. The subcategory $\mathit{Map}(\mathbb{A})$ of $\mathbb{A}$ consisting of maps that have right adjoints is called the category of maps in $\mathbb{A}$. An allegory $\mathbb{A}$ is a "power allegory" iff the canonical inclusion:
$$J \colon \mathit{Map}(\mathbb{A}) \rightarrow \mathbb{A}$$
has right adjoint $P$.
As you may see, your question for mere 2-posetal categories (i.e. $\hom(X, Y)$ is a poset for every $X, Y$) of relations is highly non-trivial.
In some sense, the concept of proarrow equipment (pointed by Tim in his comment) is a 2-categorification of the concept of an allegory. Category $\mathbf{Cat}$ can be reconstructed, up to Cauchy completion (one should not expect more by categorical methods, because $\mathbf{Prof}$ does not distinguish between a category and its Cauchy completion --- i.e. they are equivalent in $\mathbf{Prof}$), from $\mathbf{Prof}$ by taking profunctors that have right adjoints. The inclusion:
$$J \colon \mathbf{Cat}_\mathit{CC} \rightarrow \mathbf{Prof}$$
does not have right adjoint due to the size issues. The same is true for the inclusion:
$$J \colon \mathbf{Cat}_\mathit{CC}(\mathbb{C}) \rightarrow \mathbf{Prof}(\mathbb{C})$$
of Cauchy complete $\mathbb{C}$-internal categories to $\mathbb{C}$-internal profunctors, for any non-trivial category $\mathbb{C}$.


text:
Q: Register user to firebase and sign in if already registered I have the following code to register a user to firebase...
FIRAuth.auth()?.createUserWithEmail(email.text!, password: password.text!) {(user, error) in
            if let error = error {
                print(error.localizedDescription)
                if error.localizedDescription == "FIRAuthErrorCodeEmailAlreadyInUse"
                {
                   //sign in here?
                }

            }
            else {
                print("User signed in!")
            }
        } }
    else{
        print("You left email/password empty")
    }

What would I add to this so it automatically signs in if the user was already created?
Thanks.

A: You can use any of the authentication methods Firebase provides. E.g. in your case, this one would be most suitable:
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
  // ...
}

Source
EDIT
The error response from the registration method you posted will tell you if the given user already exist. In which case, you can just make a call to the signIn method automatically from within the callback.
Looking at the official docs, I see the error code you should look for is FIRAuthErrorCodeEmailAlreadyInUse.

A: You can check if currentUser is not nil beforehand:
if Auth.auth().currentUser != nil {
    // User is signed in.
    // ...
} else {
    // No user is signed in.
    // ...
}

From Firebase docs:

You can also get the currently signed-in user by using the currentUser property. If a user isn't signed in, currentUser is nil:

A: Another way of doing this is to use fetchProvidersForEmail:completion: https://firebase.google.com/docs/reference/ios/firebaseauth/api/reference/Classes/FIRAuth#-fetchprovidersforemailcompletion to check if the email exists first.
This will return the list of provider IDs associated with that email. If you get 'password' in the list then an email/password account already exists for that email, you can call signIn(withEmail: email, password: password). Otherwise, you call createUserWithEmail(email, password: password)


text:
Q: Combine many 2D textures into one and write text on it in Unity (C#) I have not found solution for my problem.
I want to combine few textures (one under another, they won't overlap) and then write a text on one of them. So basically I would like to set some render target, draw there few textures and text and then save it to final texture. Of course I need to do it during run-time from script.
What is the best way to do it in Unity 5.0? (script is in C#)

A: You can do it with
target texture


text:
Q: Creating buttons with a JavaScript class So I decided to make a little website for storing my recipes, like a digital recipe book. That way, I can access and edit them from anywhere by changing a few lines in the Javascript(no messing with files). Each recipe appears when you click its button and disappears when you click its hide button.
There are two versions. There is an old version, where the recipes are written in. There's prewritten HTML for their buttons, and they're in object literal in the javascript. It is on the gh-pages branch of the github repository, and used and the github page. It worked, so I tried to make the more dynamic second version.
The second version is on the recipes-object-oriented branch of the github repository. It has a class creator so I can add recipes just by calling it. It establishes the properties, gives each recipe its own method for the update/hide functions, and also attempts to make the HTML for them and their buttons using the DOM. It doesn't work.
I don't know for certain what code is causing the second version to not work, but I suspect it is with the buttons. I have one recipe declared, but its buttons aren't appearing. I haven't seen anyone make HTML with a class before, so this may not be the right way to do it.
Any thoughts on the problem with it, or other parts of the code? I'm not very experienced with javaScript (just a middle school student), so apologies if I have no clue what I'm doing.

GitHub repository: https://github.com/skwawk/recipes
jsfiddle for second version: https://jsfiddle.net/psz3do70/1/

Following is the code for the second version's class function.
function Recipe(id, name, ingredients, steps,) {
    this.id = id;
    this.name = name;
    this.title = "
" + name + "
";
    this.ingredients = ingredients;
    this.steps = steps;

    //the part that I'm worried about
    var btn = document.createElement("input");
    btn.type = "button";
    btn.name = this.id;
    btn.value = this.name;
    btn.onclick = this.update;
    document.body.appendChild(btn);
    var div = document.createElement("div");
    div.id = this.id;
    document.body.appendChild(div);

    this.printRecipe = function () {
            console.log(this.name);
            console.log();
            console.log(this.ingredients);
            console.log();
            console.log(this.steps);
    };
    this.update = function () {
        recipeDiv = document.getElementById(name);
        recipeDiv.innerHTML = this.title + this.ingredients + "

" + this.steps;
    };
    this.hide = function() {
        recipeDiv = document.getElementById(name);
        recipeDiv.innerHTML = "";
    };

};

There's practically no HTML for the second version, just the recipes heading.
Thanks for looking at this, and thanks in advance for any answers!
Edit: Thanks for feedback! I have fixed a few errors you found (and which I should have caught), but it's still not working. At least we're closer to finding out when it does!


text:
Q: When couples only have children until the first boy is born, what it the ratio of sexes? For one of my homework, I was given this question.
Married couples in a community only have children until the first boy is born (we neglect cases of twins).
What is the ratio of sexes in this community? How is it about independence of sexes of children?
So for the first part, I expected it to be a 1:1 ratio which was correct but for the second part, I don't really understand the second part but I thought it will be independent.
Here is the answer given:
But children within a family are not anymore independent as the youngest child is always a boy and his siblings, if any, are always girls.
Surely the events are still independent? Why does being in a family change that...
Edit: Sorry, I dont see why this is a duplicate. The first part of the question which is identical about the expectation being 1/2, I already knew. It is the second part that I'm stuck at and interested in. (It doesn't talk about multiple generations in this question like it does in the duplicate.)


text:
Q: Alert on Browser Back button click or page refresh I have seen the same function is multiple sites including SO. I am also trying to achieve this.
Here is the code so far.
 <script>
            var myEvent = window.attachEvent || window.addEventListener;
            var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';

            myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                var confirmationMessage = ' ';
                (e || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            });
        </script>

The problem is above code is working fine in chrome and IE but when I tried to test in on Firefox it is not working. I checked firebug but there is no error.
I updated the firefox and version are 47.0.1.
But issue not fixed.
Any advice would be helpful.
Guys if you have code better than this then it would be also helpful.

A: Use below code, I tested it in firefox and is working fine :
window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

A: Well I tested this code and it is working on firefox and chrome even with firebug console closed :
     <script>
            window.onbeforeunload = function (e) {
                var message = "Are you sure ?";
                var firefox = /Firefox[\/\s](\d+)/.test(navigator.userAgent);
                if (firefox) {
                    //Add custom dialog
                    //Firefox does not accept window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() furthermore
                    var dialog = document.createElement("div");
                    document.body.appendChild(dialog);
                    dialog.id = "dialog";
                    dialog.style.visibility = "hidden";
                    dialog.innerHTML = message;
                    var left = document.body.clientWidth / 2 - dialog.clientWidth / 2;
                    dialog.style.left = left + "px";
                    dialog.style.visibility = "visible";
                    var shadow = document.createElement("div");
                    document.body.appendChild(shadow);
                    shadow.id = "shadow";
                    //tip with setTimeout
                    setTimeout(function () {
                        document.body.removeChild(document.getElementById("dialog"));
                        document.body.removeChild(document.getElementById("shadow"));
                    }, 0);
                }
                return message;
            };
        </script>

I found this script crossbrowser-onbeforeunload.js. It is cross-browser compatible.

A: window.onbeforeunload is a good way to go. But it seems to be working in Firefox only if user has interaction with the website (click or scroll). Otherwise function doesn't trigger. Chrome, on the other hand works great.

Note: To combat unwanted pop-ups, some browsers don't display prompts
  created in beforeunload event handlers unless the page has been
  interacted with; some don't display them at all

Documentation

A: It's work for me by this code.
window.onbeforeunload = function () {
    return 'Are you sure? Your work will be lost. ';
};


text:
Q: How to exchange two class by value ,not reference? There are two classes in ArrayList.I want to exchange all their values but not their reference.For example , arraylist1(1) refers to the same class after exchanging , with its value changed.
If I change them in this way
Dim someclass1 as new someclass
Dim someclass2 as new someclass
arraylist1(1) = someclass1
arraylist1(2) = someclass2
temp = arraylist1(1)
arraylist1(1) = arraylist1(2)
arraylist1(2) = temp

It only exchange the reference.arraylist1(1) just refers to someclass2 but actually I want it refers to someclass1 with someclass2's value.
Now I just exchange their important properities one by one.

A: You need to copy properties yourself, one by one. You can make it a bit easier by adding two methods to your class:
Public Class SampleClass
    Public Property Id As Integer
    Public Property Name As String

    Public Function Clone() As SampleClass
        Return New SampleClass With
        {
            .Id = Me.Id,
            .Name = Me.Name
        }
    End Function

    Public Sub Init(input As SampleClass)
        With Me
            .Id = input.Id
            .Name = input.Name
        End With
    End Sub

    Public Shared Sub SwapValues(value1 As SampleClass, value2 As SampleClass)
        Dim temp = value1.Clone()
        value1.Init(value2)
        value2.Init(temp)
    End Sub
End Class

And then when trying to swap values:
SampleClass.SwapValues(list(0), list(1))


text:
Q: Setting *.prototype methods inside angular factory not working I'm creating an angular factory that encapsulates and injectable type that can be new-ed up as such:
(function() {
angular
  .module('app')
  .factory('PaymentStream', [

function() {

    function PaymentStream(){

        this._endingBalance = null;
    }

    PaymentStream.prototype.serialize = function() {

        // method body here
    };

    return PaymentStream;

   }]);
})();

When I create a PaymentStream via new PaymentStream() only the constructor seems to have been called.  If I don't use prototype and just define the methods inside the constructor it works but then I'm redefining the functions with each instance.
Any idea why those prototypes are not being set?
Edit
Here is how it is being used in the outside.
    function addStreamFunctions(stream) {

        angular.merge(stream, new PaymentStream());
    }

A: So basing on your edit, The factory was indeed working correctly. The problem is the way you used it, you angular.merged the newed object with another object, so its type is not a PaymentStream anymore, the resulting object became a 'generic' object
If the stream is a plain object, what you can do is pass the stream variable in the constructor of PaymentStream and do the merging manually inside your constructor function. Something like
function PaymentStream(stream){

    this._endingBalance = null;

    var keys = Object.keys(stream); //get all properties from the stream

    keys.forEach(function(key){
       this[key] = stream[key];   //put each one in the instance of your object;
    });

}

then use it like
function addStreamFunctions(stream) {

    var stream = new PaymentStream(stream);

}

this code is untested, please tell me if it worked or not :)

A: Since you are working with factory you need to return an instance of the object, in this case a new instance of PaymentStream
(function() {
  angular.module('my-app').factory('PaymentStream', [function() {
    function PaymentStream() {
      this._endingBalance = null;
    }

    PaymentStream.prototype.serialize = function() {
      // method body here
    };

    return new PaymentStream();
  }]);
})();


text:
Q: Razor Dropdownlist Unable to load the specified metadata resource Salaamun Alekum
I Was Using Drop Down List
@Html.DropDownList("SpecialityList", null, htmlAttributes: new { @data_toggle = "tooltip", @data_placement = "left", @title = "Select Speciality", @class = "form-control" })

Its Was Working Fine I Don't Know What Happened It Stop Working And Showed Me This Error

System.Data.Entity.Core.MetadataException: Unable to load the
  specified metadata resource.

A: @Html.DropDownList("SpecialityList", new selectList(new[]{}), htmlAttributes: new { @data_toggle = "tooltip", @data_placement = "left", @title = "Select Speciality", @class = "form-control" })

try new selectList()

A: The Issue Was Resolved By Creating Content Of Previous Project To Newly Created Project
Some Dll Files Became Corrupt


text:
Q: MergeSort with ArrayList import java.util.*;

public class Dealer {

public static void main(String[] args){
    ArrayList<Card> cards = new ArrayList<Card>();
        for (Suits s : Suits.values()) {
        for (Ranks r : Ranks.values()) {
             Card value = new Card(s,r);
             cards.add(value);
        }
    }
    shuffle(cards);
    present(cards);
    System.out.println();
    cards = selectionSort(cards);
    present(cards);
}
private static void shuffle(ArrayList<Card> list){
     Collections.shuffle(list);
}
private static void present(ArrayList<Card> list){
    int count = 0;
    for (Card c : list){
        count++;
        System.out.println(c.toString());
    }
}
private static ArrayList<Card> selectionSort(ArrayList<Card> list){
    int min;
    int count = 0;
    for (int i = 0; i < list.size(); i++) {
        count++;
        // Assume first element is min
        min = i;
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(j).Get() < list.get(min).Get()) {
                min = j;

}
    }

if(min != i){
    final Card temp = list.get(i);
    list.set(i,list.get(min));
    list.set(min,temp);
}

  //  System.out.println(list.get(i));// I print the in ascending order
}
System.out.println("================================== Sorted Deck Below =========================================================");
System.out.println("It took "+count+" iterations to sort this deck using selection sort.");
System.out.println();
return list;

}

private static ArrayList<Card> InsertionSort(ArrayList<Card> list){
    int count = 0;
    for (int i = 1; i < list.size(); i++) {
        Card temp = list.get(i);
        int j;
        for(j = i-1;j>=0&&temp.Get()<list.get(j).Get(); j--){
            list.set(j+1,list.get(j));
        }
       list.set(j+1,temp);
       count ++;
    }
    System.out.println("================================== Sorted Deck Below =========================================================");
    System.out.println("It took "+count+" iterations to sort this deck using insertion sort.");
    System.out.println();
    return list;
}

//mergeSort code below this is where I get confused on its implementation

public static void mergeSort(ArrayList<Card> list){
        if (list.size() ==1){
            return list;
        }
        else {
           int mid= list.size()/2;
           ArrayList<Card> left= new ArrayList<Card>(mid);
           ArrayList<Card> right=new ArrayList<Card>(list.size()-mid);

for (int i = 0; i < mid; i++) {
           left.add(list.get(i));
       }

for (int i = 0; i < list.size()-mid; i++) {
           right.add(list.get(i+mid));
       }

left=mergeSort(left);
   right=mergeSort(right);
   merge(left,right,list);
}
return list;

}

public static void merge (ArrayList<Card>left,ArrayList<Card>right,ArrayList<Card>list){
        int i1=0;// left Index
        int i2=0;// right Index
        int ListIndex=0;

for (int i = 0; i < list.size(); i++) {
        if (i2>=right.size() || (i1<left.size() && (right.get(i)>=left.get(i))))
        {
            list.set(ListIndex,left.get(i1));
            ListIndex++;
        }
        else {
            list.set(ListIndex, right.get(i2));
            ListIndex++;
        }
    }

}

}

===========================================================================
// Created enums
enum Ranks{
   Ace,King,Queen,Jack,Ten,Nine,Eight,Seven,Six,Five,Four,Three,Two
}

enum Suits{
    Spades,
    Hearts,
    Diamonds,
    Clubs
}

public class Card{

 private Ranks rank;
 private Cards card;

public Card(Suits suit, Ranks rank){

    this.suit = suit;
    this.rank = rank;
}

public int Get(){
     return (suit.ordinal())+rank.ordinal()*4;
}

public String toString(){

  return rank.toString()+" of " +suit.toString();
    }
}

I am a bit of a beginner of sorting using ArrayList but then I saw this code that had SelectionSort and InsertionSort and then I thought that if those two were there, then I could make a MergeSort doing the same thing using ArrayList. I understand the what it will actually do part but I am confused on how to implement it using ArrayList. I'm having trouble putting up these methods to deal with the ArrayList to get my Array sorted. Does anyone know something I should try to rectify this problem? I can tell at certain areas of this code that it becomes obvious to tell where certain parts would become a problem. To clarify, my main question is how would I be able to implement ArrayList to the MergeSort methods to properly allow MergeSort to sort the cards? As you can see I did make an attempt to put together ArrayList in the methods but I haven't really got anywhere successful with it.


text:
Q: Excel Index match with multiple criteria? I have 2 worksheets, Home and Data.
Data:
Column A                        Column B         Col C     Col D     Col E         Col F
ABC2 121 - ABC2 121             ABC2             3456                12/12/2016    =WeekNum(E1) - SPAM
123420121601     - 2678         123420121601     1234      2678      18/12/2016    =WeekNum(E2)
628428121601     - 9862          628428121601     6284      9862      21/12/2016    =WeekNum(E3)

Column A contains random text and a PO number and item no, e.g. the PO of ABC123456781011 would be 123456781011 and the item number would be 2678.
I am extracting the PO number into column B.
In Column C i am getting the first four digits of the PO, this is the supplier number.
In column D i have my item number. This is also extracted from the cell in column A.
The date in column E is also extracted from the PO e.g.
123420121601  = a date of 201216 but converted as date.
Note cell A1 contains no PO and is considered a SPAM row. i do not want/need to use it in anyway so it must be disregarded.
Next
Home:
Column H       Column I         Col J                Col L

1234           2678             18/12/2016           123420121601
6284           9862             51                   628428121601

I am trying to use an index match in col D that will give the PO number from my data sheet where the supplier number, item number and date match.
However, on the home sheet in column J, on the last row - a user has input a week number rather than the actual date. I still want to be able to return a PO value if either the date matches exactly or if the week number for that date matches.
Here's what i have so far but the index match is not checking my criteria properly and i am getting an incorrect result. It gives me a result from the PO of the first row on sheet data.
=INDEX(Data!B:B,SUMPRODUCT(IF(YEAR(Home!$J10)<2016,(Data!F:F=Home!J10),(Data!E:E=Home!J10))*(Data!C:C=Home!H10)*(Data!D:D=Home!I10)*ROW(Data!B:B)))

Please can someone show me where i am going wrong?


text:
Q: Polymer event listener in ES6 I'm using Polymer 1.0 with EcmaScript 6 and transpiling using Babel and Vulcanize.
I fire an event from a button, but I can't listen to it from my modal.
When I add an eventListner in the console, I can catch the event. But I can't from the modal.
I've tried to pass the listener as string and as the actual function, but it didn't work.
class MyEditButton {
    beforeRegister(){
        this.is= 'my-edit-button';
        this.extends = 'button';

        this.properties = {
            myObjectId: {
                type: Number,
                value: -1,
            }
        }
        this.listeners = {
            'tap': 'taphandler'
        }
    }
    taphandler(){
        this.fire(
            'my-edit-button-clicked',
            {'my-object-id': this.myObjectId}
        )
    }
}

Polymer(MyEditButton);

This is the modal that was supposed to listen to the event.
class MyModal {
    beforeRegister(){
        this.is = 'my-modal';

        this.listeners = {
            'my-edit-button-clicked': '_onButtonClick'
        };
    }

    _onButtonClick(e, details){
       console.log("Clicked!");
    }
}

Polymer(MyModal);

Does anybody knows why? Is there an "event scope" or it fires the event in just one direction?

A: If your button were a child of the modal, the event would bubble up to the modal, and your existing code would work:

HTMLImports.whenReady(_ => {
  "use strict";

  class MyEditButton {
    beforeRegister() {
      this.is = 'my-edit-button';
      this.extends = 'button';

      this.properties = {
        myObjectId: {
          type: Number,
          value: -1,
        }
      }
      this.listeners = {
        'tap': 'taphandler'
      }
    }
    taphandler() {
      this.fire(
        'my-edit-button-clicked', {
          'my-object-id': this.myObjectId
        }
      )
    }
  }

  Polymer(MyEditButton);

  class MyModal {
    beforeRegister() {
      this.is = 'my-modal';

      this.listeners = {
        'my-edit-button-clicked': '_onButtonClick'
      };
    }

    _onButtonClick(e, details) {
      console.log("Clicked!");
    }
  }

  Polymer(MyModal);
});

  <base href="https://polygit.org/polymer+1.5.0/components/">

  <link rel="import" href="polymer/polymer.html">

  <my-modal></my-modal>

  <dom-module id="my-modal">
    <template>

My Pseudo Modal Dialog

      <button id="myButton" is="my-edit-button">Click</button>
    </template>
  </dom-module>

codepen
Otherwise if the button were a sibling, the event would bubble up to the document, skipping the modal. In this case, you would have to specify the target node as the modal when you call fire() from the button:
 this.fire(
    'my-edit-button-clicked',
    { 'my-object-id': this.myObjectId },
    { node: document.querySelector('my-modal') } // direct signal at first my-modal node
  );

HTMLImports.whenReady(_ => {
  "use strict";

  class MyEditButton {
    beforeRegister() {
      this.is = 'my-edit-button';
      this.extends = 'button';

      this.properties = {
        myObjectId: {
          type: Number,
          value: -1,
        }
      }
      this.listeners = {
        'tap': 'taphandler'
      }
    }
    taphandler() {
      this.fire(
        'my-edit-button-clicked',
        { 'my-object-id': this.myObjectId },
        { node: document.querySelector('my-modal') } // direct signal at first my-modal node
      );
    }
  }

  Polymer(MyEditButton);

  class MyModal {
    beforeRegister() {
      this.is = 'my-modal';

      this.listeners = {
        'my-edit-button-clicked': '_onButtonClick'
      };
    }

    _onButtonClick(e, details) {
      console.log("Clicked!");
    }
  }

  Polymer(MyModal);
});

  <base href="https://polygit.org/polymer+1.5.0/components/">

  <link rel="import" href="polymer/polymer.html">

  <my-modal></my-modal>
  <button id="myButton" is="my-edit-button">Click</button>

  <dom-module id="my-modal">
    <template>

My Pseudo Modal Dialog

    </template>
  </dom-module>

codepen
I'm confused how the button would be accessible if the dialog were truly modal, but let's assume the user can get to the button anyway...
From Polymer docs:

fire(type, [detail], [options]). Fires a custom event. The options object can contain the following properties:

*

*node. Node to fire the event on (defaults to this).

*bubbles. Whether the event should bubble. Defaults to true.

*cancelable. Whether the event can be canceled with preventDefault. Defaults to false.


text:
Q: Scrolling PictureBox I am trying to make an application that is drawing Dendrograms like this one.
So I added a PictureBox to the winform, and for start, I wanted to wrote all labels like in the picture with this code:
foreach (var line1 in lines)
{
    i++;
    gpx.DrawString(line1, myFont, Brushes.Green, new PointF(2, 10 * i));
}

But the problem is that I have a lot of labels so it writes only a few of them on 800x600 px. I wanted to add scrolling bars, but it doesn't work at all. It works only when I am setting an Image to PictureBox.
Is there any other way, with or without PictureBox?

A: PictureBox is a very simple control, it is only good to display a picture.  The one capability it doesn't have that you need is the ability to scroll the content.  So don't use it.
Creating your own control is very simple in Winforms.  A basic starting point is to begin with Panel, a control that supports scrolling, and derive your own class for it so you customize it to be suitable for the task.  Add a new class to your project and paste the code shown below.  Compile.  Drop the new control from the top of the toolbox onto a form.  Note how you can set the Lines property, either with the designer or your code.  Use the Paint event to draw the dendrogram.  Or extend the OnPaint() method in the class, you can make it as fancy as you want.
using System;
using System.Drawing;
using System.Windows.Forms;

class DendrogramViewer : Panel {
    public DendrogramViewer() {
        this.DoubleBuffered = this.ResizeRedraw = true;
        this.BackColor = Color.FromKnownColor(KnownColor.Window);
    }

    public override System.Drawing.Font Font {
        get { return base.Font; }
        set { base.Font = value; setSize(); }
    }

    private int lines;
    public int Lines {
        get { return lines; }
        set { lines = value; setSize(); }
    }

    private void setSize() {
        var minheight = this.Font.Height * lines;
        this.AutoScrollMinSize = new Size(0, minheight);
    }

    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
        base.OnPaint(e);
    }
}