text:
Q: Visual Studio Bring Background cmd.exe to Foreground Is it possible to rise a cmd.exe processes from the silent background mode to the visible foreground so I can LOOK at them?
Problem Background:
I'm using VS2008 working with a very large solution containing C#, C++, and Fortran. Occasionally (a few times a day) when building my project the build hangs and does not allow me to do anything in VS (resulting in the need to kill the process).  I have checked the output box, and there appears to be nothing helpful there.
Possible Cause:
I am thinking that maybe one of the cmd.exe windows that are spawned in the background may be waiting for some form of input, but to investigate I need to see those windows.
Search for Other Causes/Solutions:
If not this, is there a way to try to check and see if there is something else going on?  Is this a problem anyone else is having.  (Note: killing VS and reloading often fixes the problem first try, and the build process takes less than 15 seconds.)

A: If stopping and restart fixes the problem, I guess it's not an input problem.
For example when my build project halts, it's always the VB6 project or SVN that are upset. (strangely the VS projects always work fine).
Once one of these halt, they halt until they are fixed. Thus for the VB projects run and work-out what the model dialogue is saying and fix it. or on SVN it usually need a clean-up run on the directory.
The intermittent nature suggests some sort of timing issue, like a file been lock open etc.
You could attach another copy of visual studio to the cmd.exe and see where it's at. Not sure if you can get symbols for it, so it might be fun to diagnose.


text:
Q: Sending url values to model I am working on an Asp.Net-Core Razor Page app and I am trying to send from java script some variables to use in my Model.
Here is my js code:
 const val1 = new Date(document.getElementById('val1').value);
 const val2 = new Date(document.getElementById('val2').value);

 location.href = "./MyPage/SaveValues" + "&val1=" + val1 + "&val2=" + val2;

In my model:
public void OnGetSaveValues(string value1, string value2)
{

}

The problem is that I receive an error with localhost can't be found. How can I use the values from the url in my model?

A: In JavaScript, you don't use the ./MyPage which you use to get a razor page route with base url. In JavaScript, you need to retrieve the base url from the window. Without the base URL appended to the route, the browser will always tell you not found because the path is incorrect. This should be what you should be doing

 location.href = window.location.origin + "/MyPage/SaveValues/?value1=" + value1 + "&value2=" + value2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: javascript show text input field I am using the following coding in a website I am building but rather than the text input field showing if one option is selected, I need it show if the user selects other options as well?
for example oit currently shows the text input field if the user selects option 2 from the select menu but need to show as well if the user selects option 4 in the select menu, below is my jfiddle code so far
it currently shows the extra text input fields when Domestic+ is selected in the select menu but need the text input fields to show as well when Commercial is selected within the dropdown menu
I found something similar on stackoverflow, see link below
<http://stackoverflow.com/questions/21007591/using-jquery-to-hide-form-elements-based-on-selected-dropdown-option/33055467#33055467>

<http://jsfiddle.net/gxxkdz2m/2/>

Thank you in advance
Ian

A: use this javascript code:
$(document).ready(function () {
  $('#support select[name="support_plans"]').change(function () {
    if ($('#support select[name="support_plans"] option:selected').val() == 'Domestic+') {
        $('#extra').css('display', 'inline');
    } else {
        $('#extra').css('display', 'none');
    }
  });

});

A: Is this what you mean? I added comments explaining the code where I changed it.
$(document).ready(function () {
  $('#support select[name="support_plans"]').change(function () {
    // get selected plan value
    var plan = $('#support select[name="support_plans"] option:selected').val();
    // check whether 'Domestic+' or 'Commercial+' is selected
    if (plan == 'Domestic+' || plan =='Commercial+') {
          $('#extra').show();
      } else {
          $('#extra').hide();
      }
  });
});

Fiddle of my Version (updated your fiddle).
http://jsfiddle.net/gxxkdz2m/4/


text:
Q: Failed to apply kotlin-android Image
I been trying to run flutter using emulator but I couldn't do because it throws me a error like
FAILURE: Build failed with an exception.

*

*Where:

Build file 'C:\Users\SANO\test\android\app\build.gradle' line: 25
• What went wrong:
A problem occurred evaluating project ¹:app'. > Failed to apply plugin 'kotlin-android".

Could not create an instance of type org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProject Extension. > Could not generate a decorated class for type KotlinAndroidProjectExtension. > org/jetbrains/kotlin/gradle/plugin/KotlinTarget

. Try:
Run with --stacktrace option to get the stack trace. Run with info or-debug option to get more log output. Run wi th--scan to get full insights.

*

*Get more help at https://help.gradle.org
BUILD FAILED in 2s
Exception: Gradle task assembleDebug failed with exit code 1 Exited (sigterm)


text:
Q: JPA Criteria builder for dynamic query I have to write a method where I pass it some arguments and depending on which arguments are empty it modifies the query I need to execute at the end.
E.g. if I want to select from a table Customer that has an ID, name, surname and address the starting query would be SELECT * FROM Customer WHERE ID=myId AND name=myName AND surname=mySurname (and now we check if the address I sent is empty, if it is NOT, add it to the query).
I know how to do this in C#, by simply doing a starting string and then just adding to it and using ExecuteStoreQuery directly, but how would this look in Java? Is Criteria Builder a viable tool for this?
Thank you so much!

A: Using a CriteriaQuery, it is possible to do something like that (using Static JPA Metamodel Classes):
public List<Customer> findCustomer(Long myId, String myName, String mySurName, String myAddress) {
    CriteriaBuilder cb = enitityManager.getCriteriaBuilder();
    CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
    Root<Customer> root = query.from(Customer.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(root.get(Customer_.ID), myId));
    predicates.add(cb.equal(root.get(Customer_.NAME), myName));
    predicates.add(cb.equal(root.get(Customer_.SURNAME), mySurName));

    if(address != null) {
        predicates.add(cb.equal(root.get(Customer_.ADDRESS), myAddress));
    }

    query.select(root).where(cb.and(predicates.toArray(new Predicate[0])));

    return entityManager.createQuery(query).getResultList();
}

In this case, the address will only be checked if it is not null.
Another example without using Static JPA Metamodel (not 100% sure about this):
public List<Customer> findCustomer(Long myId, String myName, String mySurName, String myAddress) {
    CriteriaBuilder cb = enitityManager.getCriteriaBuilder();
    CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
    Root<Customer> root = query.from(Customer.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(root.get("ID"), myId));
    predicates.add(cb.equal(root.get("name"), myName));
    predicates.add(cb.equal(root.get("surename"), mySurName));

    if(address != null) {
        predicates.add(cb.equal(root.get("address"), myAddress));
    }

    query.select(root).where(cb.and(predicates.toArray(new Predicate[0])));

    return entityManager.createQuery(query).getResultList();
}


text:
Q: How to flatten array in JS? I have a data that is like following:
const data = [{
    ratings: [ { rating: 5 } ],
    counts: [ { count: 100 } ],
}];

And I want to flatten it in a sense that I want to get rid of arrays and have only objects, and end result to be:
const data = {
   ratings: { rating: 5 },
   counts: { count: 100 },
};

I tried to do something like this, but it is wrong and I believe I'm kind of over complicating it.
const flatten = data => {
                return data.reduce((r, { ...children }) => {
                    Object.assign(children, r);
                    if (children) Object.assign(flatten(...Object.values(children)), r);
                    return r;
                }, {})
              }

Any ideas?

A: You could create recursive function with reduce method to turn all arrays to objects assuming you have just objects in those arrays.

const data = [{ratings: [ { rating: 5 } ],counts: [ { count: 100 } ]}];

function flatten(arr) {
  return arr.reduce((r, e) => {
    const obj = Object.assign({}, e);
    for (let p in obj) {
      if (Array.isArray(obj[p])) {
        obj[p] = flatten(obj[p])
      }
    }
    return Object.assign(r, obj)
  }, {})
}

console.log(flatten(data))

A: If by any chance the data is result from JSON.parse :

var json = JSON.stringify( [{ratings:[{rating: 5}], counts:[{count: 100}]}] )

var result = JSON.parse(json, (k, v) => v[0] || v)

console.log( result )

A: Please check:
var data = [{ratings: [ { rating: 5 } ], counts: [ { count: 100 } ]}];

var flatten = function(data) {
  if (Array.isArray(data)) {
    data = data[0];
    for (var key in data) data[key] = flatten(data[key]);
  }
  return data;
}

console.log(flatten(data));

Please check @ CodePen
https://codepen.io/animatedcreativity/pen/842e17d2b9f83bc415513f937fc29be8


text:
Q: C# Socket Receive messes up data I am trying to create a client/server application which communicates through Sockets. But when I receive data it randomly messed up and does not always (sometimes) show the correct data. The code I use to receive data:
private static void ReceiveCallback(IAsyncResult AR)
{
     try
     {
        Socket socket = (Socket)AR.AsyncState;
        if (SocketConnected(socket))
        {
           int received = socket.EndReceive(AR);
           byte[] dataBuf = new byte[received];
           Array.Copy(_buffer, dataBuf, received);
           string text = Encoding.ASCII.GetString(dataBuf);
           if (!text.Contains("GET") && !text.Contains("HTTP") && text != null)
           {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + ":" + text);
           }
           socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
         }
      }
      catch
      {

      }
}

can someone explain me why this happends? Thanks in advance!
Also, I have tried to check untill it finds a character (which is on the end of every response '-' but that did not work). Unfortunatley this was the result:

A: I assume your socket is a TCP socket, since you're dealing with something like HTTP.
TCP deals with streams, not messages. So when you do your read, at most _buffer.Length bytes are read from the stream. This means that you can easily read just a part of the response - or rather, the response will be split between multiple callbacks. When you read enough by chance, everything works as expected. This is especially true when testing on localhost, because Windows treats localhost TCP very differently from the non-localhost case. But when it so happens that you don't read enough, text will not contain the whole response - and your data is broken.
Additionally, when received is zero, it means the other side has closed the stream and you should stop doing BeginReceive.

A: You have to loop on the socket receive until you get your entire message.
This also means that you must have an application level protocol.  What defines a message?
A termination character? Then loop on the read until you get that character.
A count of characters? Then loop on the read until you get that many characters.
Is the length of the message at the front of the message? Then loop until you get enough bytes to get the length, then loop until you get the entire message.

A: Your socket code looks fine to me. Characters encoding format in the .Net world is "Unicode", you should convert the bytes you receive to Unicode instead of ASCII :
string text = Encoding.Unicode.GetString(dataBuf);


text:
Q: How to use Apache spark to implement GraphSAGE? I want to use scala and spark to implement Graph algorithm GraphSAGE, then how to do it? Is there any source code?
I want to get the code for my question

A: I haven´t implemented yet this graph algorithms on top of Spark, the only available implementation, as far as I know, for using deep learning for graph analysis is this. It is a spectral graph convolution for semi-supervised learning, and it is a transductive algorithm. It can be used for node classification. I have plans to include more algorithms in the future like GraphSAGE.


text:
Q: Template pointer initialisation I have a template class
template <class T>
class MyTemplate
{
public:
    struct node
    {
        int a;
    };
    MyClass();
    ~MyClass();
private:
    static node* theNode;
};

template <class T>
MyClass::node* MyClass<T>::theNode = 0;

But the initialization of theNode fails -
use of class template requires template argument list
If I change the declaration to
MyClass<T>node* MyClass<T>::theNode = 0;

I get

error C2143: syntax error : missing ';' before '*'

Please can someone tell me what the correct syntax is?

A: Just change your definition:
template<class T>
typename MyClass<T>::node* MyClass<T>::theNode = 0;


