text:
Q: One server, two DNS records in different networks... How to define which to use I have a Hyper-V VM that has 2 virtual NICs, in different networks.
These different networks travel over different physical infrastructure.
Network A is used for management, and goes through a 100Mbps interface. Network B should be used for data, and goes through a 4Gbps interface.
On my domain controller (which is also a DNS server, running Server 2012), the server in question has 2 DNS records... same hostname, 2 different IP's.
When I try to connect to, say, a database on this server, and specify the hostname in my connection string, traffic always goes over the 100Mbps interface.
Is there a way to force the client computer to resolve the IP address of the server in my data network? Do I have to specify the IP address of the server in my connection string?

A: On the server in question, configure the NIC connected to Network A to not register in DNS. Then delete the DNS record for the Network A NIC. When you connect by name you'll connect to the name registered by the Network B NIC. When you need to connect to the "management" NIC you can do that by ip address.

A: Manually create an A record using a different hostname or just connect directly to the IP address.


text:
Q: Consulta com duas tabelas Estou em um projeto, tenho a tabela cliente e trabalho.
Um trabalho tem um cliente. Já relacionei as tabelas, mas preciso fazer um select que a partir do id do cliente na tabela trabalho, retorne o nome do cliente.
Tenho que fazer uma consulta para exibir no meu código em php.
Alguém pode me ajudar por favor?

A: Supondo que suas tabelas sejam assim:
CLIENTE
    id int,
    nome_cliente VARCHAR
TRABALHO
    id int
    id_cliente int
    descr_trabalho VARCHAR
Você poderia fazer assim:
SELECT a.id, a.descr_trabalho, b.nome_cliente from TRABALHO a
    left join CLIENTE b on
       a.id_cliente = b.id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using gMSA account for SQL server reporting services I am trying to configure SSRS on my VM:s via gMSA account which does not seem to work and unable to access the reporting url ( Web Portal URL) link  to check configuration.
The requirement is to have services hosted on different VM's than its report server and report server TempDB databases. So on server A and B simply running SSRS services fails when using gMSA during the configuration steps in reporting server configuration utility. I am using same gMSA on 2 other database servers as well.

Error" The report server cannot connect to report server database due
to logon failure. User name and password incorrect"

Using setup as mentioned here: Configure a Native Mode Report Server Scale-Out Deployment
Is gMSA supported for scale out or there is something I am missing here?


text:
Q: Sharepoint online app, Access denied Hi I'm new to sharepoint. So I'm trying to develeop sharepoint online app. But there is an error here and I can't find how solve this issue. Error is :

Access denied. You do not have permission to perform this action or
  access this resource.

App deployed to sharepoint online site. I wrote a script into App.js
function initializePage()
{

    var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var currentcontext = new SP.ClientContext.get_current();
    var context = new SP.AppContextSite(currentcontext, hostUrl);
    var web = context.get_web();

    var slider_list = web.get_lists().getByTitle("Slider");

    //var context = SP.ClientContext.get_current();
    //var user = context.get_web().get_currentUser();

    var user = web.get_currentUser();

    // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
    $(document).ready(function () {
        getUserName();
    });

    // This function prepares, loads, and then executes a SharePoint query to get the current users information
    function getUserName() {

        currentcontext.load(user);
        currentcontext.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);

        currentcontext.load(slider_list);
        currentcontext.executeQueryAsync(onSuccess, onFail);
    }

    // This function is executed if the above call is successful
    // It replaces the contents of the 'message' element with the user name
    function onGetUserNameSuccess() {
        $('#message').text('Hello ' + user.get_title());
    }

    // This function is executed if the above call fails
    function onGetUserNameFail(sender, args) {
        alert('Failed to get user name. Error:' + args.get_message());
    }

    function onSuccess() {

        console.log(slider_list);

    }

    // This function is executed if the above call fails
    function onFail(sender, args) {
        console.log(args.get_message());
    }
}

    function getQueryStringParameter(urlParameterKey) {
        var params = document.URL.split('?')[1].split('&');
        var strParams = '';
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split('=');
            if (singleParam[0] == urlParameterKey)
                return decodeURIComponent(singleParam[1]);
        }
    }

But I get this error everytime which is wrote above.
I hope anyone help me.

A: Double Click your AppManifest.xml and hit the Permissions tab. Add the Site collection and request Full Control for your app


text:
Q: Outlook Addin - Visual Basic Windows Forms Application - WebBrowser Control Content not displayed anymore We are using an outlook addin (visual basic .NET framework 4 client profile, office 365 business 16.0.11727.20230) that displays some content within a WebBrowser control. I'm not that familiar with visual basic because someone else created this addin and he is not available anymore now, so first of all sorry if i made any basic mistake.
Actually the control should display some .xml content but to simplify the question im just trying to display the webpage https://www.google.at for the moment.
Displaying the content within this plugin was always working and since the last windows/office update all i get is a white screen with no code error.
If i create a new windows forms application with the same control that runs without outlook the content is displayed without any problems (uri and the actual .xml) so i assume it has something to do with new outlook security settings or something like this.
The control uses the lib Windows.Forms.WebBrowser and the url is set like this:
 Public Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim url = "https://www.google.at"
            Call WebBrowser1.Navigate(New System.Uri(url))
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

I already figured out, that the control displays my content if i enable the setting 'optimize for compatibility' under files/general options but actually i'd like that it displays the content without using that setting because i think that should not be necessary.
Another way to display the content would be to use the "Microsoft Web Browser" (AxSHDocVw.AxWebBrowser) control. This one displays my content too but has an older UI and i can't figure out how to disable the scrollbars with this one.
Don't know if this information helps to figure out why the System.Windows.Forms control does not display the content.
Thanks for any help or suggestions how i get my control back to display some content within.

A: The WebBrowser control is a managed wrapper for the ActiveX WebBrowser control, and uses whichever version of the control is installed on the user's computer.
The WebBrowser control cannot be used by partially trusted code. For more information, see Using Libraries from Partially Trusted Code.
The WebBrowser class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.


text:
Q: How to pass ID (Primary Key) in ListView in OnItemClickListener to get data from SQLite Database in Android app? I need to pass ID, which is a primary key in SQLite Database in android app, to get the data from the Database related to the list item in ListView. When the data is received, it is then passed to another activity using intent.
Everything else is working properly but I am not able to get the ID of the row in the Database according to list item clicked.
Following is the DatabaseHandler.java:
package com.Its_Kush.comety_new;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

// MainActivity
public static final String dbID = "ID";
public static final String dbNAME = "Name";
public static final String dbEMI = "Emi";
public static final String dbMONTHLY_EXP = "Monthly_Exp";
public static final String dbMEMBERS = "Members";
//
public static final String DATABASE_NAME = "Comety_Database.db";
public static final String TABLE_NAME = "Comety_Database_Table";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;

//

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + dbID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + dbNAME + " TEXT, "
            + dbEMI + " REAL, " + dbMONTHLY_EXP + " REAL, " + dbMEMBERS
            + " INTEGER " + ")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String name, double emi, double monthly_exp,
        int members) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    long result = db.insert(TABLE_NAME, null, content);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor viewOne(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id, null);
    return dataShow;
}

public Cursor viewAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return dataShow;
}

public boolean updateData(String id, String name, double emi, double monthly_exp, int members){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbID, id);
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    db.update(TABLE_NAME, content, "id = ?", new String[] { id });
    return true;
}

public int deleteData(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}

public void deleteAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " +  TABLE_NAME);
}

public void resetId(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from sqlite_sequence where name = '" + TABLE_NAME + "'");
}

}

Following is the class containing ListView:
    package com.Its_Kush.comety_new;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowActivity extends AppCompatActivity {

DatabaseHandler dbComety = new DatabaseHandler(this);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView list1;
Button submit, delete;
EditText id;
String name, str;
double monthly_exp, emi;
short members;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);

    list1 = (ListView) findViewById(R.id.list1);

    show_all();

    list1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            Cursor dataOneView = dbComety.viewOne(str.substring(0, 2));
            if (dataOneView.moveToFirst()) {
                name = dataOneView.getString(1);
                emi = dataOneView.getDouble(2);
                monthly_exp = dataOneView.getDouble(3);
                members = dataOneView.getShort(4);
            }
            // showMessage("Value", "Name: " + name + "\nemi:" + emi
            // + "\nm_exp" + monthly_exp + "\nmembers: " + members);
            // id.setText("");

            Intent submit = new Intent(ShowActivity.this,
                    MainActivity.class);
            submit.putExtra("name", name);
            submit.putExtra("emi", emi);
            submit.putExtra("members", members);
            submit.putExtra("monthly_exp", monthly_exp);

            //
            startActivity(submit);
        }
    });

    list1.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            showMessage("Delete", "Are you sure?");
            return true;
        }
    });

}

DialogInterface.OnClickListener cancelClickListner = new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub
        finish();
    }
};

public void show_all() {
    Cursor dataView = dbComety.viewAll();
    if (dataView.getCount() == 0) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Error");
        builder.setCancelable(false);
        builder.setMessage("No data found.").setPositiveButton("Back", cancelClickListner).show();
        dbComety.resetId();

    } else {

        String buffer = null;
        if (dataView.moveToFirst()) {
            do {
                buffer = dataView.getString(0) + "\t\t"
                        + dataView.getString(1);
                listItems.add(buffer);
            } while (dataView.moveToNext());
        }
    }
    adapter = new ArrayAdapter<String>(this, R.layout.textview_listitems,
            listItems);

    list1.setAdapter(adapter);
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            int deletedRows = dbComety.deleteData(str.substring(0, 2));
            if (deletedRows > 0) {
                Toast.makeText(ShowActivity.this, R.string.deleted,
                        Toast.LENGTH_SHORT).show();
                adapter.clear();
                show_all();
                adapter.notifyDataSetChanged();
            } else

                Toast.makeText(ShowActivity.this, R.string.not_deleted,
                        Toast.LENGTH_SHORT).show();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

public void showMessage(String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message)
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener);
    builder.show();
}

DialogInterface.OnClickListener deleteAllClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            dbComety.deleteAll();
            adapter.clear();
            show_all();
            adapter.notifyDataSetChanged();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this
                                                // adds items to the action
                                                // bar if it is present.
    getMenuInflater().inflate(R.menu.show, menu);
    return true;
}

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.delete_all) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete all");
            builder.setMessage("Are you sure?")
                    .setPositiveButton("Yes", deleteAllClickListener)
                    .setNegativeButton("No", deleteAllClickListener);
            builder.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

I am currently using a String to store the list item TextView data and then getting the id using the substring method. How can I directly get the ID of the row in Database?

A: Create a list of row id and make sure that the id and content are stored in the same index of both the lists.
buffer = dataView.getString(1);
idItems.add(dataView.getString(0));
listItems.add(buffer);

and in onitemclicklistener:
Cursor dataOneView = dbComety.viewOne(idItems.get(position));


text:
Q: javascript osc library? Does an open sound control library exists for javascript? I cant seem to find any information on this.

A: I've recently worked on a OSC library (UMD module written in ES6) named osc-js for different JavaScript applications (Node.js, Electron, Chrome Apps, webpages) with address pattern matching, WebSocket-/UDP Plugins and some solutions to connect it to MaxMSP/PureData/etc.:
https://github.com/adzialocha/osc-js

A: I think a JavaScript OSC library, that works in the conventional way (e.g. using a UDP or TCP transport) is not possible due to the lack of low-level networking functionality provided in current browser-based implementations of the JavaScript. Cross-domain scripting limitations would also limit the usefulness of a browser-based OSC implementation IMO.
JavaScript OSC is possible by using custom XPCOM components, but at best, such solutions are going to be browser-specific.
One possibility might be to run OSC over a higher-level protocol. OSC over JSONP springs to mind as a potential area for exploration. Something similar to the MaxJax project, which implements OSC for the Python Twisted web server.

A: Web sockets are, indeed, the best way to implement OSC in a browser - but, with lacking support, the next-best thing is a custom HTTP server. An effort is underway to build one - I've not checked out the process, so have a look yourself to see if it fits your purposes.

A: Implemented, client-side, in my KievII library. Here's a link to the code. Works nicely with my server-side, node.js, OSC Proxy.


text:
Q: Microsoft outlook graph events api: how to get different timezone? I'm trying to GET Microsoft calendar events. Default timezone of my outlook account is US Eastern Time Zone. But the response I'm getting from rest api call is all in UTC. How can I get my default time zone i.e. US Eastern Time?
Here is my code:
def make_api_call(method, url, token, payload = None, parameters = None):
  headers = { 'User-Agent' : 'python_tutorial/1.0',
              'Authorization' : 'Bearer {0}'.format(token),
              'Accept' : 'application/json'}

  request_id = str(uuid.uuid4())
  instrumentation = { 'client-request-id' : request_id,
                      'return-client-request-id' : 'true' }

  headers.update(instrumentation)

  response = None

  if (method.upper() == 'GET'):
      response = requests.get(url, headers = headers, params = parameters)
  elif (method.upper() == 'POST'):
      headers.update({ 'Content-Type' : 'application/json' })
      response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)

  return response

def get_my_events(access_token, start_date_time, end_date_time):
    get_events_url = graph_endpoint.format('/me/calendarView')
    query_parameters = {'$top': '10',
    '$select': 'subject,start,end,location',
    '$orderby': 'start/dateTime ASC',
    'startDateTime': start_date_time,
    'endDateTime': end_date_time}

    r = make_api_call('GET', get_events_url, access_token, parameters = query_parameters)
    if (r.status_code == requests.codes.ok):
        return r.json()
    else:
        return "{0}: {1}".format(r.status_code, r.text)

UPDATE:
Anyone else coming here for this kind of question, you need to update the headers to send any specific time zone. Here are the update headers, make sure you surround timezone in double quotes:
  headers = { 'User-Agent' : 'python_tutorial/1.0',
              'Authorization' : 'Bearer {0}'.format(token),
              'Accept' : 'application/json',
              'Prefer': 'outlook.timezone="Eastern Standard Time"'}

A: You need to specify the time zone using the Prefer: outlook.timezone header.
From the documentation:

Prefer: outlook.timezone
Use this to specify the time zone for start and end times in the response. If not specified, those time values are returned in UTC.

For example, to set it to US Eastern you would send
Prefer: outlook.timezone="Eastern Standard Time"


text:
Q: What group is the Galois group $G(\mathbb{C}/\mathbb{R})$ isomorphic to? Recently in my abstract algebra II course we have been studying Galois theory. I have been doing a lot of reading and came across the Galois group $G(\mathbb{C}/\mathbb{R})$ (The set of all automorphisms of $\mathbb{C}$ that fix $\mathbb{R}$ pointwise) and naturally being an abstract algebra student I immediately asked the question:
To what group is $G(\mathbb{C}/\mathbb{R})$ isomorphic to?
I believe $G(\mathbb{C}/\mathbb{R})$ has two elements: the complex conjugation automorphism and the identity automorphism. Would it maybe be isomorphic to $\mathbb{Z_2}$? I can't find any suppporting evidence of this in my book so if there are any relevant theorems that could supplement my question, please feel free to add.

A: Without deep machinery, any field automorphism $\phi$ of $\Bbb C$ that leaves $\Bbb R$ pointwise fix is determined by $\phi(i)$ as we must have $\phi(x+iy)=x+\phi(i)y$. Also $$0=\phi(0)=\phi(1+i^2)=1+\phi(i)^2$$ implies that $\phi(i)\in\{i,-i\}$. Hence indeed there are exactly two such automorphisms: the identity and complex conjugation. So $G(\Bbb C/\Bbb R)$ is the group of order $2$.

A: As outlined in the comments, $\mathbb C = \mathbb R(i)$ makes it a degree 2 extension. It is normal but the fundamental theorem of algebra and separable because the characteristic is 0, hence Galois. So the size of the Galois group is the degree, and clearly complex conjugation works as the nonzero element generating that Galois group.

A: It is $\mathbb{C} = \mathbb{R}(i) $ with $ [\mathbb{C}: \mathbb{R}] = 2 $ since the minimal polynomial of $ i $ is $ X^2+1$. So the extension $\mathbb{C}/\mathbb{R}$ is a galois extension with galois group of order 2. Hence it is isomorphic to $\mathbb{Z}/2\mathbb{Z}$.


text:
Q: TSQL calculate the number of records I have 3 tables with relationships sets between them. Everything works fine.
Table Producent:
ProducentID (PK, int)
ProducentName (nvarchar)

Table Produced:
ProducentID (PK, FK, int)
FilmID (PK, FK, int)

Table Film:
FilmID (PK, int)
FilmName (nvarchar)

Each producent produced various number of films.
I need to generate the following output:
ProducentName | NumberOfProducedFilms

For example:
ProducentName | NumberOfProducedFilms
-------------------------------------
Peter P.      | 2
John J.       | 4
Michael M.    | 7
Edward E.     | 3

A: You should use count and group by as follows
SELECT P.producentname,
       Count(filmName) NumberOfProducedFilms
FROM   producent P
       JOIN produced PD
         ON P.producentid = PD.producentid
       JOIN film F
         ON PD.filmid = F.filmid
GROUP  BY P.producentname

A: Thank you @RF1991 for the hint!
This is the full answer:
SELECT P.ProducentName, COUNT(PD.FilmID) NumberOfProducedFilms FROM Producent P
JOIN Produced PD ON P.ProducentID = PD.ProducentID
JOIN Film F ON PD.FilmID = F.FilmID
GROUP BY P.ProducentName
ORDER BY P.ProducentName ASC


text:
Q: Можно-ли сбросить запрос на сервер? Пытаюсь сделать валидацию логина.
Валидация состоит из 3ех частей.

*

*Проверка логина на наличие символов

*Проверка логина через регулярное выражение

*Отправка данных на сервер и проверка занятости логина.

Может сложиться такая ситуация, что пока ответ придет с сервера пользователь удалит несколько символов и проверка вернет ошибку по пункту 2 (Проверка логина через регулярное выражение)
Можно ли как-то в этот момент отменить запрос на сервер.
Правка (больше деталей)
У логина есть 4 состояния:

*

*Пустой

*Не подходит

*Свободен

*Занят

У каждого из 4ех состояний имеется свой строковой параметр
Первые две проверки проходят локально.
Если они прошли отправляется запрос на сервер.
Блокировать UI не желательно.

A: Отслеживайте ввод и в зависимости от этого обрабатывайте ответ от сервера, а также отменяйте предыдущие запросы.
К примеру, введен логин, проходящий проверки -> Отправляется запрос -> вводится еще что-то -> запрос еще не отработал - отменили -> новый запрос -> вводится еще что-то -> запрос уже отработал, но так как входящие данные уже другие - с ответом ничего не делаем -> новый запрос -> ничего не вводилось -> обрабатываем ответ.


text:
Q: div based designing of an html page I am designing a div based html form but the design is not getting alligned properly
How to properly design a complicated  form in div based design. Does anyone have link of a complex form designed by using div based design.
Here is part of my html and css

<link rel="stylesheet" type="text/css" href="style.css" />

SERVICE CALL REPORT

  SERVICE CALL LOG

 <input type="text" class="textboxNormal" id="SerCallLog" name="txtSerCallLog" />

TYPE OF VISIT

            <select>
                <option value="Inspection">Inspection</option>
                <option value="Installation">Installation</option>
                <option value="Preventive">Preventive</option>
                <option value="Breakdown">Breakdown</option>
                <option value="Other">Other</option>
            </select>

TYPE OF SERVICE

            <select>
                <option value="WARRANTEE">WARRANTEE</option>
                <option value="EXCOMA">EXCOMA</option>
                <option value="COMA">COMA</option>
                <option value="SECOMA">SECOMA</option>
                <option value="SMA">SMA</option>
                <option value="SPUMA">SPUMA</option>
                <option value="OCS">OCS</option>
            </select>

CALL RECEIVED ON:

<input type="text" class="textboxNormal" id="CallRecOn" name="txtCallRecOn" />

TIME(in hrs.)

<input type="text" class="textboxNormal" id="CallTime" name="txtCallTime" />

CALL ATTENDED ON:

<input type="text" class="textboxNormal" id="CallAttendedOn" name="txtCallAttendedOn" />

TIME IN(in hrs.):

<input type="text" class="textboxNormal" id="TimeIn" name="txtTimeIn" />

TIME OUT(in hrs.):

<input type="text" class="textboxNormal" id="TimeOut" name="txtTimeOut" />

TIME ON CALL(in hrs.):

<input type="text" class="textboxNormal" id="TimeOnCall" name="txtTimeOnCall" />

ASSOCIATE DATA:NAME

<input type="text" class="textboxNormal" id="AssociateDataName" name="txtAssociateDataName" />

LOCATION:

<input type="text" class="textboxNormal" id="AssociateDataLocation" name="txtAssociateDataLocation" />

TEL:

<input type="text" class="textboxNormal" id="AssociateDataTel" name="txtAssociateDataTel" />

EQUIPMENT DATA SR.NO.:

<input type="text" class="textboxNormal" id="EquipmentDataSrNo" name="txtEquipmentDataSrNo" />

MODEL:

<input type="text" class="textboxNormal" id="EquipmentDataModel" name="txtEquipmentDataModel" />

LOAD DATA:

<input type="text" class="textboxNormal" id="EquipmentDataLoadData" name="txtEquipmentDataLoadData" />

BATTERY DATA:TYPE-

            <select>
                <option value="SMF">SMF</option>
                <option value="WT">WT</option>
            </select>

MAKE:

<input type="text" class="textboxNormal" id="BattaryDataMake" name="txtBattaryDataMake" />

VOLTS:

<input type="text" class="textboxNormal" id="BattaryDataVolts" name="txtBattaryDataVolts" />

AH:

<input type="text" class="textboxNormal" id="BattaryDataAh" name="txtBattaryDataAh" />

NOS:

<input type="text" class="textboxNormal" id="BattaryDataNOS" name="txtBattaryDataNOS" />

BATTERY CONDITION:CHARGING VOLTAGE:

<input type="text" class="textboxNormal" id="BattaryConditionChargingVoltage" name="txtBattaryConditionChargingVoltage" />

VDC

<input type="text" class="textboxNormal" id="BattaryConditionVDC" name="txtBattaryConditionVDC" />

DISCHARGE VOLTAGE(ON LOAD):

<input type="text" class="textboxNormal" id="BattaryConditionDiscVolt" name="txtBattaryConditionDiscVolt" />

VDC

<input type="text" class="textboxNormal" id="BattaryConditionOnLoadVDC" name="txtBattaryConditionOnLoadVDC" />

PREVENTIVE MAINTENANCE

Condition of Ventilation

Condition of Nut & Bolts of Equipment

Condition of Input & Output Cables

Condition of FAN , METER & LED Indication

Equipment cleaned with vacuum

                        <select>
                            <option value="Good">Good</option>
                            <option value="Bad">Bad</option>
                        </select>

                        <select>
                            <option value="Good">Good</option>
                            <option value="Bad">Bad</option>
                        </select>

                        <select>
                            <option value="Good">Good</option>
                            <option value="Bad">Bad</option>
                        </select>

                        <select>
                            <option value="Good">Good</option>
                            <option value="Bad">Bad</option>
                        </select>

                        <select>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>

Input Voltage
<input type="text" class="textboxNormal" id="InputVoltage" name="txtInputVoltage" />VAC
Output Voltage
<input type="text" class="textboxNormal" id="OutputVoltage" name="txtOutputVoltage" />VAC

Checked Battery Back up (In Min.)
<input type="text" class="textboxNormal" id="CheckedBattBackup" name="txtCheckedBattBackup" />

BATTERY MAINTEINANCE :

Condition of Nut, Bolts & Links :

Terminals & Lugs OK :

Filled D.M.Water :

Gravity & Voltage Checked :

Cleaning Done :

                        <select>
                            <option value="Good">Good</option>
                            <option value="Bad">Bad</option>
                        </select>

                        <select>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>

                        <select>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>

                        <select>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>

                        <select>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>

FAULT REPORTED

<input type="text" class="textboxNormal" id="faultReported" name="txtfaultReported" />

SOLUTION

            <textarea rows="2" cols="50"> </textarea>

REMARKS

            <textarea rows="2" cols="50"> </textarea>

Part of My css
 .mainContainer
    {
        width:100%;
        height:90%;
        background-color:gray;
    }

    .lblNormal
    {
        font-family:Verdana, Geneva, sans-serif;
        font-size:5px;
    }

    .textboxNormal
    {
        width:50px;
        height:8px;
    }
    .textboxLarge
    {
        width:100px;
        height:8px;
    }
    .textboxSmall
    {
        width:25px;
        height:8px;
    }

    #header
    {
        width:50%;
        height:10%;
        background-color:gray;
    }
    #callLog
    {
        width:40%;
        height:10%;
        border:1px solid black;
    }
    #callLog1
    {
        width:48%;
        height:90%;
        float:left;
        display:block;
    }

    #typeVisit
    {
        width:100%;
        height:10%;
        border:1px solid black;
    }
    #typeVisit1
    {
        width:24.5%;
        float:left;
        display:block;
        height:90%;
    }
    #callRec
    {
        width:100%;
        height:10%;
        border:1px solid black;
    }
    #callRec1
    {
        width:7.9%;
        height:100%;
        float:left;
        display:block;

    }

    #assoData
    {
        width:100%;
        height:10%;
    }
    #assoData1
    {
        width:16%;
        height:100%;
        float:left;
        display:block;
    }

    #equipData
    {
        width:100%;
        height:10%;

    }
    #equipData1
    {
        width:16%;
        height:100%;
        float:left;
        display:block;

    }
    #battData
    {
        width:100%;
        height:10%;
        background-color:red;
    }
    #battData1
    {
        width:9.9%;
        height:100%;
        float:left;
        display:block;
        background-color:red;
    }

    #battCond
    {
        width:100%;
        height:10%;
        background-color:blue;
    }
    #battCond1
    {
        width:11%;
        height:100%;
        float:left;
        display:block;
        background-color:green;
    }

    #maintenance
    {
        width:100%;
        height:20%;
        background-color:black;
    }

    #preveMaintMain
    {
        width:49%;
        height:100%;
        float:left;
        display:block;
        background-color:aqua;
    }
    #preveMaint
    {
        width:100%;
        height:100%;
        float:left;
        display:block;
        background-color:aqua;
    }
    #preveMaint1
    {
        width:32%;
        height:100%;
        float:left;
        display:block;
        background-color:red;
    }
    #preveMaintVolt
    {
        width:100%;
        height:100%;
        float:left;
        display:block;
        background-color:aqua;
    }

    #batMainNFault
    {
        width:49%;
        height:100%;
        float:left;
        display:block;
        background-color:red;
    }
    #battMaint
    {
        width:100%;
        height:60%;
        background-color:yellow;
    }
    #battMaint1
    {
        width:32%;
        height:100%;
        float:left;
        display:block;
        background-color:green;
    }

    #faltReported
    {
        width:100%;
        height:60%;
        background-color:yellow;
    }
    #faltReported1
    {
        width:32%;
        height:100%;
        float:left;
        display:block;
        background-color:green;
    }
    #faltReported2
    {
        width:64%;
        height:100%;
        float:left;
        display:block;
        background-color:green;
    }

    #solutions
    {
        width:100%;
        height:10%;
        background-color:GREEN;
    }
    #solutions1
    {
        width:14%;
        height:100%;
        float:left;
        display:block;
        background-color:RED;
    }
    #solutions2
    {
        width:85%;
        height:100%;
        float:left;
        display:block;
        background-color:YELLOW;
    }

    #remark
    {
        width:100%;
        height:10%;
        background-color:BLUE;
    }
    #remark1
    {
        width:14%;
        height:100%;
        float:left;
        display:block;
        background-color:YELLOW;
    }
    #remark2
    {
        width:85%;
        height:100%;
        float:left;
        display:block;
        background-color:RED;
    }

A: Not sure what is complicated about it or what your having difficulty with BUT, since your saying it looks bad in IE then I'm going to assume your not using a css reset.
What is a CSS RESET? In short, "

The goal of a reset stylesheet is to reduce browser inconsistencies in
  things like default line heights, margins and font sizes of headings,
  and so on.

Check this link first and download any of them (although i always use Eric Meyer's)
http://www.cssreset.com/
hit the "get code" button. Once you have it, insert it into your header.
Once done, style accordingly. All should look the same on the most popular browsers(if not all)


text:
Q: Batch refactoring to make Java method arguments final I'm looking around for a way to perform batch refactoring on a complete Java application. In this namely make method arguments final where it's not the case yet.
Does somebody in here knows about such a tool ? Or something that parses Java source and that can be extended with such changes.

A: You can do a bulk change in IntelliJ to change every field, local variable or parameter which can be final to be final.
Do a Code Analysis with the option, and "Apply Fix" globally, make sure it still compiles as it doesn't always get it 100% right in odd cases.

A: As Peter Lawrey suggests, IntelliJ does that.
Analyze -> Inspect code -> custom profile
There, in the "Code style issues" section, you have:
Field may be final
This inspection reports any fields which may safely be made final. A static field may
be final if it is initialized in its declaration or in one static class initializer, but
not both. A non-static field may be final if it is initialized in its declaration or in
one non-static class initializer or in all constructors.
Powered by InspectionGadgets

Local variable or parameter can be final
This inspection reports parameters or local variables, found in the specified inspection
scope, that may have a final modifier added.

Use check boxes in the inspection options below, to define whether parameters or local
variables (or both) are to be reported.

That will propably only make final the variable that can safely be so but the ones that you're trying to spot will remain non-final. Still, it's a way to spot them.

A: I don't know of any such refactoring in Eclipse or NetBeans. But a decent regular expression replace would do the trick. In order to make sure you don't accidentally perform it in places where it shouldn't happen, you might want to confirm each replace manually. This might not really be feasible if you have hundreds of classes, though. In that case, doing the replace everywhere and then checking a diff with the older version could be of use.
Should any argument not be made final because it is overwritten, it'll become clear during compilation.


text:
Q: How to create Rules for dynamically generated fields http://www.kosherjellyfish.com/test/index.php
I'm using the [jQuery Validation Plugin][1] for my form.
I have form fields within tables which are dynamically-generated: the number of tables is dependent on how many the users has created. A sample of the table below:
<?php (for $i=1;$i<3;$i++){?>

       Title *

          <select name="contactTitle<? echo $i;?> ">
          <option value="">Select Title</option>
          <option value="Dr">Dr</option>
          <option value="Miss">Miss</option>
          <option value="Mr">Mr</option>
          <option value="Mrs">Mrs</option>
          <option value="Ms">Ms</option>
          <option value="Professor">Professor</option>
         </select>

      First Name *
      <input type="text" name="contactFirstName<? echo $i;?>" style="width:280px;" />

<?php }  ?>

I wish to add validation rules to the dynamically generated input fields: it seems like I can't do it properly in the Validation Method itself, because I do not know the actual number of fields that's going to be generated:
$("#papersubmitform").validate(
        {
        rules:{
            //Can't add rules this way as I do not know how many rows will be generated.
            contactTitle: {required: true},
            contactFirstName: { required:true},

});

I've tried to add rules that'll be added on $(document).ready(function() once the page is loaded, but it does not seem to work.
$(document).ready(function() {
   $(".coauthortable").each(function(i){
            $(this).find(":input").each(function(){
                $(this).rules("add",{required:true});
            });
});

  $("#papersubmitform").validate();

});

Does anyone have any recommendations on what I should do to add the rules to dynamically-created elements?
I have created a sample page here in my own server... http://www.kosherjellyfish.com/test/index.php

A: You just need to do that in the opposite order:
$(document).ready(function() {
   $("#papersubmitform").validate();

   $(".coauthortable").each(function(i){
            $(this).find(":input").each(function(){
                $(this).rules("add",{required:true});
            });
    });
});


text:
Q: Form submit handler executing before ajaxStop I've set some handlers for this whole project to show/hide the loading div.
Some of them are ajaxStart, ajaxStop (both binded to $(document)) and submit that is bind to the forms.
I can't understand why the ajaxStop is executing after the form.submit in the sample bellow:

var blobs = [];

var echo = function echo(data, type) {
  var blob = window.URL.createObjectURL(new Blob([data], {
    "type": type
  }));

  blobs.push(blob);

  return blob
};

$(document).ready(function() {
  $('form').on('submit', function(e) {
    console.log('form submit');
    e.preventDefault();
  });
}).ajaxStart(function() {
  console.log('ajaxStart');
}).ajaxStop(function() {
  console.log('ajaxStop');
});

$('button').click(function() {
  $.get(echo("Sample data", "text/html"), function(data) {
    if (data != '')
      $('#frm').submit();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<form id="frm">
  <button type="button">
    Send
  </button>
</form>

A: The reason is because ajaxStop() is called after the complete event fires on all active AJAX requests.
You see the form submit in the console because you fire that event in the success handler, which occurs before complete.


text:
Q: homomorphism $\phi$ : $\mathbb Z$ $\rightarrow$ $\mathbb Z$ using $\phi(n)$=$2n$ A question from Visual group theory says :
consider the homomorphism $\phi$ : $\mathbb Z$ $\rightarrow$ $\mathbb Z$ by $\phi(n)$=$2n$,where the group operation on $\mathbb Z$ is '+'.
Would $\phi$ be an homomorphism if it were to use a different coeffiecient than 2?
I think it should remain so for any coeffiecient because it does not violate the properties for homomorphism. Am I correct?

A: Sure! If you just left $\phi(n)=kn$ then you can show that for all $k \in \mathbb{N}$ that the homomorphism properties hold.

A: To show that $\phi:(G,\ast)\to (G',\star)$ is an homomorphism for all $k \in \mathbb{Z}$, you just need to prove that for all $a,b \in G$:
$$\phi(a \ast b)=\phi(a) \star \phi(b)$$
So in the case of the endomorphism $\phi:(\mathbb{Z},+) \to (\mathbb{Z},+)$ with $\phi(n)=kn, k\in\mathbb{Z}$, this means that:
$$k(a+b)=ka+kb$$

A: The group ${\mathbb Z}$ is cyclic, so it suffices to define a homomorphism to another group by giving the image of its generator; we have two generators to choose from, $\pm 1$, so it's perfectly all right to define $\phi$ by giving $\phi(1)$.
${\mathbb Z}$ is free abelian, so any $\phi(1)$ is good.  On the other hand, if you consider ${\mathbb Z}/n{\mathbb Z}$, here the generator must satisfy $n\phi(\overline{1})=0$ for any group homomorphism
$$\phi:{\mathbb Z}/n{\mathbb Z}\to G.$$

In the case where $G={\mathbb Z}/m{\mathbb Z},$ the condition that $\phi(\overline{1})$ must satisfy due to the source group adds to the condition the target group satisfies, i.e.
$$\phi(\overline{1})\in {\mathbb Z}/m{\mathbb Z} \mbox{ and so } m\phi(\overline{1})=0.$$
This is best expressed by the well-known relation
$$Hom({\mathbb Z}/n{\mathbb Z}, {\mathbb Z}/m{\mathbb Z})={\mathbb Z}/d{\mathbb Z},$$
where $(m,n)=d$.
If $dm_1=m$, then $\phi(1)$ need be a multiple of $m_1$ in ${\mathbb Z}/m{\mathbb Z}$, so both relations satisfy.

By the above, one always has the relation (in principle, as sets)
$$Hom({\mathbb Z},G)=G$$ given by $\phi \mapsto \phi(1).$  However, the l.h.s. has a group structure only if $G$ is abelian, in general.  If $G$ is abelian, then the above bijection is a group homomorphism.


text:
Q: APEX - Parsing a recursive JSON I am programming to salesforce (APEX).
The input is complex and recursive JSON. Something like
{
    "id":"0",
    "children":[
        {
            "id":"1",
            "children":[...]
        },
        {
            "id":"2",
            "children":[...]
        }
    ]
}

I need a way to iterate a complex and recursive JSON (in APEX).
anyone can help?
Thanks,
Hagai

A: If you know the names of all the attributes in your JSON object, you can create classes to represent them and then deserialize.  For instance:
public class myObject {
  public String id;
  public List<myObject> children;
}

Then write a method that returns the children
static List<myObject> getChildren(myObject parent){
    List<myObject> children = new List<myObject>();
    for ( myObject c : parent.children ){
        children.addAll( getChildren(c) );
        children.add(c);
    }
    return children;
}

And finally put the two together:
myObject parent = (myObject)JSON.deserialize(jsonString,myObject.class);
List<myObject> all = new List<myObject>();
all.add(parent);
all.addAll(getChildren(parent));


text:
Q: markov-chains - Steady-state probabilities with multiple recurrent-classes
The following question is from MIT-OCW, 6.041 Spring (2006), Tutorial-12, 2.b.

For the Markov chain below. Assume that the process is in state-3 immediately before the first transition. Then, Find $\pi_i$ for $i = 1, 2, ..., 4$ the probability that the process is in state-$i$ after $10^{10}$ transitions or explain why these probabilities can't be found.

The solution here says - "If you assumed that $\pi_i$ denoted steady state probabilities, then these probabilities do not exist."
I want to know if the solution is wrong, since, I can compute the steady-state probabilities as follows:
Let $C_i$ be the recurrent-class corresponding to the recurrent state-$i$, then
$$
\begin{align}
\pi_i & = P_{steady} (state = i|absorbed = C_i)\, P(absorbed = C_i)
\end{align}
$$

A: The solution is wrong. Having been told that you start at $3$ and given this chain, the steady state distribution is $\frac{2}{5}(4/5,1/5,0,0) + \frac{3}{5}(0,0,0,1)=(8/25,2/25,0,3/5)$. This changes if you change the initial distribution (because there are two independent invariant distributions as a result of there being two recurrent classes), but that doesn't mean it simply doesn't exist.
The distribution after $10^{10}$ steps deviates from this by a tiny amount; in particular $p_3$ at this point is $2^{-10^{10}}$. The other probabilities will deviate by similar amounts. For this to work it was important that there is a self-edge from $1$ to $1$, so that the dynamics confined to $\{ 1,2 \}$ are aperiodic.


text:
Q: Centos 6.7 on VirtualBox loses network with SELinux disabled I've been struggling with this issue the whole day yesterday and it seems I'm in a dead end, too much Googling, reading, and trial and error without a result, so I decided to ask the gurus (you)
I'm gonna deploy (among other things) a CentOS 6.7 in 7 physical servers (which I don't yet the brand/model) with some packages, so.. in order to speed up things, I was making the whole procedure inside a Virtual Machine for avoiding any surprise later (I have only a pair of days)
The intallation procedures goes fine and I get into the system. I configure the network with static IP addreses, gateway and DNS, and everything goes fine.
I also have to disable SELinux and iptables service (client wants it disabled for their own reasons) and turn the max number of open files to 20000.
Here comes the problem. After rebooting, my eth0 is active and configured, BUT I cannot reach the gateway or any other IP.
A simple service network restart or ifdown/ifup eth0 solves this issue. BUT, again.. after rebooting.. same thing happens.
I've noticed that this does NOT happens if I let SELinux enabled (enforcing), in this case, I can reboot the machine and get to any IP without restarting the network service or the interface. Enabling/disabling iptables has no effect in this.
And this is where I still lost.
I'd also like to point out that before restarting the network service, if I execute a route command, it displays all the routes but the default gateway route with takes around 10 seconds to appear.
I'm Using:
-VirtualBox 5.0.2r102096 with bridged networking mode. I've tried WiFi and wired connection in the Host machine.
-CentOS 6.7 minimall install.
/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
UUID=7db47baa-d1d4-43b9-9ef6-f4f1ce42e30d
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
HWADDR=08:00:27:F0:AE:9F
IPADDR=192.168.1.10
PREFIX=24
DEFROUTE=yes
PEERROUTES=no
PEERDNS=no
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"

/etc/sysconfig/network
NETWORKING=yes
HOSTNAME=master01
GATEWAY=192.168.1.1
DNS=192.168.1.1

/etc/resolv.conf
nameserver 192.168.1.1

chkconfig

ifconfig

route -n

route (before restarting network service)

route (after restarting network service)

What else should I look?
Many, MANY thanks in advance for taking the time to read this question!!!!

A: Solved. It turned out to be a VirtualBox issue, apparently, with the driver for the Intel E1000 adapter, disabling SeLinux gave me this problem. Using PCnet-FAST III adapter with the same previous configurations (and other too) worked perfect! rebooted all times I wanted and I had the network working, whether or not SELinux is disabled.
Thanks to the people that replied!


text:
Q: Angular 2 Material Dialog box I am making an application with Angular 2 and Angular Material 2 and on one of the pages I have to use a dialog box. I checked out the description and usage on the MdDialog docs but that didn't solve my problem with my dialog box.
What I want for my dialog box is that when I open the dialog box, it shows me a list and when I click on one of the element of the list it goes to more options of that list.
--------------
|  Heading   |
| Option 1   |
| Option 2   |    --->  ----------------
| Option 3   |          | <-- Option 1 |
| Option 4   |          |  Option 1    |
| Option 5   |          |  Option 2    |
| Cancel  Ok |          |  Cancel   Ok |
-------------           ----------------

So like it is showed in the design when I click Option 1 then it takes me to more options of Option 1. And all of this is in the dialog box.
So how can I do this? Thanks!!

A: You could have a component in the dialog box that changes based on what the used clicked on. This way, you can open a dialog box, then the user can keep interacting with it, as the options inside it change. Then, you may close it, just like any MdDialog.


text:
Q: NIDAQmx Counter input Edge Source change I'm a little bit confused with my code. I want to read the position of a counter input (edge counter). I can get the Device and the channel but I want to change the Edge Source or the Terminal. If I add the channel the Edge Source is automatically "PFI0" which counts some different thing that I need. I want to change it to "PFI1" as seen in the picture. I tried the following, but it didn't work. Can someone please help me out!
import nidaqmx
def read_position():
    task = nidaqmx.Task()
    task.ci_channels.add_ci_count_edges_chan("Dev1/ctr0")
    task.ci_channels[0].ci_count_edges_term = "PFI1"
    task.start()
    pos = task.read()
    task.stop()
    task.close()
    return pos

Best regards,
Szilárd

A: You need to specify the device as well as the channel: instead of task.ci_channels[0].ci_count_edges_term = "PFI1" you should write task.ci_channels[0].ci_count_edges_term = "/Dev1/PFI1"
An easy way to check for the correct syntax is just to print the default channel: print(task.ci_channels[0].ci_count_edges_term)
Note how the / is necessary at the beginning of the string.


text:
Q: Laravel Auth::attempt() redirect me always to login page I'm trying to use Laravel Auth::attempt() function but it's always redecting me to login page, even when I use valide username and password.
This's my Route :
 Route::get('/login', 'PublicController@loginPage');
    Route::post('/login', 'PublicController@loginAction');

    Route::get('/users/members', array('before' => 'auth', function()
    {
        return View::make('users.members');
    }));

And this's my loginAction function :
public function loginAction() {
        $rules = array( 'username' => 'required',
                        'password' => 'required'
                        );
        $validator = Validator::make(Input::all(), $rules);

        if ($validator->fails()) {
             $messages = $validator->messages();
            return Redirect::to('login')
                                ->withErrors($validator)
                                ->withInput(Input::except('password'));
        }
    else {
        $user = array(
            'username' => Input::get('username'),
            'password' => Input::get('password')
        );
        $auth = Auth::attempt($user);

        if ($auth) {
            dd(Auth::check()); // this return always **True**
            return Redirect::to('users/members');
        } else {
            return Redirect::to('login')
                                ->withErrors(['Login Failed please try again']);}
        }

    }

When I use wrong username and password it show me the error message Login Failed please try again, and when I use valide data it rederict me to the Login page without showing any error
Update
The route filter :
Route::filter('auth', function()
{
    if (Auth::guest())
    {
        if (Request::ajax())
        {
            return Response::make('Unauthorized', 401);
        }
        else
        {
            return Redirect::guest('login');
        }
    }
});

Update 2 :
This my Profile Page (where I want to be redirected after login) :
Route::get('/users/members', function()
{
    dd(Auth::check()); This always return **false**
});

So the problem, as I think is that the users authentication is not saved after logged in.

A: After deep digging I've figured that the problem I was using different name for the primary key,user_id instead of id, in my database. So simply I've added this line my USER model
class User extends Eloquent {
    protected $primaryKey = 'admin_id';
....}

Notice If you are using a different name for the primary key rather  id then don't forget to add this propriety

protected $primaryKey = 'PrimaryKeyName';

This will solve tones of issues

A: Could you send us the relevant part of your filters.php
Route::filter('auth', function()
{
    // Your filter here
 }

I believe there is something in there that prevents the proper redirection.
For testing you could remove the filter from your route.
Route::get('/users/members', function() ...


text:
Q: Error audio loading when runing Whisper Open AI model The problem im trying to solve is that i cant run Whisper model for some audio, it says something related to audio decoding. payload.wav: Invalid data found when processing input. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
I tried using the micro-machines.wav and it works fine but when i used other audio it gives me an error
import whisper

model = whisper.load_model("base")
text=model.transcribe('micro-machines.wav',fp16=False)
print(text)
text=model.transcribe('payload.wav',fp16=False)
print(text)

Error im getting for payload
d:\...\venv\lib\site-packages\whisper\transcribe.py:79: UserWarning: FP16 is not supported on CPU; using FP32 instead
  warnings.warn("FP16 is not supported on CPU; using FP32 instead")
Traceback (most recent call last):
  File "d:\...\venv\lib\site-packages\whisper\audio.py", line 42, in load_audio
    ffmpeg.input(file, threads=0)
  File "d:\...\venv\lib\site-packages\ffmpeg\_run.py", line 325, in run
    raise Error('ffmpeg', out, err)
ffmpeg._run.Error: ffmpeg error (see stderr output for detail)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\....\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\.....\Python\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "D:\...\venv\Scripts\whisper.exe\__main__.py", line 7, in <module>
  File "d:\...\venv\lib\site-packages\whisper\transcribe.py", line 314, in cli
    result = transcribe(model, audio_path, temperature=temperature, **args)
  File "d:\...\venv\lib\site-packages\whisper\transcribe.py", line 85, in transcribe
    mel = log_mel_spectrogram(audio)
  File "d:\...\venv\lib\site-packages\whisper\audio.py", line 111, in log_mel_spectrogram
    audio = load_audio(audio)
  File "d:\...\venv\lib\site-packages\whisper\audio.py", line 47, in load_audio
    raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
RuntimeError: Failed to load audio: ffmpeg version 6.0-essentials_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enab
le-gmp --enable-lzma --enable-zlib --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-sdl2 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxv
id --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf
--enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libgme --enable-libopenmpt --enable-libo
pencore-amrwb --enable-libmp3lame --enable-libtheora --enable-libvo-amrwbenc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enab
le-librubberband
  libavutil      58.  2.100 / 58.  2.100
  libavcodec     60.  3.100 / 60.  3.100
  libavformat    60.  3.100 / 60.  3.100
  libavdevice    60.  1.100 / 60.  1.100
  libavfilter     9.  3.100 /  9.  3.100
  libswscale      7.  1.100 /  7.  1.100
  libswresample   4. 10.100 /  4. 10.100
  libpostproc    57.  1.100 / 57.  1.100
payload.wav: Invalid data found when processing input

i tried searching for solution and i found it says It appears that the code failed to load the audio file for some reason and even failed to display that error because e.stderr did not contain a valid UTF-8 string
if anyone can guide me it how i can solve this issue
Thank you


text:
Q: Identity provider and bookmarks I know that for security reasons we cannot save a different address in the bookmarks that the one we are visiting, but it is quite annoying in my case.
We have the secured site and the idp site in the same domain. When the customer arrives to the secured site (https://mysite.domain.com), he is redirected to the login page (https://idp.domain.com), with url parameters received from the secured website.
The fact is that if the customer tries to save a bookmark when in the login page, it should save the secured site url (https://mysite.domain.com), not the idp (https://idp.domain.com) who needs extra information for the authentication process flow.
I'm surprised I didn't see anything about it yet.
Anyone has a solution ?

A: The issue was if a customer bookmarked IDP.

*

*The user clicks on the bookmark

*The login page of the IDP is presented

*after authentication, user is redirected to website

*website has no storage data of OIDC, so exception

Changed the website so

*redirect to website root. If no token, storage of OIDC data and redirect to IDP.

*IDP has data from previous login and resends auth token and redirect to website.

*now localstorage data matches data received from IDP.


text:
Q: Expanding the textarea height I created this codes to make automatic expanding of textarea height when the text inside exceeded to height of the textarea but this only works in jsfiddle but when i run this in my project this doesnt work. does anyone can help me? Thanks.

 $("#ta").keyup(function (e) {
        autoheight(this);
    });

    function autoheight(a) {
        if (!$(a).prop('scrollTop')) {
            do {
                var b = $(a).prop('scrollHeight');
                var h = $(a).height();
                $(a).height(h - 5);
            }
            while (b && (b != $(a).prop('scrollHeight')));
        };
        $(a).height($(a).prop('scrollHeight') + 20);
    }

    autoheight($("#ta"));
 #ta {
        width:250px;
        min-height:116px;
        max-height:300px;
        resize:none;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="ta"></textarea>

A: If you are using jquery then you have to load Jquery library and add your code in the document ready or window load. Below is the updated code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>

#ta {
    width:250px;
    min-height:116px;
    max-height:300px;
    resize:none;
}

</style>

<script>
$(document).ready(function(){
$("#ta").keyup(function (e) {
    autoheight(this);
    console.log("log");
});
});

function autoheight(a) {
    if (!$(a).prop('scrollTop')) {
        do {
            var b = $(a).prop('scrollHeight');
            var h = $(a).height();
            $(a).height(h - 5);
        }
        while (b && (b != $(a).prop('scrollHeight')));
    };
    $(a).height($(a).prop('scrollHeight') + 20);
}

autoheight($("#ta"));
</script>

</head>
<body>

<textarea id="ta"></textarea>

</body>
</html>

A: It is working for me in IE 11 as well, try the below js fiddle link in IE -
https://jsfiddle.net/wp3wvuj2/3/
$(document).ready(function(){
$("#ta").keyup(function (e) {
autoheight(this);
console.log("log");
});
});

 function autoheight(a) {
if (!$(a).prop('scrollTop')) {
    do {
        var b = $(a).prop('scrollHeight');
        var h = $(a).height();
        $(a).height(h - 5);
    }
    while (b && (b != $(a).prop('scrollHeight')));
};
$(a).height($(a).prop('scrollHeight') + 20);
}

autoheight($("#ta"));


text:
Q: Best approach for analysis of proportional change I am interested in modelling a response that is a proportional change in  mechanical equipment health before the equipment is turned off, and then when it is brought back online again (so the treatment this in case is both conditions in the offline period and how its brought back online again).
The health measurement is strictly positive, it should have an upper bound of 100 but there are circumstances where it can exceed 100 legitimately. I have four continuous variables that I would like to include as explanatory variables - these relate to the conditions during the downtime and how the equipment is brought back online. We have only take the second health measurement once the equipment is considered safely online.
In this thread - Relative or Absolute Change for Test Statistic it was mentioned that proportional change was analysed traditionally using logarithms. From this thread I don't see the final step of modelling - should I be log transforming my response? And what would the appropriate GLM specification be in that case (family/link)?
I've also seen it recommended that a Beta distribution as the family in the GLM is appropriate for a ratio of two continuous variables (in my case, these are positive continuous variables).
I'm a bit confused as to which approach I should be taking - if anyone could clarify this it would be amazing.

A: In case anyone stumbles on this question - I found some additional relevant sources around the use of log transformations and alternatives to it (gaussian with log link) and potentially gamma distributions for evaluating a multiplicative relationship between response and regressors.
Log-linked Gamma GLM vs log-linked Gaussian GLM vs log-transformed LM
Linear model with log-transformed response vs. generalized linear model with log link


text:
Q: Fatal error during command execution (MySQL, VBNET) Tengo un problema al insertar unos datos desde una aplicacion VB.Net a una base de datos Mysql, el problema que tengo lo han preguntado muchas otras personas pero no puedo encontrar que exactamente que es en lo que falla mi codigo
Function Guardar_Datos() As Boolean
    Dim err As Boolean = False
    Dim con As New MySqlConnection
    Dim captura As String = ""
    con.ConnectionString = server
    Try
        con.Open()
        Try

            For f As Integer = 0 To DataGridView1.RowCount - 1
                captura = "INSERT INTO estatusdeot.presupuestos (`Presupuesto`, `Obra`, `Cliente`, `Direccion`, `Atencion`, [Ruta de Archivo], `Cotizo`, `Factor`, [Monto Ppto.], `Fecha`)" & _
                     "VALUES (@Presupuesto, @Obra, @Cliente, @Direccion, @Atencion, @RutadeArchivo, @Cotizo, @Factor, @MontoPpto, @Fecha);"
                Dim insertar As New MySqlCommand(captura, con)
                'insertar.Prepare()

                insertar.Parameters.AddWithValue("@Presupuesto", DataGridView1.Item(0, f).Value)
                insertar.Parameters.AddWithValue("@Obra", DataGridView1.Item(1, f).Value.ToString)
                insertar.Parameters.AddWithValue("@Cliente", DataGridView1.Item(2, f).Value.ToString)
                insertar.Parameters.AddWithValue("@Direnccion", DataGridView1.Item(3, f).Value.ToString)
                insertar.Parameters.AddWithValue("@Atencion", DataGridView1.Item(4, f).Value.ToString)
                insertar.Parameters.AddWithValue("@RutadeArchivo", DataGridView1.Item(5, f).Value.ToString)
                insertar.Parameters.AddWithValue("@Cotizo", DataGridView1.Item(6, f).Value.ToString)
                insertar.Parameters.AddWithValue("@Factor", DataGridView1.Item(7, f).Value)
                insertar.Parameters.AddWithValue("@MontoPpto", DataGridView1.Item(8, f).Value)
                insertar.Parameters.AddWithValue("@Fecha", DataGridView1.Item(9, f).Value.ToString)
                insertar.ExecuteNonQuery()
            Next
            err = False
        Catch ex As Exception
            MsgBox(ex.Message)
            err = True
        End Try
        con.Close()
        con.Dispose()
    Catch exc As Exception
        MsgBox("hubo un error al conectar con servidor " & vbCrLf & exc.Message, vbCritical)
    End Try
    Return err
End Function

El campo Presupuesto y el Campo Factor estan como Int(11) y el campo Monto esta como Decimal(15,2).
Gracias por su ayuda.


text:
Q: How to insert data from one table to another in array format? I'm setting up two Postgres tables table 1 and table 2.
Table 1 has a user_id and a name and description.
Table 2 has the same user_id as user and an array of name and description.
Now I want to insert data into name and description arrays of table2 from table1. All entries having the same user_id in table1 should have a single entry in table2 having user the same as that of user_id and the name and description arrays should have the rest data.
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
name VARCHAR NOT NULL,
description VARCHAR NOT NULL
)

table2(
id UUID PRIMARY KEY,
user UUID NOT NULL,
name VARCHAR [],
description VARCHAR [],
FOREIGN KEY (user) REFERENCES table1 table1 (user_id)
)

A: I think you want:
insert into table2 (id, user, name, description)
   select uuid_generate_v1(),  -- or whichever generation function you prefer
          user_id, array_agg(name order by id), array_agg(description order by id)
   from table1
   group by user_id;

Note the order by clause so the names and descriptions are in the same order in the arrays.


text:
Q: Close InternalJFrame without selected the frame I am really new for Java. I have question about getting the JInternalFrame . I searched the web and find the example. I modified the example a little bit, adding a close menuitem but it didn't work my code. In the project if I closed the JInternalFrame without select it first, then I have error. I tried to loop through the WindowMenu for getting the selected JcheckboxMenuitem, but it didn't get any components. Would someone tell me what to do.
There is the code:
// This is example is from Kjell Dirdal.
// Referenced from http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-mdi.html

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;

import javax.swing.DefaultDesktopManager;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class KjellDirdalNotepad extends JFrame {
private MDIDesktopPane desktop = new MDIDesktopPane();

private JMenuBar menuBar = new JMenuBar();

private JMenu fileMenu = new JMenu("File");

private JMenuItem newMenu = new JMenuItem("New");

private JScrollPane scrollPane = new JScrollPane();

private JMenuItem closeMenu=new JMenuItem("Close");
private int index=1;
private WindowMenu wMenu=null;

public KjellDirdalNotepad() {
   menuBar.add(fileMenu);
   wMenu=new WindowMenu(desktop);
   menuBar.add(wMenu);
   fileMenu.add(newMenu);
   fileMenu.add(closeMenu);
   setJMenuBar(menuBar);
   setTitle("MDI Test");
   scrollPane.getViewport().add(desktop);
   getContentPane().setLayout(new BorderLayout());
   getContentPane().add(scrollPane, BorderLayout.CENTER);

   addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
     System.exit(0);
   }
  });
newMenu.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
    desktop.add(new TextFrame(String.valueOf(index)));
    index=index+1;
  }
});

//I added the close menu
closeMenu.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        JInternalFrame f=desktop.getSelectedFrame();
         if (f==null)
         {
             for (Component child: wMenu.getComponents()){
                 if (child instanceof WindowMenu.ChildMenuItem){
                     JCheckBoxMenuItem item=(JCheckBoxMenuItem) child;
                    if( item.isSelected()){
                        DisplayTestMsg(item.getText());
                 }
             }
           }
           }
           else{
             f.dispose();
           }

        }
        });
     }
        public   void DisplayTestMsg(String msg){
    //custom title, error icon
     JTextArea textArea=new JTextArea(msg);
     textArea.setColumns(30);
     textArea.setLineWrap( true );
     textArea.setWrapStyleWord( true );
     textArea.setSize(textArea.getPreferredSize().width, 1);
     JOptionPane.showMessageDialog(null,
            textArea,
         "Test",
         JOptionPane.WARNING_MESSAGE);
 }
      public static void main(String[] args) {
        KjellDirdalNotepad notepad = new KjellDirdalNotepad();
        notepad.setSize(600, 400);
       notepad.setVisible(true);
      }

}

class TextFrame extends JInternalFrame {
  private JTextArea textArea = new JTextArea();
  private JScrollPane scrollPane = new JScrollPane();
 public TextFrame(String title) {
 setSize(200, 300);
 setTitle("Edit Text-" + title);
setMaximizable(true);
setIconifiable(true);
setClosable(true);
setResizable(true);
scrollPane.getViewport().add(textArea);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
 }
}

/**
 * An extension of WDesktopPane that supports often used MDI functionality. This
 * class also handles setting scroll bars for when windows move too far to the
 * left or bottom, providing the MDIDesktopPane is in a ScrollPane.
 */
class MDIDesktopPane extends JDesktopPane {
private static int FRAME_OFFSET = 20;
 private MDIDesktopManager manager;

  public MDIDesktopPane() {
    manager = new MDIDesktopManager(this);
    setDesktopManager(manager);
    setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
   }

  public void setBounds(int x, int y, int w, int h) {
    super.setBounds(x, y, w, h);
    checkDesktopSize();
  }

  public Component add(JInternalFrame frame) {
    JInternalFrame[] array = getAllFrames();
    Point p;
    int w;
    int h;

    Component retval = super.add(frame);
    checkDesktopSize();
    if (array.length > 0) {
      p = array[0].getLocation();
      p.x = p.x + FRAME_OFFSET;
      p.y = p.y + FRAME_OFFSET;
    } else {
     p = new Point(0, 0);
    }
    frame.setLocation(p.x, p.y);
    if (frame.isResizable()) {
      w = getWidth() - (getWidth() / 3);
      h = getHeight() - (getHeight() / 3);
      if (w < frame.getMinimumSize().getWidth())
         w = (int) frame.getMinimumSize().getWidth();
      if (h < frame.getMinimumSize().getHeight())
         h = (int) frame.getMinimumSize().getHeight();
      frame.setSize(w, h);
   }
    moveToFront(frame);
   frame.setVisible(true);
   try {
     frame.setSelected(true);
   } catch (PropertyVetoException e) {
      frame.toBack();
    }
    return retval;
  }

 public void remove(Component c) {
    super.remove(c);
   checkDesktopSize();
 }

  /**
   * Cascade all internal frames
   */
  public void cascadeFrames() {
    int x = 0;
    int y = 0;
    JInternalFrame allFrames[] = getAllFrames();

    manager.setNormalSize();
    int frameHeight = (getBounds().height - 5) - allFrames.length * FRAME_OFFSET;
    int frameWidth = (getBounds().width - 5) - allFrames.length * FRAME_OFFSET;
    for (int i = allFrames.length - 1; i >= 0; i--) {
         allFrames[i].setSize(frameWidth, frameHeight);
        allFrames[i].setLocation(x, y);
       x = x + FRAME_OFFSET;
      y = y + FRAME_OFFSET;
    }
  }

  /**
   * Tile all internal frames
   */
  public void tileFrames() {
    java.awt.Component allFrames[] = getAllFrames();
    manager.setNormalSize();
    int frameHeight = getBounds().height / allFrames.length;
    int y = 0;
    for (int i = 0; i < allFrames.length; i++) {
       allFrames[i].setSize(getBounds().width, frameHeight);
      allFrames[i].setLocation(0, y);
      y = y + frameHeight;
    }
  }

  /**
   * Sets all component size properties ( maximum, minimum, preferred) to the
   * given dimension.
   */
  public void setAllSize(Dimension d) {
    setMinimumSize(d);
    setMaximumSize(d);
    setPreferredSize(d);
  }

  /**
    * Sets all component size properties ( maximum, minimum, preferred) to the
   * given width and height.
   */
  public void setAllSize(int width, int height) {
    setAllSize(new Dimension(width, height));
  }

  private void checkDesktopSize() {
    if (getParent() != null && isVisible())
      manager.resizeDesktop();
  }
}

/**
 * Private class used to replace the standard DesktopManager for JDesktopPane.
 * Used to provide scrollbar functionality.
 */
class MDIDesktopManager extends DefaultDesktopManager {
  private MDIDesktopPane desktop;

  public MDIDesktopManager(MDIDesktopPane desktop) {
    this.desktop = desktop;
  }

  public void endResizingFrame(JComponent f) {
    super.endResizingFrame(f);
    resizeDesktop();
  }

  public void endDraggingFrame(JComponent f) {
    super.endDraggingFrame(f);
    resizeDesktop();
  }

  public void setNormalSize() {
    JScrollPane scrollPane = getScrollPane();
    int x = 0;
    int y = 0;
    Insets scrollInsets = getScrollPaneInsets();

    if (scrollPane != null) {
      Dimension d = scrollPane.getVisibleRect().getSize();
      if (scrollPane.getBorder() != null) {
        d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
            - scrollInsets.top - scrollInsets.bottom);
      }

       d.setSize(d.getWidth() - 20, d.getHeight() - 20);
      desktop.setAllSize(x, y);
      scrollPane.invalidate();
      scrollPane.validate();
    }
  }

  private Insets getScrollPaneInsets() {
    JScrollPane scrollPane = getScrollPane();
    if (scrollPane == null)
      return new Insets(0, 0, 0, 0);
    else
      return getScrollPane().getBorder().getBorderInsets(scrollPane);
  }

   private JScrollPane getScrollPane() {
     if (desktop.getParent() instanceof JViewport) {
       JViewport viewPort = (JViewport) desktop.getParent();
     if (viewPort.getParent() instanceof JScrollPane)
       return (JScrollPane) viewPort.getParent();
    }
     return null;
   }

  protected void resizeDesktop() {
    int x = 0;
    int y = 0;
    JScrollPane scrollPane = getScrollPane();
    Insets scrollInsets = getScrollPaneInsets();

    if (scrollPane != null) {
      JInternalFrame allFrames[] = desktop.getAllFrames();
      for (int i = 0; i < allFrames.length; i++) {
        if (allFrames[i].getX() + allFrames[i].getWidth() > x) {
           x = allFrames[i].getX() + allFrames[i].getWidth();
        }
        if (allFrames[i].getY() + allFrames[i].getHeight() > y) {
          y = allFrames[i].getY() + allFrames[i].getHeight();
        }
      }
      Dimension d = scrollPane.getVisibleRect().getSize();
      if (scrollPane.getBorder() != null) {
        d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
        - scrollInsets.top - scrollInsets.bottom);
      }

      if (x <= d.getWidth())
        x = ((int) d.getWidth()) - 20;
      if (y <= d.getHeight())
        y = ((int) d.getHeight()) - 20;
      desktop.setAllSize(x, y);
      scrollPane.invalidate();
      scrollPane.validate();
    }
  }
}

/**
 * Menu component that handles the functionality expected of a standard
 * "Windows" menu for MDI applications.
 */
 class WindowMenu extends JMenu {
  private MDIDesktopPane desktop;
  private JMenuItem cascade = new JMenuItem("Cascade");
  private JMenuItem tile = new JMenuItem("Tile");

  public WindowMenu(MDIDesktopPane desktop) {
    this.desktop = desktop;
    setText("Window");
    cascade.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        WindowMenu.this.desktop.cascadeFrames();
      }
    });
    tile.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        WindowMenu.this.desktop.tileFrames();
      }
    });
    addMenuListener(new MenuListener() {
      public void menuCanceled(MenuEvent e) {
      }

  public void menuDeselected(MenuEvent e) {
    removeAll();
  }

  public void menuSelected(MenuEvent e) {
    buildChildMenus();
  }
});
  }

  /* Sets up the children menus depending on the current desktop state */
  private void buildChildMenus() {
      int i;
     ChildMenuItem menu;
     JInternalFrame[] array = desktop.getAllFrames();

     add(cascade);
     add(tile);
     if (array.length > 0)
       addSeparator();
       cascade.setEnabled(array.length > 0);
      tile.setEnabled(array.length > 0);

    for (i = 0; i < array.length; i++) {
      menu = new ChildMenuItem(array[i]);
      menu.setState(i == 0);
      menu.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          JInternalFrame frame = ((ChildMenuItem) ae.getSource()).getFrame();
          frame.moveToFront();
          try {
            frame.setSelected(true);
          } catch (PropertyVetoException e) {
            e.printStackTrace();
          }
        }
      });
      menu.setIcon(array[i].getFrameIcon());
      add(menu);
    }
  }

  /*
   * This JCheckBoxMenuItem descendant is used to track the child frame that
   * corresponds to a give menu.
   */
  class ChildMenuItem extends JCheckBoxMenuItem {
    private JInternalFrame frame;

    public ChildMenuItem(JInternalFrame frame) {
      super(frame.getTitle());
      this.frame = frame;
    }

    public JInternalFrame getFrame() {
      return frame;
    }
  }

}

A: If you want to remove the JPanel when a button is pressed, you can call JFrame.remove(panel) such as:
final JFrame frame = new JFrame("test");
final JPanel panel = new JPanel();
//add the panel at the start
frame.add(panel);
// when the buttons clicked
button.addActionListener(new ActionListener() {
    @Override
    public void ActionPerformed(ActionEvent e) {
        frame.remove(panel);
        frame.repaint();
    };
});

A: I figured it out. I added the method on Class WindowMenu as belows. This method is called when the close button is click without selected internal frame.
   public JInternalFrame getFrontFrame(){
   InternalFrame[] array = desktop.getAllFrames();
  JInternalFrame f=(JInternalFrame)array[0];

 return f;

 }


text:
Q: How do I solve the "TypeError: can only concatenate str (not "int") to str" I get a type error I cannot solve
This is to construct a counter for a dictionary:
counts = dict()
names = ['csev','cwen', 'csev', 'zqian', 'cwen']

#makes new tally for new names and updates existing names
for name in names :
    if name not in counts:
        counts[name] = 1
    else:
        counts[name] = counts[name + 1]

print(counts)

Should output:
{'csev':2, 'zqian':1, 'cwen':2}

A: change the line10 to
counts[name] = counts[name]+1

A: Even though the only problem you have is counts[name + 1] (should be counts[name] + 1 since you want to increment the count not the name), you should consider using a collections.Counter for this task:
from collections import Counter
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
counts = Counter(names)

and while Counter is a dict-like object, if you want a dict object, use:
counts = dict(Counter(names))


text:
Q: how to create multiple form elements dynamically inside a form using symfony2 and doctrine2 I have a form which is linked to 3 tables in a database.
The first table's  Form has an access to the second table's form which has access to the third form's type.
The way it works is as follows:
firstType has following structure
$builder->add('second', new secondType())

secondType has following
$builder->add('third', 'collection', array(
    'type', new thirdType(),
    'allow_add' => true,
    'by_reference' => false,
))

The thirdType:
$builder->add('a')->add('b')

Of course the firstType and secondType has more elements and firstType is linked with secondType via a onetoone mapping and secondtype is linked with thirdtype via a onetomany mapping.
Above structure is so that i can map many instances of third table with 1 instance of second. Now the problem I have is that i cannot access the third table in a twig form. The error I am getting is

Method "a" for object "Symfony\Component\Form\FormView" does not exist in x.html.twig at line 120

I am trying to access it like this:
{{ form_label(form.second.third.a) }}

The same format works for elements of second. e.g.
{{ form_label(form.second.a_2) }}

I tried to follow:
http://symfony.com/doc/2.7/cookbook/form/form_collections.html
http://symfony.com/doc/2.7/reference/forms/types/collection.html
without success.

A: The problem here seems to be that second has a collection of third so you need to iterate over form.second.third and then for each element you can get the "a" element. I have never showed embed form in that way but you could try something like:
{% for element in form.second.third %}
   {{ form_label(element.a) }}
{% endfor %}

Hope this help you


text:
Q: ZF2 - Formatting Routes I typically format my routes in ZF2 like so: /name/to/route
Now I have been doing the same thing with my api routes however I am finding that I am struggling to include data such as encoded urls or arrays.
Here is an example of such a route:
http://example.com/api/register/access/code/c102dea422fa4bb6958d77a29d9873d2/http%3A%2F%2Frouter-local.example.com%2Fapi%2Fdirectory

The following represents forward slashes and thus causes the route not to work: %3A%2F%2
I am thinking I should encode my route as such:
http://example.com/api/register/access/code/?access_code=c102dea422fa4bb6958d77a29d9873d2&route=http%3A%2F%example.com%2Fapi%2Fdirectory

How do you configure the module.config file to deal with this?
Currently it is set as such in apigility:
'api.rpc.register-access-code' => array(
                'type' => 'Segment',
                'options' => array(
                    'route' => '/api/register/access/code/:access_code/:route',
                    'defaults' => array(
                        'controller' => 'Api\\V1\\Rpc\\RegisterAccessCode\\Controller',
                        'action' => 'registerAccessCode',
                    ),
                ),
            ),

EDIT
I have encoded my routes to include GET parameters by doing the following:
    $url = "http://example.com/api/register/access/code/";
    $params = [
        'access_code' => 'c102dea422fa4bb6958d77a29d9873d2',
        'route' =>  'http://example.com/api/directory'
    ];

    $final = $url . "?" . http_build_query($params);

Which gives this:
http://example.com/api/register/access/code/?access_code=c102dea422fa4bb6958d77a29d9873d2&route=http%3A%2F%2Fexample.com%2Fapi%2Fdirectory
However this breaks due to a "The requested URL could not be matched by routing." error.
The route is unidentified due to the interpretation of the slashes in the included URL.
Perhaps the issue is to do with how the URL is formatted and included as a parameter?

A: You don't define query variables in the segment route option; only the path.
You may append ?query=vars to any url, regardless of route configuration. ZF2's url helpers should encode the query vars for you, you just have to create an array of query vars and give it to the helper function when creating a url.
<?php echo $this->url('api.rpc.register-access-code', array(), array('query' => array(
    'access_code' => 'c102dea422fa4bb6958d77a29d9873d2',
    'route' => 'http://router-local.example.com/api/directory',
))); ?>`

A: In this case, it would seem the problem is to do with htaccess or apache. The simplest solution has been to encode the url using: base64_encode($url) which can be de-coded at the other end.


text:
Q: Using \boxed{} in \newenvironment{envname}{here}{and here} There's a type of environment (shown below) which I'm using very frequently. I would like to define a new environment to begin it and end it with single commands.
\begin{equation}\boxed{\boxed{
\begin{gathered}
    i(t)=\frac{V_s}{R}\left[1-e^{-\frac{R}{L}t}\right]\\
    \textnormal{Time Constant (} \tau_L \textnormal{)} =\frac{L}{R}
\end{gathered}
}}\end{equation}

However, it seems *\boxed{}* cannot be split between the beginning-and-ending braces of \newenvironment{} \newenvironment{envname}{ *\boxed{* }{ *}* } (the parts enclosed in the asterisks have bad syntax).
Splitting two instances of "\boxed{}" is even worse syntactically.
For reference, this is the output I want:

I have to type out these formatted equations very frequently, and any way to condense the necessary commands is appreciated...
Is there a way to get around the syntactical issues and define a \newenvironment{name}{beginning}{ending} properly? If possible, I would like to avoid using extra packages.
Sorry if any part of this post seems stupid. I'm new to StackExchange...

A: With a "save box":
\documentclass{article}
\usepackage{amsmath}

\newsavebox{\doubleboxedbox}
\newenvironment{doubleboxed}
 {\begin{lrbox}{\doubleboxedbox}$\displaystyle}
 {$\end{lrbox}\boxed{\boxed{\usebox{\doubleboxedbox}}}}

\begin{document}

\begin{equation}
\begin{doubleboxed}
  \begin{gathered}
    i(t)=\frac{V_s}{R}\left[1-e^{-\frac{R}{L}t}\right]\\
    \text{Time Constant ($\tau_L$)}=\frac{L}{R}
  \end{gathered}
\end{doubleboxed}
\end{equation}

\end{document}

(I simplified the input for the second line).

With expl3 facilities:
\documentclass{article}
\usepackage{amsmath}

\NewDocumentEnvironment{doubleboxed}{b}{\boxed{\boxed{#1}}}{}

\begin{document}

\begin{equation}
\begin{doubleboxed}
  \begin{gathered}
    i(t)=\frac{V_s}{R}\left[1-e^{-\frac{R}{L}t}\right]\\
    \text{Time Constant ($\tau_L$)}=\frac{L}{R}
  \end{gathered}
\end{doubleboxed}
\end{equation}

\end{document}

A: Of course you cannot have unbalanced braces in the begin/end code. A way out is to use \boxes:
\documentclass[twocolumn]{article}

\usepackage{amsmath}

\newenvironment{boxedeq}{%
   \equation\setbox0=\hbox\bgroup$\gathered
  }{%
   \endgathered$\egroup
   \fbox{\fbox{\box0}}%
   \endequation
}

\begin{document}

\begin{boxedeq}
i(t)=\frac{V_s}{R}\left[1-e^{-\frac{R}{L}t}\right] \\
\textnormal{Time Constant ($\tau_L$)} =\frac{L}{R}
\end{boxedeq}

\end{document}

A: Another solution, using a patched version of the \doublebox command from fancybox:
\documentclass{article}
\usepackage{amsmath}
\usepackage{fancybox}
\usepackage{xpatch}
\makeatletter
\xpatchcmd{\@doublebox}{\advance\fboxsep .5pt}{\advance\fboxsep 2.5pt}{}{}
\newenvironment{boxedequation}{\equation\doublebox\bgroup$\gathered}
{\endgathered$\egroup\endequation}
\makeatother

\begin{document}

\begin{boxedequation}
    i(t)=\frac{V_s}{R}\left[1-e^{-\frac{R}{L}t}\right]\\
    \textnormal{Time Constant (} \tau_L \textnormal{)} =\frac{L}{R}
\end{boxedequation}

\end{document}


text:
Q: What is the auto generated
A:
This script tag will call .js files for jquery and put into your html.

And you can add script tag in .cshtml There is to way for this
1. Directly added script tag
@{
    ViewBag.Title = "Create";
}

Create

It's will be add this script under the RenderBody() method
  (RenderBody() method is in the Layout.cshtml file)

2.
You have to add below code into your Layout.cshtml
@RenderSection("scripts", required: false)

And you can add you can add your script into your View like this
@section scripts {

}

then this script file will be added to where you put your @RenderSection("scripts", required: false) code.

@RenderSection("Name", required: Boolean) code.
  Name: Type your name of whatever you want to call in .cshtml
  Boolean: You can write true or false. If true you have to add this section into your every .cshtml file use this Layout.cshtml. Else you haven't.


text:
Q: MVC Global variables reseting to null when entering another action method public class MusicController : Controller
{
    User currentUser;

    public PartialViewResult UploadMusic()
    {

        return PartialView("_UploadMusic");
    }

    [HttpPost]
    public ActionResult UploadMusic(List<HttpPostedFileBase> files)
    {
        EntityDBContext db = new EntityDBContext();
        List<Song> uploadedSongs = new List<Song>();

        foreach (var file in files)
        {
            if (file != null)
            {
                string songName = Path.GetFileName(file.FileName);
                byte[] songAsBytes = new byte[file.ContentLength];

                using (BinaryReader br = new BinaryReader(file.InputStream))
                {
                    songAsBytes = br.ReadBytes(file.ContentLength);
                }

                //Save new record in database
                Song song = new Song
                {
                    SongName = songName,
                    SongBytes = songAsBytes
                };

                uploadedSongs.Add(song);
            }
        }

        string userName = User.Identity.Name;
        currentUser = db.Users.Where(x => x.Username == userName).First();
        currentUser.UserSongs = uploadedSongs;

        return ShowSongs(currentUser.UserSongs);
    }

    public ActionResult ShowSongs(List<Song> UserSongs)
    {
        return View("ShowSongs", UserSongs);
    }

    public ActionResult Publish()
    {
        EntityDBContext db = new EntityDBContext();

        foreach (var song in currentUser.UserSongs)
        {
            if (song != null)
            {
                db.Songs.Add(song);
                db.SaveChanges();
            }
        }
        return View();
    }
}

ShowSongs view:
@model List<Vidafo.Models.Song>

@Html.ActionLink("Publish", "Publish")

The Problem
So I declare currentUser at the top of the controller. I then assign a value to that with this line here currentUser.UserSongs = uploadedSongs; This works fine but when the code goes into Publish() currentUser.UserSongs is null.
I need to have access to currentUser.UserSongs in more than one action method after assigning a value but it seems that it resets to null when it enters another action.

A: Object state isn't maintained across requests, that's not how web applications work.  Every time a request is sent to the server, a new instance of the controller object is created.  So any instance-level values are new.
In order to persist information across requests you need to persist it somewhere.  For something like a user context, session state is a common choice.  You'll probably want to wrap it in a common provider interface so as to not couple your controllers to an HTTP context, but at its core storing in session is simple:
HttpContext.Current.Session["someKey"] = someValue;

(You could even re-fetch from the database with each request.  It's slightly less performant, but very simple and robust.)
Don't count out the ASP.NET identity system for this, though.  ASP.NET is pretty good at abstracting a lot of this for you.  You're already using it here:
string userName = User.Identity.Name;

Then you use that value to get the user from the database.  You could extend the identity system to store a custom user object which fits your needs.  But that's a larger scope effort outside of this question.

A: For this you can make use of TempData i.e. store value in TempData dictionary. One problem here is MVC doesn't sore value of variable during postback i.e. during different action of same controller or calling another controller for this you can use temporary varialble TempData as suggested.


text:
Q: Programmatic icon styling/color manipulation iOS uses programmatic styling for tab style icon images. I was wondering if this functionality is public, and if not, is this something that can easily be done? I am not using the UITabBar, which is why I need this exposed. UITabBarItem does not seem to have any methods for accessing the manipulated image.
Basically I would need to:
1) add white tint to base color for the shape outlines
2) add gradients
3) add a diagonal border for the gloss effect
Which APIs are best suited for this kind of image manipulation?

A: Take a look at Matt Gallagher's Advanced drawing using AppKit for inspiration. He's talking about AppKit there, so you can't use his code directly in iOS, but many of the same tools are either available in iOS or have some sort of counterpart.


text:
Q: Why is my generated precompiled file so big when using a boost based library? I'm working on a project using libraries handled through vcpkg.
As compile time wasn't that great, I did some headers clean up and configured the project to use precompiled headers, putting STL and vcpkg headers inside.
I started to run into the infamous C1076, C3859 and C1060 errors, and a quick check to the generated pch showed me a massive 1.2GB file ...
I ran a build using the /showIncludes switch, and it appears that spirit-po, a Boost based library that I use for translations, references more than 2600 Boost headers. (My project just has 70 files, with nothing fancy)
It's the only Boost based library used in the project.
Just to be sure this was the culprit, I removed everything but the spirit-po files from the pch :
#pragma warning(push)
#pragma warning(disable : 4267)
#include <spirit_po/spirit_po.hpp>
#pragma warning(pop)

and the resulting generated file is still 1GB big ...
There's no difference in size between debug and release build.
With an empty pch file, the generated file is around 4MB.
Provided that a 250MB file is considered big, how come I end up with a file 4 times that size ?
With just that library in the pch I don't have errors compiling anymore, but I don't want the problem to arise again in the future.
I'm using Microsoft Visual Studio Community 2019 Version 16.8.4.
What are my options to improve the situation ?
Could this be a misconfiguration in Visual Studio ?
Do I have to ditch the library altogether to remove the Boost dependency ?
Is there another alternative ?
Thanks for reading me :)

A: *

*Header only libraries work because there are no details left out of those headers.

*Precompiled headers contain all the compiled information of the headers before start of the translation unit.

*A large part (the majority) of boost libraries are header only. To add insult to injury, they're highly generic meaning there will be many templates and their instantiations.
1 + 2 + 3 are the perfect storm. If the size is a concern, your better bet is to shield boost from your headers and include them in the select translation units that actively depend on them.

A: While doing some more research, I came across the following libraries :

*

*tinygettext :
+ Doesn't depend on Boost
- Needs Iconv library to work, which isn't that trivial to make it work on Windows even if it's available as a vcpkg package

*spiritless_po
+ Doesn't depend on Boost
+ Self contained
- Not compatible with spirit-po
I tested both, and I must say the last one is a perfect fit for my use, which is to use directly po files as translations ...
I guess it's not a fit all solution, but it might be enough for some.