text:
Q: Why function's (self, index)'s index doesn't get called inside the function and the function still works? I have this snippet of working and tested Python code:
def renameFiles(self, index):
    filename = self._filenames[self._current_index]
    newFilename = self.createNewFilename()
    self.currentFileName.setText(newFilename)
    dirname = os.path.dirname(filename)
    fullPath = os.path.join(dirname, newFilename)
    os.replace(filename,fullPath)
    self._filenames[self._current_index] = fullPath
    self.current_index = self._current_index

Why is it that the index in the def renameFiles(self, index): isn't called in anywhere inside the function and yet the function still works? (It may not be the most optimized and beautiful code, but still works)
I've searched for manuals and guides for hours now and still can't wrap my head around this. And I can't progress in my project until I understand how this works.
I'll gladly post more of the code if needed.

A: In python, a user-defined function can have as many "non-callable" arguments as you want. For example, the following is a valid function:
def f(a, b, c, d, e):
    print("Hello World")

However, unless you provide default values for variables a through e, calling the function without specifying them will raise an exception


text:
Q: Why can't python find the stdout channel, when running a .tcl file with subprocess? I am trying to capture the output of a .tcl script. Whenever I run the script I get the error: can not find channel named "stdout".
I tried using the "stdout=subprocess.PIPE" argument too, but to no avail.
Content of the .py file.
import subprocess

sBatchPath= "C:\\Program Files\\Altair\\2019\hm\\bin\\win64\\hmbatch.exe"
sScriptPath="\\test.tcl"
sArgs = sBatchPath +" -tcl "+ sScriptPath

x = subprocess.run(sArgs, capture_output=True, text=True)
print(x.stdout)

The content of the .tcl script:
puts "This is a test"

The error:
can not find channel named "stdout"

    while executing

"puts "This is a test""

    (file "/test.tcl" line 11)

    invoked from within

"source /test.tcl"

End of command file - terminating.

HM exiting with code 1

Without giving any output every script, I tried runs fine.
In case you wonder I use the "hmbatch.exe", because that way I am able to use HyperMesh commands too.
Why does Python subprocess fail to get the output?


text:
Q: Android path. Merge path array I have a surfaceview custom class. I drawn in it canvas an array of paths. This paths coordinates are generated by view dynamically added with inflate view. This is my run code:
public void run() {
    while (isItOK == true) {
        // perform canvas drawing
        if (!holder.getSurface().isValid()) {
            continue;
        }

        c = holder.lockCanvas();
        c.drawColor(Color.GREEN);
        c.drawBitmap(bitmap, 0, 0,null);

        if (ii>jj) {
            for(aaa = 2; aaa <= 50; aaa++) {
                if (rr[aaa] != null) {
                    // MIDDLEX = ss[aaa].getX();
                    // MIDDLEY = ss[aaa].getY();
                    path[aaa] = new Path();
                    path[aaa].moveTo(rr[aaa-1].getX() + 40, rr[aaa-1].getY() - 80);
                    path[aaa].cubicTo(rr[aaa-1].getX() + 40, rr[aaa-1].getY() - 80, ss[aaa].getX(), ss[aaa].getY(), rr[aaa].getX() + 40, rr[aaa].getY() - 80);
                    path[aaa].setFillType(Path.FillType.EVEN_ODD);
                    c.drawPath(path[aaa], paint);
                }

path[aaa] in an array of paths. rr[aaa] is the array of view dynamically added, and represent the start point and the end  point of a bezier curve. ss[aa] is an array of view dynamically added and represent the control point  of a bezier curve. How can I merge path[aaa] into one single path? Thanks in advance!


text:
Q: install4j: Change label color I have three Run executable or batch file actions that invokes my launch scripts, tails into the log files respectively, and verifies that each service has started entirely. I would have used the native launch action in install4j but these services need to start in order - synchronously - and take up to 30 seconds per service.
After each action, I have a Run script action that verifies the return code and determines whether the rest of the scripts should execute as well. On the form itself, it shows the installed components and I would like to add an icon and change the color of each label after it successfully launches.
If this has confused you, please see the screen shot below to get a better under standing.

And as always, thanks for your support.
Chris

A: The trick is how to get the form environment of a screen from a "Run script" action. A screen that can contain form components is an instance of com.install4j.api.screens.FormPanelContainer and that class provides access to the com.install4j.api.formcomponents.FormEnvironment.
In a "Run script" action, you can do this:
import java.awt.EventQueue;
import java.awt.Color;

EventQueue.invokeLater(new Runnable() {
    public void run() {
        FormEnvironment formEnvironment =
            ((FormPanelContainer)context.getScreenById("screenId")).getFormEnvironment();
        JComponent label = (JComponent)formEnvironment.getFormComponentById("componentId").
             getConfigurationObject();
        label.setForeground(Color.MAGENTA);
    }
});
return true;

with the appropriate values for "screenId" and "componentId".
for a more reusable solution add
import java.awt.EventQueue;
import java.awt.Color;

public static void changeColor(final String screenId, final String componentId,
                               final Color color, final Context context)
{
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            FormEnvironment formEnvironment =
               ((FormPanelContainer)context.getScreenById(screenId)).getFormEnvironment();
            JComponent label = (JComponent)formEnvironment.getFormComponentById(componentId).
                getConfigurationObject();
            label.setForeground(color);
        }
    });
}

to the static code on the "Installer->Custom Code & resources" step (install4j 6+) and call
changeColor("screenId", "componentId", java.awt.Color.GREEN, context);

in your "Run script" actions.

For setting an icon, you have to define the "Icon" property on one label component and use the "Initialization script" property to save it in the context and remove it from the label:
context.setVariable("checkIcon", configurationObject.getIcon());
configurationObject.setIcon(null);

Then after the call to label.setForeground(); in the above code snippets, you can call
    label.setIcon((Icon)context.getVariable("checkIcon"));


text:
Q: How to I send a Texture2D to a connected printer in Unity for iOS I have a dynamically generated Texture2D asset and I want to allow my user the ability to quickly print it out from within my Unity3D app.
I understand how this works natively with UIPrintInteractionController, And I am wondering if there is a way to accomplish this within Unity.

A: Yes, it's possible. There are many ways you can do this. The easiest one is:
1) Encode your texture to byte array, JPG or PNG.
2) Write iOS native plugin, and send your byte array to native side.
3) And print it using UIPrintInteractionController.


text:
Q: How to select single item/entity, ngrx? I have selector to get all posts, actually all entities, now I want to get single post/entity. Should I filter the posts I get from 'getAllPosts' selector or create another one and how to do it ?
Here are my selectors:

export const getPostsState = createFeatureSelector<fromPosts.PostState>('posts');

export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsIds = createSelector(getPostsState, fromPosts.getPostsIds);
export const selectTotal = createSelector(getPostsState, fromPosts.getPostsTotal);
export const selectPostId = createSelector(getPostsState, fromPosts.getSelectedPostId);

export const getSelectedPost = createSelector(selectPostsEntities, selectPostId, (entities, id) => entities[id]);

As you see I have getSelectedPostId and getSelectedPost selectors but I'm not sure how to use it, I tried to follow some tutorials but nothing helps..

A: Maybe it is a bit late, but it might help someone out there. You are using the same entity adapter selector for both, the list of entries and the entities. And you do not define what you want to do with your selected data. The last argument of the createSelector function should always be a function having arguments which are directly related to the before mentioned selectors and should return some value (usually the argument itself or a modification of it).
export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts); // <-- see

But it should use the selectEntities instead of selectAll. Imagine you get the selectors from the entity adapter like this and that you have your custom ID selector implemented:
// NgRX entity selectors
const {
  selectIds,
  selectEntities,
  selectAll,
  selectTotal,
} = adapter.getSelectors();

// Custom selector for the selected ID (I guess you have it in the store) and
// should be the equivalent of your `getSelectedPostId` selector.
const getSelectedId = createSelector(getState, state => state.id);

Then you can combine the selectEntities with the getSelectedId in the following way:
export const selectedEntity = createSelector(
  selectEntities,
  getSelectedId,
  (entities, id) => entities[id]
);

Personally I prefer to import the adapter in the selectors so that you can simply use the above statement in your reducer and make all of the adapter related selectors available where they are needed.


text:
Q: How does webservice maintain session when client is windows/Console app? How does webservice maintain session when client is windows/Console app?

A: Using cookies.
When you send HTTP requests, make sure to include a CookieContainer.  (assuming you're using HttpWebRequest)

A: Under the covers, the C# WebClient is storing the cookie given to it by the web service.

A: Here is some sample code if someone is interested.
class Program
{
    static void Main(string[] args)
    {
        CookieContainer session = new CookieContainer();

        HttpWebRequest httpSomeRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8080/someURL");
        httpSomeRequest.CookieContainer = session;
        httpSomeRequest.GetResponse();

        HttpWebRequest httpSomeOtherRequest  = (HttpWebRequest)WebRequest.Create("http://localhost:8080/someOtherURL");
        httpSomeOtherRequest.CookieContainer = session;
        httpSomeOtherRequest.GetResponse();
    }
}

We just need to make sure that every HttpWebRequest made, uses the same CookieContainer instance.


text:
Q: Can't use external Tomcat in MyEclipse I've added an external Tomcat into Window -> Preferences -> Servers -> Runtime Environments. After that, when I clicking the Run button in the toolbar, MyEclipse keeps running my web app by its embedded Tomcat.
I looked at the Run Configurations but found nothing like "Tomcat Server" except for "MyEclipse Server", which I'm not to use. What's the next step to use external Tomcat?

A: You've created a new Runtime Environment, but not the Server itself.

*

*Bring up the context menu in the Servers view and choose New > Server.

*In the New Server wizard, in the Server runtime environment combo, select the new runtime environment you defined earlier. Normally you would use the Create runtime environments link here to create the runtime here too, but you can skip this as you've already created one.

*You will now be able to start your server from the Servers view and from the Run / Debug dialogs.

You can always ask in the MyEclipse forum if you need further assistance, I hope this helps!


text:
Q: Multi table Triggers SQL Server noob I have a load of tables all with the same 2 datetime columns (lastModDate, dateAdded).
I am wondering if I can set up global Insert Update trigger for these tables to set the datetime values. Or if not, what approaches are there?
Any pointers much appreciated

A: I agree there is no such Global Trigger, but we can certainly reduce our efforts by creating script which will generate triggers for the tables.
Something like: http://weblogs.sqlteam.com/brettk/archive/2006/11/29/35816.aspx

A: No, there's no such thing as a "global" trigger or a multi-table triggers. Triggers are by design bound to a table, so if you need to have triggers on a load of tables, you need to create a load of triggers, one for each table, and deploy them. No way around that, I'm afraid.

A: since the code will be same and only table_name will be changed...
i think that best is to create procedure and then call this procedure from every trigger

A: You can use DEFAULT values for the inserts (dateAdded) and a TABLE trigger for the UPDATE.
Something like
CREATE TABLE MyTable (
        ID INT,
        Val VARCHAR(10),
        lastModDate DATETIME DEFAULT CURRENT_TIMESTAMP,
        dateAdded DATETIME DEFAULT CURRENT_TIMESTAMP
)
GO

CREATE TRIGGER MyTableUpdate ON MyTable
FOR UPDATE
AS
UPDATE  MyTable
SET     lastModDate = CURRENT_TIMESTAMP
FROM    MyTable mt INNER JOIN
        inserted i ON mt.ID = i.ID
GO

INSERT INTO MyTable (ID, Val) SELECT 1, 'A'
GO

SELECT *
FROM MyTable
GO

UPDATE MyTable
SET Val = 'B'
WHERE ID = 1
GO

SELECT *
FROM MyTable
GO

DROP TABLE MyTable
GO

A: Generate Triggers for all Tables
Well, I did this originally to generate triggers for all tables in a database to audit data changes, and that is simple enough, just move the entire row from the deleted table to a mirrored audit table.
But someone wanted to track activity on tables, so it's a little more simple.  Here we create one log table, and any time a dml operation occurs, it is written there.
Enjoy
USE Northwind GO

CREATE TABLE LOG_TABLE (Add_dttm datetime DEFAULT (GetDate()),
TABLE_NAME sysname, Activity char(6)) GO

DECLARE @sql varchar(8000), @TABLE_NAME sysname SET NOCOUNT ON

SELECT @TABLE_NAME = MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables

WHILE @TABLE_NAME IS NOT NULL   BEGIN  SELECT @sql = 'CREATE TRIGGER
[' + @TABLE_NAME + '_Usage_TR] ON [' + @TABLE_NAME +'] '   + 'FOR
INSERT, UPDATE, DELETE AS '   + 'IF EXISTS (SELECT * FROM inserted)
AND NOT EXISTS (SELECT * FROM deleted) '   + 'INSERT INTO LOG_TABLE
(TABLE_NAME,Activity) SELECT ''' + @TABLE_NAME + ''', ''INSERT''' + '
'   + 'IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM
deleted) '   + 'INSERT INTO LOG_TABLE (TABLE_NAME,Activity) SELECT '''
+ @TABLE_NAME + ''', ''UPDATE''' + ' '   + 'IF NOT EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted) '   + 'INSERT INTO
LOG_TABLE (TABLE_NAME,Activity) SELECT ''' + @TABLE_NAME + ''',
''DELETE''' + ' GO'  SELECT @sql  EXEC(@sql)  SELECT @TABLE_NAME =
MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME >
@TABLE_NAME    END SET NOCOUNT OFF


text:
Q: How do I send a JPEG file along with other data such as Strings and Integers from Android to a Server? I have a JPEG file and some other data (of type String and Integer) that I'm trying to send from an Android activity to a a REST Controller on my Server (Spring).
How can I do so? There are so many libraries out there I'm not sure which is deprecated or not or what are some best practices...
Thanks in advance!

A: One of the safest and fastest ways is using an MQTT server. It is not a simple solution, but the best for my programs:

*

*There is a good library on Android to send messages with pictures and other data.

*There are enough program languages that can connect to MQTT.

*Multiple Android devices can send data.

*Connection loss is solved by MQTT.

*Guarantee of delivering data: either in the same order or small chance on different order as sent by Android.

*It's secure.

*To improve security, I use base64 encoding, (also add sha256 checksums and dummy blocks with random data)

*For publishing on a website you need to program some backend part on the server.

*Most important: It's FREE

For details look:
https://mqtt.org/


text:
Q: To Convert C# published code and in to proper solution file I have one c# Application which i have only published Application in IIS and i don't have the original code with me.
we have to make some changes in one (.cs) file which is dependent on entire application and dlls.
Is it possible to convert the Application and make some changes and publish again.

A: I did run into this situation before where client is only having published code and I need to enhance a product.
For those , I decompiled published DLLs using Telerik's JustDecompile as I found it more mature and accurate than DotPeek and Reflector.
Few of the things will still not work after decompilation and that is obvious so you will need to manually fix those.
You may also remove few of the layers by introducing your own layer to avoid all DLL decompilation , but for that you need to understand decompiled code.
I hope that it will help you in running project.
Thanks,


text:
Q: Set anchorpoint for rotation in Titanium How can I set an anchor-point for the rotation of an image.
Over here, I need to place other images in a rotated/tilted manner w.r.t to the first image. So I need to set an anchor-point of rotation for the first image

A: On android you have to set the anchor point on the transform matrix.
On iOS you have to set the anchor point to the view you are trying to rotate.

IMPORTANT UNDOCUMENTED BEHAVIOUR:
  I've been struggling with this for a week and found out the following: If you try to set the anchorpoint to a view without first setting it's width or height, or setting them to Ti.UI.SIZE the anchorpoint will always be at 0,0.

You can try this code snippet which should work. Haven tested it, but you can get the idea.
This code should work for both platforms.
var anchor_x = 0.5;
var anchor_y = 0.5;

var view = Ti.UI.createView({
    // ALWAYS SET THE HEIGHT AND WIDTH!!!!
    // IF NOT ANCHOR WILL BE CALCULATED FROM WIDTH = 0 AND HEIGHT = 0
    width: Ti.UI.FILL
    height: Ti.UI.FILL
});

// It it's ios (iPad or iPhone)
if (Ti.Platform.platform == 'iPhone OS')
    view.anchorPoint = {x: anchor_x, y: anchor_y};

var transform;
// If it's android, create the 2DMatrix with the desired anchorpoint.
if (Ti.Platform.platform == 'android')
    transform = Ti.UI.create2DMatrix({anchorPoint: { x: anchor_x, y: anchor_y }});
else
    transform = Ti.UI.create2DMatrix();

// Apply rotation
transform = transform.rotate(90);

// Apply transformation to your view.
view.transform = transform;


text:
Q: Rectangle Selection Like Tool MS Paint C# I have been working on creating a program similar to MS Paint. I have several of the features it has down but the one which is currently giving me trouble is the rectangular selection tool. My program currently draws everything on the panel and saves it all in an ArrayList so each shape can be redrawn in Paint().
Like MS paint I would like the user to be able to select a section of the drawing on the panel and either copy it, move it, re-size it, or even delete it. I was thinking about having the user draw a rectangle & saving the information for it. Then taking that information for the rectangle, passing them to create a new Bitmap. I would then paint a new rectangle in the background color to give the appearance that the selected area was "removed" when the selected portion is moved. It sounded okay until I realized that I couldn't use the Graphics.FromImage() on the PaintEventArgs variable passed to Paint() which made my idea useless. Not sure if that makes sense so my apologies if it's a confusing mess.
I've been searching the internet for some assistance and I haven't found much to help so either this is very easy to do, very difficult, or "rectangle selection tool" is not the proper term. Any help or pointers would be greatly appreciated!!! Thank you for your time! :)

A: I understand that you actually have the Rectangle and now would like to copy an area from your painted Panel.
This is possible, assuming you have, as you should, placed all the painting in the Paint event of the Panel.
Then you can, use DrawToBitmap to ask the Panel to draw itself onto a new Bitmap; from there you can DrawImage the Rectangle onto your Panel.
Note: For this to integrate with your list of 'Paint-Actions' you will have to either now store that Bitmap or store the Rectangle and redo the whole operation.
using (Graphics G = panelCanvas.CreateGraphics() )
{
    Rectangle R0 = new Rectangle(22,22,55,55); // your Rectangle!
    using (Bitmap bmp = new
           Bitmap(panelCanvas.ClientSize.Width, panelCanvas.ClientSize.Height))
    {    panelCanvas.DrawToBitmap(bmp, panelCanvas.ClientRectangle);
         G.DrawImage(bmp, 111f, 111f, R0, GraphicsUnit.Pixel);
    }
}

Aside: Please do replace the ArrayList, which is depracated by the new List<T>, e.g. a List<PaintAction> or whatever name your class has!
If you simply want to extract a rectanglular area from the Panel Control you can use thsi function:
public Bitmap getAreaFrom(Control ctl, Rectangle area)
{
    Bitmap bmp2 = new Bitmap(area.Width, area.Height);
    using (Graphics G = ctl.CreateGraphics())
    using (Bitmap bmp = new Bitmap(ctl.ClientSize.Width, ctl.ClientSize.Height))
    {
        ctl.DrawToBitmap(bmp, ctl.ClientRectangle);
        using (Graphics G2 = Graphics.FromImage(bmp2))
            G2.DrawImage(bmp, 0f, 0f, area, GraphicsUnit.Pixel);
    }
    return bmp2;
}


text:
Q: How to combine html with php I'm trying to connect php with html form. Currently my code looks like this:
<? php

$path = "books /";
$books = opendir ($path);
while (($book = readdir ($books))! == false)
{
    if (substr ($book, -4) === ".txt")
    {
        $filePath = $path. $book;
        // echo $book;

        $readFile = fopen ($filePath, "r+") or die ("Permission error");
        $infoBook = fread ($readFile, filesize($filePath));
        echo $infoBook;
        echo "
";
        $writeInfo = fwrite ($readFile, filesize($filePath));
        fclose ($readFile);
    }

}
closedir ();

?>

        <title> Books Form </title>
        <meta charset = "UTF-8">
        <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">

        <form method = "post" action="<? php $_SERVER ['PHP_SELF'];?>" id = "bookform">

            <select name = "book" id = "books" form = "bookform">

                <option value = "blank"> </option>
                <option value = "Atlas_chmur.txt"> Cloud Atlas </option>
                <option value = "Dune.txt"> Dune </option>
            </select>

            <button style = "position: relative; left: 240px" type = "submit" form = "form" value = "<? php $readFile = fopen ($book," r + ");?>" name = "click" > Load </button>

            <textarea name = "info" rows = "30" cols = "100">
                <? php echo $infoBook?>
            </textarea>

            <button type = "submit" form = "form" value = "Submit"> Save </button>

        </form>

I don't really know how to add files returned in a loop to combobox ( ) so that I can select a specific one and display it later in
Thank you in advance for your help

A: you can do it in PHP simply like that
<?php for ($x = 0; $x <= 10; $x++): ?>
  <option value="<?= $x ?>"><?= $x ?></option>
<?php endfor; ?>

at each iteration in the loop, an option will be added. you can use the same principle with your array


text:
Q: Cannot get subEntityId on MS Teams tab app from deep link I cannot retrieve a subEntityId on a Teams tab app from a deep link. It's always empty in getContext. Could anyone please help me out?
I generated a deep link as following this page, https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links
The link looks like this,
https://teams.microsoft.com/l/entity/58061894-78f0-49c3-99d7-25830d1c84f0/anpi-personal&context=%7B%22subEntityId%22:%22task123%22%7D

The link works as it expected, it brings me to the tab app on Teams. But no subEntityId.
The manifest of the tab app looks like this,
{
  "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.7/MicrosoftTeams.schema.json",
  "manifestVersion": "1.7",
  "version": "1.0.0",
  "id": "58061894-78f0-49c3-99d7-25830d1c84f0",
  "packageName": "something.package.name",
  "developer": {
    "name": "dev",
    "websiteUrl": "some url",
    "privacyUrl": "some url",
    "termsOfUseUrl": "some url"
  },
  "icons": {
    "color": "color.png",
    "outline": "outline.png"
  },
  "name": {
    "short": "some name",
    "full": "some text"
  },
  "description": {
    "short": "some text",
    "full": "some text"
  },
  "accentColor": "#FFFFFF",
  "staticTabs": [
    {
      "entityId": "anpi-personal",
      "name": "app name",
      "contentUrl": "https://exmample.com/Default.aspx?entityId={entityId}&subEntityId={subEntityId}",
      "scopes": [
        "personal"
      ]
    }
  ],
  "permissions": [
    "identity",
    "messageTeamMembers"
  ],
  "validDomains": [
    "foo.com"
  ],
  "webApplicationInfo": {
    "id": "13958568-6984-47d4-910f-7bb9c87078c2",
    "resource": "api://exmample.com/13958568-6984-47d4-910f-7bb9c87078c2"
  }
}

A: I think you need to change:
...anpi-personal&context=%7B%22subEntityId%22:%22task123%22%7D
to:
...anpi-personal?context=%7B%22subEntityId%22:%22task123%22%7D
the change is hard to see - I've changed "&context" to "?context" - "&" is required if you have -multiple- values you're passing (like "weburl=something" AND "context=something"), but in this case you only have "context", so it needs to start with "?"


text:
Q: How to find bold text line from image using python? enter image description here    from PIL import Image
    import pytesseract
    from pdf2image import convert_from_path
    import os
    import pandas as pd
    import numpy as np
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('grey.png',gray)
binary,thresh1 = cv2.threshold(gray, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
cv2.imwrite('Thresh1.png',thresh1)
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 3))
dilation = cv2.dilate(thresh1, rect_kernel, iterations = 2)
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
im2 = img.copy()

ROI_number = 0

for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    ROI=im2[y:y+h, x:x+w]
    print(str(w),str(h))
    #cv2.putText(im2, str(h), (x,y - 10 ), cv2.FONT_HERSHEY_SIMPLEX, 0.1, (255, 0, 0), 1)
    #cv2.putText(im2, str(w), (x,y + 10 ), cv2.FONT_HERSHEY_SIMPLEX, 0.1, (0, 0, 255), 1)
    #cv2.imwrite('ROI_{}.png'.format(ROI_number),ROI)
    cv2.rectangle(im2,(x,y),(x+w,y+h),(36,255,12),1)
    ROI_number += 1

cv2.imwrite('contours1.png',im2)

How to make a filter which detect the bold lines part from image Bold text line should be the output for me .Don't know to approach this thing but i have a suggestion to get that thing in order of Binary inversion Threshold covert to get the white bigger part should come from that need suggestions regarding this Problem.


text:
Q: Why is my delegate not working even when I complete all of the necessary steps? I am trying to use a delegate to pass an array of data to the previous view controller. I have decided to use a delegate as my unwind segues are not working (more on that in a previous Stack Overflow post). I have created the delegate performing all of the necessary steps for setting it up.
I have tried some solutions from this Stack Overflow question but a lot of the answers are for things I have already done. Things I have tried:

*

*Renaming the protocol.

*Renaming the delegate.

*Making the protocol not of type class.

*Force unwrapping the delegate (this one is interesting - it caused my app to crash even though I know the delegate exists).

I have created the protocol in ViewControllerB:
protocol ViewControllerBDelegate: class {
    func viewControllerB(_ controller: UIViewController, didSelectArray array: [String])
}

I create a variable for the delegate with a weak reference cycle:
weak var viewControllerBDelegate: ViewControllerBDelegate?

I have also called a function from my delegate in didSelectRowAt:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let strArray = ["Hello", "World"]
    viewControllerBDelegate?.viewControllerB(self, didSelectArray: strArray)
}

Then on ViewControllerA:
class ViewControllerA: UIViewController, ViewControllerBDelegate

In the ViewControllerB delegate function:
func viewControllerB(_ controller: UIViewController, didSelectArray array: [String]) {
    print("An array of strings: \(array)")

    controller.dismiss(animated: true, completion: nil)
}

In the prepare for segue function:
if let viewControllerB = segue.destination as? ViewControllerB {
    viewControllerB.viewControllerBDelegate = self
}

I expected the delegate to print the contents of the array that was passed over by ViewControllerB. It did not work though, and unlike what my code was aiming for, the view controller did not dismiss like it was supposed to.

A: You create a weak reference to delegate. If nothing else doesn't reference on the delegate (include UIKit staff), it will be removed by ARC. If it's true, you should remove weak modifier.
You can read about ARC here https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html
The follow situation can be appeared in the your app:

*

*App presents viewControllerA

*App makes the transition to viewControllerB

*App makes viewControllerA as the delegate viewControllerB

*App dismises viewControllerA

now, the delegate of viewControllerB equals nil

A: You said:

Force unwrapping the delegate ... caused my app to crash

That narrows it down to the fact that viewControllerBDelegate is obviously nil. So the question is why. So, add a breakpoint in your prepare(for:sender:) and make sure you're hitting that line. If not, perhaps you presented the second view controller rather than performing a segue to it? Perhaps the second view controller was embedded in a navigation controller? It's impossible to tell on the basis of the information initially provided, but it's likely to be something like that.
In the comments, you have confirmed that the second view controller was embedded within a navigation controller. I know you've figured this out, but for the sake of future readers, in that case the prepare(for:sender:) might look like:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController,
        let controller = nav.topViewController as? ViewControllerB {
            controller.delegate = self
    }
}

Forgive my changing the name of the delegate property to simply delegate. As a matter of convention, I alway use delegate except in those rare cases where I need to disambiguate between two different delegate protocols. But hopefully this illustrates the idea.


text:
Q: Rails 4 simple_form params not being saved to database As a novice to RoR I am making a site that allows clients to fill out a large form online. The form includes some nested models, but my issue is with the client not being saved to the database on the form submit.
From looking at my server it seems that params is picking up on the client information, but when sql action starts it doesn't insert any of the information into the database. Although it says it commits the transaction, my client in rails console have all nil attributes.
    Started POST "/clients" for 192.168.1.114 at 2014-08-16 23:40:14 -0700
Processing by ClientsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"2tPnVc7Aj5mMdd9ZnXVuFHHs3CprND6QZ8qyCxSC674=", "client"=>{"name"=>"Jon", "birthdate"=>"August 2 1990", "has_guardian"=>"0", "guardian"=>{"name"=>"", "phone_number"=>"", "relationship"=>"", "address"=>"", "birthdate"=>""}, "gender"=>"male", "relationship"=>"single", "address"=>"25 Oak Road, LA, CA, 90003", "home_phone"=>"3105636778", "home_phone_manner"=>"leave_message_with_info", "preferred_home_phone"=>"false", "confidential_home_phone"=>"false", "cell_work_phone"=>"3104556721", "cell_work_phone_manner"=>"leave_message_with_info", "preferred_cell_work_phone"=>"true", "confidential_cell_work_phone"=>"true", "email"=>"jon@gmail.com", "confidential_email"=>"true", "written_communication"=>"use_email", "family_contact"=>{"name"=>"Lily Mod", "phone_number"=>"3109776663"}, "additional_info"=>"Test", "created_at(1i)"=>"2014", "created_at(2i)"=>"8", "created_at(3i)"=>"17", "employer"=>"Polly", "occupation"=>"Sales", "prescriptions"=>"None", "medicines"=>"None", "allergies"=>"None", "conditions"=>"None"}, "commit"=>"Create Client"}
    Unpermitted parameters: has_guardian, guardian, family_contact, created_at(1i),       created_at(2i), created_at(3i)
  (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "clients" ("additional_info", "created_at", "updated_at")          VALUES   (?, ?, ?)  [["additional_info", "Test"], ["created_at", Sun, 17 Aug 2014 06:40:14 UTC  +00:00], ["updated_at", Sun, 17 Aug 2014 06:40:14 UTC +00:00]]
  (0.6ms)  commit transaction
 Redirected to http://192.168.1.114:3000/
 Completed 302 Found in 59ms (ActiveRecord: 1.5ms)

When I pry inside my clients#create it shows at @client with all nil attributes, but when I call a method like name on @client it returns the value that is in the params.
26:   def create
27:     @client = Client.new(client_params)
=> 28: binding.pry
29:     respond_to do |format|
30:       if @client.save
31:         format.html { redirect_to root_path, notice: 'Client was successfully created.' }
32:         format.json { render controller: :static_pages, action: 'home', status: :created, location: root_path }
33:       else
34:         format.html { render action: 'new' }
35:         format.json { render json: @client.errors, status: :unprocessable_entity }
36:       end
37:     end
38:   end

[1] pry(#<ClientsController>)> @client
=> #<Client id: nil, name: nil, email: nil, home_phone: nil, home_phone_manner: nil, cell_work_phone: nil, cell_work_phone_manner: nil, written_communication: nil, confidential_email: nil, additional_info: "test", birthdate: nil, gender: nil, relationship: nil, employer: nil, occupation: nil, medicines: nil, allergies: nil, conditions: nil, created_at: nil, updated_at: nil, preferred_home_phone: nil, confidential_home_phone: nil, preferred_cell_work_phone: nil, confidential_cell_work_phone: nil, prescriptions: nil, address: nil>
[2] pry(#<ClientsController>)> @client.name
=> "Jon"

My relevant Clients Controller:
 def new
   @client = Client.new
 end

 def create
   @client = Client.new(client_params)

   respond_to do |format|
     if @client.save
       format.html { redirect_to root_path, notice: 'Client was successfully created.' }
       format.json { render controller: :static_pages, action: 'home', status: :created,     location: root_path }
     else
       format.html { render action: 'new' }
       format.json { render json: @client.errors, status: :unprocessable_entity }
     end
   end
 end
 def client_params
   params.require(:client).permit(:name, :email, :address, :home_phone, :home_phone_manner,
                                 :cell_work_phone, :cell_work_phone_manner,
                                 :written_communication, :confidential_email,
                                 :additional_info, :birthdate, :gender, :relationship,
                                 :prescriptions, :employer, :occupation, :medicines,
                                 :allergies, :conditions, :preferred_home_phone,
                                 :confidential_home_phone, :preferred_cell_work_phone,
                                 :confidential_cell_work_phone)
 end

My routes file:
  match '/contact', to: 'static_pages#contact', via: :get
  match '/about', to: 'static_pages#about', via: :get
  match '/contact', to: 'static_pages#about', via: :get

  match '/forms', to: 'clients#new', via: [:get, :post]

  resources :clients
  resources :family_contacts
  resources :guardians

My Client model, I realize I haven't completed everything to get the associations working but I am concerned with just saving a client for now:
  class Client < ActiveRecord::Base

    has_one :guardian

    has_many :family_contacts

    accepts_nested_attributes_for :family_contacts
    accepts_nested_attributes_for :guardian

    attr_accessor :name, :email, :birthdate, :gender, :address
    attr_accessor :home_phone, :home_phone_manner, :confidential_home_phone, :preferred_home_phone
    attr_accessor :cell_work_phone, :cell_work_phone_manner, :confidential_cell_work_phone, :preferred_cell_work_phone
    attr_accessor :written_communication, :confidential_email
    attr_accessor :relationship, :employer, :occupation
    attr_accessor :prescriptions, :medicines, :allergies, :conditions

    def has_guardian?
      self.guardian.present?
    end

 end

My form is very long, but Iv'e tried to simplify it by taking out a lot of the styling and labels:
    <%= simple_form_for(@client, defaults: { required: false }, html: { class: 'form-inline' }) do |f| %>

    <%= f.input :name, label: "Patient's Name:", placeholder: "First & Last" %>

    <%= f.input :birthdate, label: "Birthdate:", placeholder: "January 1 2000" %>

    <%= f.input :has_guardian?, label: "Are you under the age of 18?", as: :boolean %>

      <%= f.simple_fields_for Guardian.new do |g| %>
        <%= g.input :name, label: "Name of Gaurdian", placeholder: "First & Last" %>
        <%= g.input :phone_number, label: "Phone # of Guardian", as: :tel %>
        <%= g.input :relationship, label: "Relationship to Patient" %>
        <%= g.input :address, label: "Guardian's Address" %>
      <% end %>

    <%= f.collection_radio_buttons :gender, [['male', 'Male'], ['female', 'Female']], :first, :last %>

    <%= f.collection_radio_buttons :relationship, [['single', 'Single'], ['married', 'Married'], ['widowed', 'Widowed'], ['seperated', 'Seperated'], ['domestic_relationship', 'Domestic Relationship']], :first, :last %>

    <%= f.input :address, lable: "Home Address:", placeholder: '25 Oak Road, Los Angeles, CA, 90003' %>

    <%= f.input :home_phone, label: "Home Phone #", as: :tel %>

    <%= f.collection_radio_buttons :home_phone_manner, [['leave_message_with_info', 'Leave message with detailed information.'], ['leave_message_with_callback', 'Leave message with call-back number only.']], :first, :last %>

    <%= f.collection_radio_buttons :preferred_home_phone, [[true, 'Yes'], [false, 'No']], :first, :last %>

    <%= f.collection_radio_buttons :confidential_home_phone, [[true, 'Yes'], [false, 'No']], :first, :last %>

    <%= f.input :cell_work_phone, label: "Cell/Work Phone #", as: :tel %>

    <%= f.collection_radio_buttons :cell_work_phone_manner, [['leave_message_with_info', 'Leave message with detailed information.'], ['leave_message_with_callback', 'Leave message with call-back number only.']], :first, :last %>

    <%= f.collection_radio_buttons :preferred_cell_work_phone, [[true, 'Yes'], [false, 'No']], :first, :last %>

    <%= f.collection_radio_buttons :confidential_cell_work_phone, [[true, 'Yes'], [false, 'No']], :first, :last %>

    <%= f.input :email, label: "Email:", as: :email %>

    <%= f.collection_radio_buttons :confidential_email, [[true, 'Yes'], [false, 'No']], :first, :last %>

    <%= f.collection_radio_buttons :written_communication, [['mail_home', 'Mail to my home address (above).'], ['mail_work', 'Mail to my work address.'], ['fax_to_home', 'Fax to me home phone (above).'], ['use_email', 'Email me to the above email address.']], :first, :last %>

  <%= f.simple_fields_for FamilyContact.new do |c| %>

      <%= c.input :name, label: "Name:", placeholder: "First & Last" %>

      <%= c.input :phone_number, label: "Phone #", as: :tel %>

      <%= c.input :name, label: "Name:", placeholder: "First & Last" %>

      <%= c.input :phone_number, label: "Phone #", as: :tel %>

  <% end %>

  <%= f.input :additional_info, label: "Additional Information:", as: :text %>

    <%= f.input :created_at, label: "Date", as: :date %>

    <%= f.input :employer, label: "Employer:" %>

    <%= f.input :occupation, label: "Occupation:" %>

    <%= f.input :prescriptions, label: "Current Prescription Medications:" %>

    <%= f.input :medicines, label: "Over the Counter Medications:" %>

    <%= f.input :allergies, label: "Allergies to Medications" %>

    <%= f.input :conditions, label: "Other Medical Conidtions" %>

    <%= f.input :created_at, label: "Date", as: :date %>

  <%= f.simple_fields_for Guardian.new do |g| %>
    <%= g.input :name, label: "Name of Gaurdian", placeholder: "First & Last" %>
    <%= g.input :birthdate, label: "Birthdate of Guardian", placeholder: "January 1 2000" %>
  <% end %>

  <%= f.input :name, label: "Patient's Name:", placeholder: "First & Last" %>
  <%= f.input :birthdate, label: "Birthdate:", placeholder: "January 1 2000" %>

  <%= f.submit %>

Sorry for the length of the files, but I really appreciate any help. Thanks

A: Here's the error:

Unpermitted parameters: has_guardian, guardian, family_contact,
  created_at(1i),       created_at(2i), created_at(3i)

Although the error above is for strong_params, I think it's a deeper issue which we need to resolve. As you're new, let me detail how this works for you...

Attributes
The model you have are heavily populated with attr_accessor. attr_accessor is a way to create "virtual attributes" in Ruby / Rails, as it defines a custom getter and setter method, which will essentially define the "attributes" for use on the system
The problem you  have is attr_accessor, in the simplest of terms, will not permit your data to be saved in the database. This will be one of the bigger issues you have - you need to get rid of any attr_accessors which override your database attributes
This is demonstrated here:

INSERT INTO "clients" ("additional_info", "created_at", "updated_at")
  VALUES   (?, ?, ?)  [["additional_info", "Test"], ["created_at", Sun,
  17 Aug 2014 06:40:14 UTC  +00:00], ["updated_at", Sun, 17 Aug 2014
  06:40:14 UTC +00:00]]

This basically shows that only additional_info, created_at and updated_at are populating the database.
You should remove the attr_accessor methods from your Client model:
#app/models/client.rb
class Client < ActiveRecord::Base

    has_one :guardian

    has_many :family_contacts

    accepts_nested_attributes_for :family_contacts
    accepts_nested_attributes_for :guardian

end

Unpermitted
The unpermitted parameters issue is caused mainly by your non-permission of these in your strong params hash. You'll need to add them here:
#app/controllers/clients_controller.rb
Class ClientsController < ApplicationController
   private

   def client_params
      params.require(:client).permit(..., :has_guardian, :guardian, :family_contact, :created_at(1i), :created_at(2i), :created_at(3i))
   end
end

Although this is definitely the case, I feel there is a massive problem with the number of attributes you're trying to pass through. It's not against convention or anything, but validating all of those attributes each submit is surely going to cause a problem?
I'd say its unworkable - you'd be better splitting it up into manageable associated models / objects, though I'll leave that up to you to work out


text:
Q: Creating sub-rows in a row with html I would like to create a simple html table with sub-rows within a single row. It looks something like this;

The tricky part is to divide the 3rd column into 2 rows row 1 and Row 2. How would the html code look like to implement such a table?

A: Using rowspan

1	Main	Row 1

Row 2

A: Try this:

   col1
   col2
   col3
   col4
   col5

   data1
   data2
   data3

   data1
   data2
   data3

A: You can use two div's to simulate the two rows in the last column:

table {
  border-collapse: collapse;
  width: 50%;
  height: 50%;
}

th, td {
    border: 1px solid black;
}

td .test {
 border-bottom: 1px solid black;
}

        a

        b

Test

Test

A: Even nested tables might help:

        Hi

                    How

                    When

Nested Tables Fiddle


text:
Q: Is there a better method of creating a list of quarters by counting back from a given quarter? I have done this function which creates an array of quarters, counting back x quarters including from specified quarter.
The last item in the array is the reference quarter.
For example, with reference quarter 2 and a count of 9, this would yield [2, 3, 4, 1, 2, 3, 4, 1, 2];
My function works, but I would like to know, if there is a simpler, more elegant solution to this.
Code below:

/// Counts back x from specified quarter
/// Parameters:
/// @param countFrom   -- the reference quarter to count back from
/// @param count       -- count
///
/// @returns array     -- the array of quarters
function getQuarterList(countFrom, count) {
 var ret = [];
 for (var i = 0; i < count; i++){
  var z = countFrom - i;
  while (z < 1) {
   z = z + 4;
  }
  ret.splice(0, 0, z);
 }

 return ret;
}

var quarterList = getQuarterList(2, 9);
console.log(quarterList);

A: You can leverage on the map function and on the arithmetical module operator. Here follow a generalized version of your function:
function getModuleList(countFrom, count, mod) {
  var arr = [];
  for (var i = 0; i < count; i++){
    arr.push(i + countFrom);
  }

  return arr.map(function(num){ return num % mod || mod });

}

var quarterList = getModuleList(2, 9, 4);
console.log(quarterList);

A: That while loop can be omitted if you just use countFrom as the counter:
function getQuarterList(countFrom, count) {
    // assert: countFrom ∈ [1..4]
    var ret = [];
    for (var i = 0; i < count; i++) {
        ret.unshift(countFrom)
        countFrom--;
        if (countFrom < 1)
            countFrom += 4;
    }
    return ret;
}

An easier approach would be to compute which value to start at and use the module operator:
function getQuarterList(countFrom, count) {
    var ret = [];
    var z = (countFrom - count % 4 + 4) % 4;
    for (var i = 0; i < count; i++) {
        ret.push(++z)
        z %= 4;
    }
    return ret;
}

A: I would do this job as follows;

var quarters = (n,m) => Array(...Array(m - m%4 + n%4)).map((e,i) => i%4 + 1)
                                                      .slice(this.length-m);
console.log(quarters(2,9));

Well thinking further i believe i can not get any more functional than this.

var quarters = (n,m) => Array(...Array(m)).map((e,i) => (Math.abs(m%4-n) + i)%4 + 1);
console.log(quarters(1,11));
console.log(quarters(3,7));
console.log(quarters(2,9));

A: You could calculate the start value

function getQuarterList(countFrom, count) {
    var offset = (countFrom - count) % 4 + 4;
    return Array.apply(null, { length: count }).map(function (_, i) {
        return (i + offset) % 4 + 1;
    });
}

console.log(getQuarterList(2, 9));
console.log(getQuarterList(3, 7));
console.log(getQuarterList(1, 2));
console.log(getQuarterList(4, 9));


text:
Q: rsync completed in both directions, but size of directories is different. How it's possible? I want to sync 2 directories (/src & /dst) to mirror all the files in both of them.
Here is a steps:

*

*sudo rsync -vaP --stats /src  /dst -> completed without errors

*sudo rsync -vaP --stats /dst /src -> completed without errors

*diff -rq /src /dst-> doesn't show any diffs.

*du -s /src && du -s /dst shows different sizes (10% diff).

How it's possible? I'm completely stuck with this dilemma.

A: *

*Sparse files may be expanded on copy when the -S flag is not used.  (Will make the destination take more space)

*Hard links within the tree may be expanded to separate files on copy when the -H flag is not used.  (Will make the destination take more space)

*Filesystems may have different allocation sizes.  A one-byte file may take up 512 bytes of disk allocation on one filesystem and may take up 4096 bytes (or even more) on another.  If your tree has a lot of small files, this will make a large difference.  (Destination may take more or less space depending on the particulars)

*Directories may be much larger than necessary to hold the current contents on some filesystems.  When the contents are copied, the directory will be smaller on the destination.  Not normally a big deal, but some pathological directories can be enormous.  (Will make the destination take less space)

It's also possible for filesystems to have different compression/deduplication/redundancy settings leading to different storage requirements for the data.  But that's less common, and even when present the differences aren't always visible via du.


text:
Q: How do I sort my R data by a specific named condition inside a column? I have two columns in my dataset in R studio right now: one is "experience level", which contains four different two letter abbreviations ("SE", "MI", "EX", "EN") related to the experience level of an employee. The second column is "salary", which is the employee's salary in USD. How can I create a data frame or sort the data by a specific experience level, such as showing only salaries that are a part of "EN" employees?
I am not sure where to start even. Have tried using group_by but to no avail.

A: Showing "only" salaries that are part of a group, can be done with filter()
Sorting can be done with the arrange() function
library(tidyverse)
df %>%
   filter(experience=="EN") %>% # filters to only EN
   arrange(desc(salary)) #sort/arrange the salary data, descending (high to low)


text:
Q: Qt5 and CMake: cannot find Quick, QuickControls modules I have the following set-up:
$ qmake --version
QMake version 3.1
Using Qt version 5.9.5

I am using CMake with the following relevant instructions (to give you a context):
set(CMAKE_PREFIX_PATH /usr/lib/qt5/bin/)

if(CMAKE_VERSION VERSION_LESS "3.7.0")
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()

set(CMAKE_MODULE_PATH /usr/lib/qt5)
# @see: https://stackoverflow.com/questions/51994603/cmake-qt5-undefined-reference-to-qprinterqprinterqprinterprintermode
SET(QT5_MODULES Core Widgets PrintSupport)
find_package(Qt5 COMPONENTS ${QT5_MODULES} REQUIRED)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(HW_GUI_DIR ${CMAKE_CURRENT_SOURCE_DIR}/gui)
# include_directories(${HW_HEADER_DIR})
set(CMAKE_AUTOUIC ON)
...

The core part is
SET(QT5_MODULES Core Widgets PrintSupport)
find_package(Qt5 COMPONENTS ${QT5_MODULES} REQUIRED)

Now, when I add Quick or QuickControls2 into the QT5_MODULES, CMake cannot find those,
and I see this error on the cmake-config step:

CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt5/Qt5Config.cmake:28
  (find_package):   Could not find a package configuration file provided
  by "Qt5Quick" with any   of the following names:
Qt5QuickConfig.cmake
qt5quick-config.cmake

Now, not to confuse you, /usr/lib/x86_64-linux-gnu/qt5/bin seems to be a symlink
to /usr/lib/qt5, which I've checked like this:
$ ls -l /usr/lib/x86_64-linux-gnu/qt5/bin/
total 0
lrwxrwxrwx 1 root root 33 Oct 30 18:00 fixqt4headers.pl -> ../../../qt5/bin/fixqt4headers.pl
lrwxrwxrwx 1 root root 20 Oct 30 18:00 moc -> ../../../qt5/bin/moc
lrwxrwxrwx 1 root root 29 Oct 30 18:00 qdbuscpp2xml -> ../../../qt5/bin/qdbuscpp2xml
lrwxrwxrwx 1 root root 29 Oct 30 18:00 qdbusxml2cpp -> ../../../qt5/bin/qdbusxml2cpp

How to fix this error and find the Quick module? What is special about it -- I am able to load the other modules allright.

A: First, please check if you have installed the correct packages providing those modules. Since you seem to be using some Debian derivative, these are the package names that you should install: qtdeclarative5-dev and qtquickcontrols2-5-dev. See:
https://packages.debian.org/sid/amd64/qtdeclarative5-dev/filelist
https://packages.debian.org/sid/amd64/qtquickcontrols2-5-dev/filelist


text:
Q: MSSQL Join Calculation i am searching for a solution in regards to joining and MSSQL.
I have two tables.
The first one the Basic Table:
ID, Name, Key
1, Test1, 1x11
2, Test2, 2x22
3, Test3, 3x33

The second is the table which I want to join to the Basic table:
Key, Action, create,         close,           duration
1x11,   1,  01/01/2021 06:00,01/01/2021 07:00,  1
1x11,   5,  01/01/2021 07:00,01/01/2021 10:00,  1
1x11,  10,  01/01/2021 10:00,0,                 0
2x22,   1,  01/01/2021 10:00,01/01/2021 11:00,  1
2x22,   5,  01/01/2021 11:00,01/01/2021 12:00,  1
2x22,   7,  01/01/2021 12:00,01/01/2021 13:00,  1
2x22,   5,  01/01/2021 13:00,01/01/2021 14:00,  1
2x22,  10,  01/01/2021 14:00,0,                 0
3x33,   1,  01/01/2021 10:00,01/01/2021 12:00,  2
3x33,  10,  01/01/2021 12:00,0,                 0

In this table the closedate was not given, so i had to use the following command to get the closedate (closedate is the next createdate):
 lead (create,1) OVER (PARTITION BY Key ORDER BY create) AS close

Now, my goal is to join the sum(of ActionNumber 5 per Key) to the  basic table
Can someone tell me how to do that? I am really frustrated.
Final Table:
ID, Name, Key, join(sum of 5)
1, Test1, 1x11,1
2, Test2, 2x22,2 (because there are two times one hour that means 2h)
3, Test3, 3x33,0

Thanks for helping. Christian

A: This is simple, all you need is to do conditional aggregation:
SELECT [key], SUM(CASE WHEN Action = 5 THEN duration ELSE 0 END)
FROM t
GROUP BY [key]

where t is the second table.
Output:
key sum_of_5
-------------
1x11    1
2x22    2
3x33    0

To join back to the original table use a derived table:
SELECT [key], name, sum_of_5
FROM t1
JOIN (
    SELECT
       [key]
       , SUM(CASE WHEN Action = 5 THEN duration ELSE 0 END)
    FROM t
    GROUP BY [key]
) t2 ON t1.[key] = t2.[key]

Demo here

A: If the two tables exist then this should be a simple aggregation.
SELECT
    B.ID,
    B.Name,
    B.Key,
    CountAction5 = SUM(CASE WHEN S.Action = 5 THEN Duration ELSE 0 END)
FROM
    BasicTable B
    INNER JOIN SecondTable S ON S.Key = B.Key
GROUP BY
    B.ID,
    B.Name,
    B.Key


text:
Q: $u\in C_0^3(\Omega)$ satisfis $ -\Delta u=f(x), x\in\Omega. $Prove that $ \sum_{i,j=1}^{n}\int_\Omega u^2_{x_i x_j} dx\leq n\int_{\Omega}f^2 dx. $
Suppose $u\in C_0^3(\Omega)$ satisfis
$$
-\Delta u=f(x), x\in\Omega.
$$
Prove that
$$
\sum_{i,j=1}^{n}\int_\Omega u^2_{x_i x_j} \mathrm{d}x\leq n\int_{\Omega}f^2\mathrm{d}x.
$$

I have tried as follows: Let $v=\Delta u$ in the Green's formula $\int_\Omega \nabla u\cdot\nabla v \mathrm{d}x=-\int_\Omega v\Delta u \mathrm{d}x+\int_{\partial\Omega}\frac{\partial u}{\partial n}v\mathrm{d}S$, then we get
$$
\int_\Omega \nabla u\cdot\nabla(\Delta u)dx=-\int_\Omega f^2+\int_{\partial\Omega}\frac{\partial u}{\partial n}(-f)\mathrm{d}S.
$$
By the Integration by parts formula or Green's formula, I find the left side can be written as
$$
LHS=\sum_{i,j=1}^n\left[-\int_\Omega(u_{x_ix_j})^2\mathrm{d}x+\int_{\partial\Omega}u_{x_ix_j}\cdot u_{x_i}\cdot n^j\mathrm{d}S\right]\\=-\sum_{i,j=1}^n\int_\Omega(u_{x_ix_j})^2\mathrm{d}x+\int_{\partial\Omega}\mathrm{div}u\cdot\dfrac{\partial \mathrm{div}u}{\partial n}\mathrm{d}S.
$$
I do not know how to proceed. Where to find the coeffcient $n$? Also, how to estimate the term $\int_{\partial\Omega}\frac{\partial u}{\partial n}(-f)\mathrm{d}S$?
Did I get wrong somewhere? Appreciate any help!

A: In fact a stronger statement holds and it follows directly from integration by parts. Indeed, integrating by parts twice we obtain \begin{align*}\sum_{i,j=1}^n \int_\Omega u^2_{x_ix_j} \, dx &= -\sum_{i,j=1}^n \int_\Omega u_{x_ix_ix_j}u_{x_j} \, dx \\
&=\sum_{i,j=1}^n \int_\Omega u_{x_ix_i}u_{x_jx_j} \, dx \\
&= \int_\Omega (\Delta u )^2 \, dx \\
&=\int_\Omega f^2 \, dx.
\end{align*} There are no boundary terms since $u$ has compact support in $\Omega$.


text:
Q: Celery daemon spawning multiple processes for single worker with systemd I'm trying to use django with celery & celerybeat to run periodic tasks. I have my celery process setup with systemd as
[Unit]
Description=my celery daemon
After=network.target

[Service]
PIDFile=/var/run/celery/celery.pid
Type=forking
User=myuser
Group=www-data
RuntimeDirectory=celery
RuntimeDirectoryMode=0770
WorkingDirectory=/opt/myapp/
ExecStart=/opt/myapp/.virtualenv/bin/celery multi start worker1 \
    --app=myapp \
    --concurrency=1 \
    --schedule=/var/run/celery/celerybeat-schedule \
    --pidfile=/var/run/celery/celery.pid \
    --logfile=/opt/myapp/log/celery.log \
    --loglevel=INFO \
    --beat
ExecStop=/opt/myapp/.virtualenv/bin/celery multi stopwait worker1 \
    --pidfile=/var/run/celery/celery.pid \
    --logfile=/opt/myapp/log/celery.log \
ExecReload=/opt/myapp/.virtualenv/bin/celery multi restart worker1 \
    --pidfile=/var/run/celery/celery.pid \
    --logfile=/opt/myapp/log/celery.log \

[Install]
WantedBy=multi-user.target

This all works fine.. but I notice it spawns 3/4 processes despite there being only 1 worker, and concurrency being set to 1. Why is this? My goal is to have 1 worker running that will queue tasks up, rather than perform them synchronously for now.
$ ps aux | grep celery:
myuser    1748  0.6 11.8 189816 59400 ?        S    11:59   0:01 /opt/myapp/.virtualenv/bin/python -m celery worker --beat --concurrency=1 --app=myapp --schedule=/var/run/celery/celerybeat-schedule --loglevel=INFO --logfile=/opt/myapp/log/celery.log --pidfile=/var/run/celery/celery.pid --hostname=worker1@staging
myuser    1753  1.2 11.9 272324 59528 ?        Sl   11:59   0:02 /opt/myapp/.virtualenv/bin/python -m celery worker --beat --concurrency=1 --app=myapp --schedule=/var/run/celery/celerybeat-schedule --loglevel=INFO --logfile=/opt/myapp/log/celery.log --pidfile=/var/run/celery/celery.pid --hostname=worker1@staging
myuser    1754  0.0 11.4 197540 57244 ?        S    11:59   0:00 /opt/myapp/.virtualenv/bin/python -m celery worker --beat --concurrency=1 --app=myapp --schedule=/var/run/celery/celerybeat-schedule --loglevel=INFO --logfile=/opt/myapp/log/celery.log --pidfile=/var/run/celery/celery.pid --hostname=worker1@staging


text:
Q: What is the Laplace transform of $e^{3t} \cdot \sin^2 t$ I am trying to compute the Laplace transform of the following functions $e^{3t} \cdot \sin^2 t$
Please help me to find a  solution

A: Converted my comments into an answer:
The procedure I would use is to find the first find the Laplace Transform of $\sin^2(t)$ using the identity $\sin^2(t)\equiv\dfrac{1-\cos(2t)}{2}$ and then apply the first shifting theorem, which states that:
$$\mathcal{L}\{e^{at}f(t)\}=F(s-a) \tag{1}$$
Where $F(s)=\mathcal{L}\{f(t)\}$. It is easy to prove the above using the definition of the Laplace Transform, which I leave as an exercise.

Letting $f(t)=\sin^2(t)$, we obtain for $F(s)$:
$$F(s)=\mathcal{L}\{\sin^2(t)\}=\frac{1}{2}\mathcal{L}\{1\}-\frac{1}{2}\mathcal{L}\{\cos(2t)\}=\frac{1}{2s}-\frac{s}{2(s^2+4)}=\frac{2}{s(s^2+4)}$$
Thus, it follows from the first shifting theorem that:
$$\mathcal{L}\{e^{3t}f(t)\}=F(s-3)=\frac{2}{(s-3)((s-3)^2+4)}=\frac{2}{(s-3)(s^2-6s+13)}$$


text:
Q: Copy Constructor and Operator Overloading : C++ Consider Below example:
#include <iostream>

using namespace std;

class Test{

public:
    int a;
    Test(int a=0):a(a){ cout << "Ctor " << a << endl;}
    Test(const Test& A):a(A.a){ cout << "Cpy Ctor " << a << endl;}
    Test operator+ ( Test A){
    Test temp;
    temp.a=this->a + A.a;
    return temp;
    }
};

int main()
{
Test b(10);
Test a = b ;
cout << a.a << endl;
return 0;
}

The Output is:
$ ./Test
Ctor 10
Cpy Ctor 10
10

It calls Copy constructor. Now, suppose If we modify the code as:
int main()
{
Test b(10);
Test a = b + Test(5);
cout << a.a << endl;
return 0;
}

The Output becomes:
$ ./Test
Ctor 10
Ctor 5
Ctor 0
15

The expression Test a = b + Test(5); does not call copy constructor. What I thought that that b+ Test(5) should be used to instantiate a new object a of type Test , so this should call copy constructor. Can someone explain the output?
Thanks

A: See copy elision: http://en.wikipedia.org/wiki/Copy_elision
Basically, no temp is constructed and result is put directly into Test a object.


text:
Q: Copy text and paste in UFT I would like to copy a text from a webpage and paste it in another field on the same web page.
Here is what I've tried so far without success
This is my code:
Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$Tabs").GetROProperty + micCtrlDwn + "a" + micCtrlUp
Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$Tabs").GetROProperty + micCtrlDwn + "c" + micCtrlUp
Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$TabsCPe_3").Click
Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$TabsCPe_3").GetROProperty + micCtrlDwn + "v" + micCtrlUp

It clicks on the field i need it to copy the text from but does not select all the text and copy it to the defined destination.
Object properties for feild1 after entering text manually
feild1 object spy

A: Why don't you just fetch the value from field1, store it in a variable and set that value to field2 as shown below:
Dim strValue
'fetch the value from field1 and store it in a variable
strValue = Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$Tabs").getRoProperty("value")

'set that value to field2
Browser("Candidate").Page("Candidate").WebEdit("ctl00$Main$TabsCPe_3").set strValue


text:
Q: Active Directory modifications using SQL Server I've exported my AD into CSV and pumped it into SQL, the goal is to modify some fields and import it back into AD.
I've done every field I need to do except one, the proxyAddress field.
My data looks like this:
proxyAddresses
sip:john.smiths@email.com;SMTP:john.smith@email.com
sip:james.jones@email.com;SMTP:james.jones@email.com;notes:james.jones/EMAIL/

etc...
I'm trying to change the sip: values, but as they're all different username, and have SMTP included, I'm struggling with the SQL LIKE command.
I need to data to look like this:
proxyAddresses
sip:john.smiths@newemail.com;SMTP:john.smith@email.com
sip:james.jones@newemail.com;SMTP:james.jones@email.com;notes:james.jones/EMAIL/

Changing the sip: value, but leaving the rest as they are.
Any help would be appreciated.

A: We don't know the tables definition nor the mapping between new and old values, so just for the start something like this:
declare @e varchar(1000) = 'sip:james.jones@email.com;SMTP:james.jones@email.com;notes:james.jones/EMAIL/'
declare @newEmail varchar(126) = 'james.jones@newemail.com'

select stuff(@e, charindex(':', @e)+1, charindex(';', @e)-charindex(':', @e)-1, @newEmail)


text:
Q: Difference between "happy birthday" vs "happiest birthday" I have heard people saying "happy birthday" but "happiest birthday" sounds a little weird to me as it is the superlative form. Which would mean that only the recent birthday to be the happiest only, no? I'm confused :/ could someone please explain the logic behind this?

A: There is nothing wrong or weird about Happiest birthday. For example:

It was my happiest birthday as I received more presents than I
  expected.
  Yesterday was the happiest birthday of my life.
  I hope you
  will have the happiest birthday with your fiance in London.

As you mentioned, happiest is the superlative form of the adjective happy. It doesn't mean it is the most recent birthday. If your happiest birthday was 10 years ago, you could say, "10 years ago today was the happiest birthday of my life."
However, you don't usually say "Happiest birthday to you." when you wish someone a happy birthday.

A: You would occasionally find "happiest birthday" as in this book title, which starts with "Happiest birthday to my best friend". What that means is simply "may this be my best friend's happiest birthday yet".
A notebook planner's title starts with "Happiest birthday to the BEST teacher ever." Again, this means "may this be the happiest birthday the best teacher ever has had".
As others have commented, "happy birthday" is way more common, both in everyday speech and writing. You'd sometimes see "happiest of birthdays to you" on greeting cards. In summary, stick to "happy birthday", but be aware that on rare occasions  - and, it seems, primarily in writing - people might use "happiest" to with someone a very happy birthday.


text:
Q: java: Class.isInstance vs Class.isAssignableFrom Let clazz be some Class and obj be some Object.
Is
clazz.isAssignableFrom(obj.getClass())

always the same as
clazz.isInstance(obj)

?
If not, what are the differences?

A: I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance but just the Class object to use isAssignableFrom.

A: For brevity, we can understand these two APIs like below:

*

*X.class.isAssignableFrom(Y.class)
If X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

*X.class.isInstance(y)
Say y is an instance of class Y, if X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

A: clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.
clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.
That is:
clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)

is always true so long as clazz and obj are nonnull.

A: Both answers are in the ballpark but neither is a complete answer.
MyClass.class.isInstance(obj) is for checking an instance.  It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException.  In other words, obj is an instance of MyClass or its subclasses.
MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other.  Other can be a class or an interface.  It answers true if Other can be converted to a MyClass.
A little code to demonstrate:
public class NewMain
{
    public static void main(String[] args)
    {
        NewMain nm = new NewMain();
        nm.doit();
    }

    class A { }

    class B extends A { }

    public void doit()
    {
        A myA = new A();
        B myB = new B();
        A[] aArr = new A[0];
        B[] bArr = new B[0];

        System.out.println("b instanceof a: " + (myB instanceof A)); // true
        System.out.println("b isInstance a: " + A.class.isInstance(myB)); //true
        System.out.println("a isInstance b: " + B.class.isInstance(myA)); //false
        System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class)); //true
        System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class)); //false
        System.out.println("bArr isInstance A: " + A.class.isInstance(bArr)); //false
        System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr)); //true
        System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass())); //true
    }
}


text:
Q: phpmyadmin database getting deleted automatically I am using aws ec2 t2 instance. Where I created few database as per my requirement.
For last few day I noticed new databases which I create getting deleted automatically. Is there any possibility of automatically getting deleted?
Current I have not put any password on phpmyadmin. Also no one other then me knowing IP of this server.
Any clue why it is getting deleted and tips to secure it?

A: *

*Thoroughly read Making MySQL Secure Against Attackers and implement the recommendations.

*Restrict access to the EC2 through Security Group

*

*Only permit access to the database (port 3306) from the IP addresses where your web application lives (if it's on the same server don't open access to port 3306 at all).

*Only permit access to phpMyAdmin and SSH from your IP (e.g. your home connection).

*Set password for phpMyAdmin

*Use HTTPS to access phpMyAdmin, e.g. use free LetsEncrypt certificate.

*Consider using Adminer which is similar to phpMyAdmin and enforces some basic security.

*Read or get some training about security essentials - both general and cloud-related.

Hope that helps :)


text:
Q: Encapsulating the Order of a Collection in OOP Let's say you have a collection of objects that are part of a class:
[A, B, C, D]
But the order they are in means something. There are a finite number of orderings that you want to be able to delegate at runtime. For example [C, A, B, D], [B, D, A, C], etc. How would you go about encapsulating the notion of order in such a way that allows you to change the ordering at runtime, and add new orderings later on without changing existing code?
The language doesn't matter, but an explanation in Java or C++ is preferred.


text:
Q: What numerical methods can be used to verify the accuracy of Feynman diagram results? Recently, I have been attempting to replicate the Feynman diagram calculation which was featured in an article  here.
\begin{align}
 &C_{x y x y}^{1, e}(i \Omega)= -(1-\delta)  r_0^{-\delta} 2^{4+\delta} \pi \frac{\Gamma[(3+\delta) / 2]}{\Gamma[(3-\delta) / 2]} \int \frac{d^2 \boldsymbol{k}}{(2 \pi)^2} \int \frac{d^2 \boldsymbol{l}}{(2 \pi)^2} \int _{-\infty}^{\infty}\frac{d \alpha^{\prime}}{2 \pi} \int _{-\infty}^{\infty}\frac{d \alpha}{2 \pi} \frac{l_x l_y}{l^{\delta+3}} \operatorname{Tr} \notag\\
 &\left[-\frac{i \alpha^{\prime}+ \boldsymbol{\sigma} \cdot(\boldsymbol{k}+\boldsymbol{l})}{\alpha^{\prime 2}+( |\boldsymbol{k}+\boldsymbol{l}|)^2}\right]\left[-\frac{i(\alpha+\Omega)+ \boldsymbol{\sigma} \cdot \boldsymbol{k}}{(\alpha+\Omega)^2+k^2}\right] \frac{ \left(k_x \sigma_y+k_y \sigma_x\right)}{2}\left[-\frac{i \alpha+  \boldsymbol{\sigma} \cdot \boldsymbol{k}}{\alpha^2+k^2}\right],\notag\
\end{align}
where $\boldsymbol{k}$ and $\boldsymbol{l}$ are momentum of electrons in two dimension, $\boldsymbol{\sigma} $ are Pauli matrices, $r_{0}$ is a constant, $\delta$ is an infinitesimal constant and take the limit $\delta\rightarrow 0$ at the end.
Following a thorough calculation, and analytical continuation to real frequencies $i \Omega \rightarrow \omega+i \delta$, we can arrive at the expression $$\frac{\operatorname{Im} C_{x y x y}^{(1, e)}}{\omega}   = \frac{2^{2 \delta-8}(\delta-1) \omega^{-\delta} r_0^{-\delta} \Gamma(\delta / 2)}{\Gamma(3-\delta / 2)} \omega^2.$$
To ensure accuracy of the results, I wish to validate the analytical results through numerical method. However, it is challenging to integrate the original expression, as the integrand is a highly oscillatory function. How can we numerically verify the accuracy of the above results?

To make numerical calculation easier, I need to preprocess the expression. It has been noted that the trace consists of four components, with the $\alpha^{\prime}$ of the first component being zero after the integration is completed. Consequently, the expression can be reduced to
\begin{align}
 &C_{x y x y}^{1, e}(i \Omega)= -(1-\delta)  r_0^{-\delta} 2^{4+\delta} \pi \frac{\Gamma[(3+\delta) / 2]}{\Gamma[(3-\delta) / 2]} \int \frac{d^2 \boldsymbol{k}}{(2 \pi)^2} \int \frac{d^2 \boldsymbol{l}}{(2 \pi)^2} \int _{-\infty}^{\infty}\frac{d \alpha^{\prime}}{2 \pi} \int _{-\infty}^{\infty}\frac{d \alpha}{2 \pi} \frac{l_x l_y}{l^{\delta+3}} \operatorname{Tr}  \left[-\frac{  \boldsymbol{\sigma} \cdot(\boldsymbol{k}+\boldsymbol{l})}{\alpha^{\prime 2}+( |\boldsymbol{k}+\boldsymbol{l}|)^2}\right]\left[-\frac{i(\alpha+\Omega)+ \boldsymbol{\sigma} \cdot \boldsymbol{k}}{(\alpha+\Omega)^2+k^2}\right] \frac{ \left(k_x \sigma_y+k_y \sigma_x\right)}{2}\left[-\frac{i \alpha+  \boldsymbol{\sigma} \cdot \boldsymbol{k}}{\alpha^2+k^2}\right],\notag\
\end{align}
Integrating $ \alpha $ and $ \alpha ^ { \prime} $ yields
$$C_{x y x y}^{1, e}(i \Omega)= \int_{0}^{\infty} dk\int_{0}^{\infty} dl\int_{0}^{2\pi}d\theta_{k}\int_{0}^{2\pi}d\theta_{l}\frac{2^{\delta } k^2 \Gamma \left(\frac{\delta +3}{2}\right) \cos (2 \theta _k) \sin (2 \theta _l) l^{-\delta } r_{0}^{-\delta } \sin (\theta _k-\theta _l)}{\pi ^3 \Gamma \left( \frac{1-\delta }{2}\right) \left(4 k^2+\Omega ^2\right) \sqrt{k^2+2 k l \cos (\theta _k-\theta _l)+l^2}}$$
Let us assume that $\delta=0.1$, $r_{0}=1$, and $\Omega=-0.2i$, and then use Mathematica for numerical integration. The result of the calculation is unsatisfactory because singularity or highly-oscillatory integration may be present.

The code I formulated using Mathmatica is displayed below.
Clear["`*"]

equ=-(1-\[Delta])*r0^-\[Delta]*2^(\[Delta]+4)*Pi*Gamma[(3+\[Delta])/2]/Gamma[(3-\[Delta])/2]*(-1)*(-1)*(1/2)*(-1)*1/(2*Pi)^6*1/(\[Alpha]prime^2+(Sqrt[(kx+lx)^2+(ky+ly)^2])^2)*1/((\[Alpha]+\[CapitalOmega])^2+k^2)*1/(\[Alpha]^2+k^2)*(lx*ly)/l^(3+\[Delta])*Tr[(I*0*PauliMatrix[0]+PauliMatrix[1]*(kx+lx)+PauliMatrix[2]*(ky+ly)).(I*(\[Alpha]+\[CapitalOmega])*PauliMatrix[0]+PauliMatrix[1]*kx+PauliMatrix[2]*ky).(kx*PauliMatrix[2]+ky*PauliMatrix[1]).(I*\[Alpha]*PauliMatrix[0]+PauliMatrix[1]*kx+PauliMatrix[2]*ky)];
equ2=equ/.{lx->l*Cos[\[Theta]l],ly->l*Sin[\[Theta]l],kx->k*Cos[\[Theta]k],ky->k*Sin[\[Theta]k]};
equ3=FullSimplify[Integrate[equ2,{\[Alpha]prime,-Infinity,Infinity},{\[Alpha],-Infinity,Infinity}],k>0]
NIntegrate[equ3/.{\[Delta]->0.1,r0->1,\[CapitalOmega]->-0.2*I},{\[Theta]k,0,2*Pi},{\[Theta]l,0,2*Pi},{k,0,Infinity},{l,0,Infinity}]


text:
Q: ADAL reduce token lifetime from the default 60 minutes for testing we're working on some Azure-related script using ADAL for authentication. I'm working on the code for refreshing the access token, and would like to test this without having to wait for 60 minutes until the access token expires. Anyone know if there's a way to reduce the token lifetime to ease testing scenarios?

A: If you are using ADAL the refresh logic is already provided by the library automatically. Whenever you call AcquireToken* ADAL will either return the cached token if present and still within validity range or use the refresh token to get you a new one. For that reason, there are no knobs for getting a new access token before its validity expires. You can use experience modifiers (like PromptBehavior) for ignoring the cache, or you can surgically delete the cache entry for the token you are worksite its, but both approaches will result in deleting the refresh token too and in a prompt to the user.


text:
Q: php: interface inheritance: add optional parameter in child interface The following seems to work ok in PHP 5.5.6, but not in PHP 5.3:
(following this bug report on a piece of code I wrote)
(supposed error message is Fatal error: Can't inherit abstract function ...)
interface A {
  function foo($a);
}

interface B extends A {
  function foo($a, $b = NULL);
}

In my understanding this does not violate the LSP principle. You are not allowed to narrow down the signature, but you should be allowed to losen it..
The purpose of this is I have an interface A that I cannot change for BC, but then I still want to introduce the additional parameter. This seemed to work all fine until this bug report showed up.
Is this simply a PHP version thing?

A: This seems to be indeed a version thing.
https://stackoverflow.com/a/21381524/246724:

"it helped upgrading from PHP 5.3.8 to PHP 5.3.28."


text:
Q: npm install unhandled rejection I'm trying to figure out why npm install no longer works on a Ubuntu 14 LTS machine.
The project is a nuxt project, and npm install works on a Unix machine.
I have tried uninstalling and reinstall both node and npm.
Current versions are:

*

*node: v10.15.1

*npm : 6.4.1

If I run npm install --verbose
we get
Unhandled rejection Error: Command failed: /usr/bin/git clone --depth=1 -q -b master git://github.com/dcodeIO/long.js.git /home/<USER>/.npm/_cacache/tmp/git-clone-226d28b2
/home/<USER>/.npm/_cacache/tmp/git-clone-226d28b2/.git: Permission denied

    at ChildProcess.exithandler (child_process.js:294:12)
    at ChildProcess.emit (events.js:189:13)
    at maybeClose (internal/child_process.js:970:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:189:13)
    at Pipe._handle.close (net.js:600:12)

npm timing npm Completed in 128572ms
npm ERR! cb() never called!

npm ERR! This is an error with npm itself. Please report this error at:
npm ERR!     <https://npm.community>

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/<USER>/.npm/_logs/2019-02-21T15_22_07_078Z-debug.log

the last few lines of that file are:
17822 silly extract core-js@2.6.5 extracted to /home/<USER>/<PROJECT>/node_modules/.staging/core-js-49a396dc (950ms)
17823 silly extract vuetify@1.5.1 extracted to /home/<USER>/<PROJECT>/node_modules/.staging/vuetify-c586b9e6 (4197ms)
17824 timing npm Completed in 128572ms
17825 error cb() never called!
17826 error This is an error with npm itself. Please report this error at:
17827 error <https://npm.community>

A: try to install node by nvm (node version manager).
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
just try these simple step's (hope its work in your case):

*

*copy and paste this command in the terminal after completing this.

*close and re-open the terminal

*type nvm to check is nvm installed on your system.

*type by checking nvm ls (this show you a default node installed version).

*then go to your project directory and use npm install or npm i


text:
Q: W3 Validation of HTML form When im trying to validate my page on http://validator.w3.org/ i get one error that says

Line 118, Column 44: there is no attribute "onClick"

But when I change the onClick to just onclick i get about 40 new errors and almous al of them is complaining about the character, they want me to change the caracters to the HTML format, but If i do that my PHP script stop working.
This is one of the rows that the validator is complaning about after I change onClick to onclick
<input type="text" name="enterprise" id="enterprise" value="<?php echo isset($_POST['enterprise']) ? $_POST['enterprise'] : '' ?>" />

and this is my onclick string
<input type="button" value="Clear" onclick="window.location.reload();return false" />

Is there another way I can reload the page or how can I write the input type php scrip so it validates.
Thanks in advance

A: the W3 validator will complain if it finds any language it doesn't recognize and it's not normal in a webpage, such as php. You should pass your page trough a php server and then copy the final HTML in the validator.

A: There is 3 Method to do it with Html/JS,
<input type="button" value="Reload" onClick="window.location.reload()"/>
<input type="button" value="Reload" onClick="history.go(0)"/>
<input type="button" value="Reload" onClick="window.location.href=window.location.href"/>

Notice: You can use AJAX technology to refresh page without reloading all elements like images, css files...etc.


text:
Q: JVM http proxy in windows cmd I am using a java application which requires internet. But I have internet through proxy so application doesn't work. I am looking for a way to enable proxy in JVM (note i can't change it by code , i doesn't have source code). Kindly let me know how i can do that through command prompt on windows.
Thanks

A:  java -Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 yourprogramhere


text: Q: Google Maps API key error on some networks I have a web application that's using Google Maps Javascript v3.  I have an API key.  Everything works fine, on some networks, but on some networks, it gives me an API key error.  I've set everything correctly in the allowed refers but no luck.  It is failing when I go to the Regus business lounge and use their wifi.  It's also failing for my testers in Korea.  It works on all the other networks I have tried.  I'm going crazy and I can't figure out what's wrong here.  Any ideas or any way of debugging this?


text:
Q: How to wait for authentication check before loading default state in angularjs applicaton with ui-router I have an angularjs application that is using $transitions to check if a user is authenticated before certain $state changes. I am using passport.js to do the authentication strategy. If authentication has not occurred or fails the AuthisLoggedIn() check I want the user to be reverted back to the 'login' state. The issue I am having is that the default state '/' always seems to load before my authentication promise, Auth.getCurrentUserAsync() is done executing causing a bunch of issues. How can I enforce that no state gets loaded while waiting for this authentication check and then send the user to my 'login' state if they in all cases when they are not authenticated. My code is as follows
app.js
clientApp.run(['$transitions', '$state', '$http', 'Auth', '$rootScope',
    function($transitions, $state, $http, Auth, $rootScope) {
        $http.defaults.xsrfHeaderName = 'X-CSRFToken'
        $http.defaults.xsrfCookieName = 'csrftoken'

        $rootScope.baseApiUrl='/app/api'

        //verify the user
        $transitions.onStart(
        {
            to:  function(state) {
                if (typeof state.authenticate !== 'undefined' && state.authenticate === false) {
                    return // this state does not require authentication
                }
                if (!Auth.isLoggedIn()) {

                    Auth.getCurrentUserAsync().then(
                        function() {
                            if (!Auth.isLoggedIn()) {
                                $state.go('login')
                            }
                        }
                    )
                }
            }
        })
}])

clientApp.config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
    function($urlRouterProvider, $stateProvider, $locationProvider) {
        $urlRouterProvider
            .otherwise('/')
        $stateProvider
            .state('main', {
                url: '/',
                component: 'main',
                authenticate: true
            })
            .state('login', {
                url: '/login',
                template: loginTemplate,
                controller: 'LoginCtrl',
                controllerAs: 'Login',
                authenticate: false,
                params: {
                    loginMessage: "",
                    loginErrorMessage: "",
                    username: "",
                    password: undefined,
                    errors: []
                },
            })
        $locationProvider.html5Mode(true)
}])

auth.js
import angular from 'angular'

angular
    .module('app.factories.auth', [])
    .factory('Auth',
        ['$http', '$q', '$rootScope',
            function Auth($http, $q, $rootScope) {

                function _isLoggedIn() {
                    if (Object.keys(authObj.user).length !== 0) {
                        return true
                    } else {
                        return false
                    }
                }

                function _login(user) {
                    const deferred = $q.defer()

                    $http.post($rootScope.baseApiUrl + '/user/login', {
                        username: user.username,
                        password: user.password
                    })
                        .then(
                            function(response) {
                                if (response.status === 200) {
                                    authObj.user = response.data.user
                                    deferred.resolve(response)
                                } else {
                                    authObj.user = {}
                                    deferred.reject(response)
                                }
                            },
                            function(err) {
                                authObj.user = {}
                                deferred.reject(err)
                            }
                        )

                    return deferred.promise
                }

                function _getCurrentUserAsync() {
                    return $http.get($rootScope.baseApiUrl + '/user/status')
                        .then(
                            function(response) {
                                console.log('response', response)
                                if (response.data.status) {
                                    authObj.user = response.data.user
                                } else {
                                    authObj.user = {}
                                }
                            },
                            function() {
                                authObj.user = {}
                            })
                }

                const authObj = {
                    isLoggedIn: _isLoggedIn,
                    getCurrentUserAsync: _getCurrentUserAsync,
                    login: _login,
                    user: {}
                }

                return authObj
            }
        ])


text:
Q: WebStorm annotate cutting off usernames on dashes and spaces When using the Annotate functionality in WebStorm, if a user that commited code has a username that contains a space or dash, WebStorm only shows the part of their name after the space or dash.
I'm not sure if this is intentional functionality, or if there is an option to change it (I couldn't find one).  But I would expect it to behave like git blame by default.
Currently:

*

*"user-name" -> "name" shows

*"firstName lastName" -> "lastName" shows

Expected:

*

*"user-name" -> "user-name"

*"firstName lastName" -> "firstName lastName"

Question: is there an option to switch the functionality? or is it a bug or expected behavior?

A: Yup, right click the annotation bar > view > name > full name: