text:
Q: How to serialize a string into JSON and group by one of the values? I am currently serialising a datatable using JsonConvert().SerialiseObject(dt) into a JSON format that looks something like
{"id": "123", "name": "xyz", "value": "a"},{"id": "234", "name": "xyz", "value": "a"},{"id": "789, "name": "x", "value": "b"} etc
I would like the format to be grouped by the value for example:-
[
   {
      "value":"a",
      "members":[
         {
            "id":"123",
            "name":"xyz"
         },
         {
            "id":"234",
            "name":"xyz"
         }
      ]
   },
   {
      "value":"b",
      "members":[
         {
            "id":"789",
            "name":"x"
         }
      ]
   }
]

is this easy to achieve with newtonsoft?

A: You would preferably get your data in the required format before serialization.
Something like this for example:
using System;
using System.Linq;
using System.Text.Json;

var dataTable = new[]
{
    new { Id = 123, Name = "xyz", value = "a" },
    new { Id = 123, Name = "xyz", value = "a" },
    new { Id = 123, Name = "xyz", value = "b" },
};

var groupedByValue = dataTable
    .GroupBy(x => x.value)
    .Select(x => new
    {
        Value = x.Key,
        Members = x.Select(m => new
        {
            m.Id,
            m.Name
        })
    });

var json = JsonSerializer.Serialize(groupedByValue);

Console.WriteLine(json);


text:
Q: Running a function in a for loop I have a simulator which rolls a 6 sided dice:
def diceRoll6():
    return random.randint(1,6)

and now I want to repeat this roll with a for loop, but also to be able to change which simulator I am using in the function, e.g. maybe I have another function which rolls 2 dice and takes the product.
def frequencies(sim,n):
    output = []
    for i in range(n):
        result = sim
        output.append(result)
    return output

However whenever I run frequencies(diceRoll6(),10) it just has the same output 10 times, rather than running the simulator 10 separate times and getting different outputs.

A: You also dont execute the sim function in the for loop. so your actually passing the result of the function to frequencies rather than the function its self.
So your saying execute the diceroll function, get its result and pass that to frequencies. Instead you need to pass the func to it without the () so that your passing a reference to the func not its result.
So frequencies is just receiving the int value from diceroll and the n times. So it will append that int n times to the list
you need to pass the dice roll function not its result to frequency and have frequency function execute it for you n times.
import random

def diceRoll6():
    return random.randint(1,6)

def frequencies(sim,n):
    output = []
    for i in range(n):
        result = sim()
        output.append(result)
    return output

print(frequencies(diceRoll6, 10))

you could also simply your frequencies function to be something like
def frequencies(sim,n):
    return [sim() for _ in range(n)]

A: Passing a function into another function as a variable is fine and you did it correctly here. When you call frequencies(diceRoll6,10), sim=diceRoll6. However, in the loop you set result=sim and then append result which means you are appending the function diceRoll6 10 times when you instead want to call diceRoll6 and append the result.
Try:
def frequencies(sim,n):
    output = []
    for i in range(n):
        result = sim()
        output.append(result)
    return output

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change the int variable in a cycle and if so is there a more efficient way? First post ever on this site so spare my life , please.
I'm trying to do a little encryption and decryption program imitating the Enigma cipher/machine from the WW2 (enough history lessons)
So I'm trying to input a number and a letter like so : 1h 2e 3l 4l 5o ;
Because I don't use a cycle I need to write for every variable that I'm adding the number , but what do I do if I have less letters than variables?The only way I can think of is using a cycle which checks if the input is a letter or not.That's why the current code I've written only can be used for specific amount of numbers and  letters...
#include <iostream>
#include <limits>
using namespace std;
int main()
{

int opt;
cout<<"Enter 1 for encryption and 2 for decryption. "<<endl;
cin>>opt;
if(opt == 1)
  {
  int setting1,setting2,setting3,setting4;
  char a,b,c,d;
  cout<<"_________________________________________________"<<endl;
  cin>>setting1>>a>>setting2>>b>>setting3>>c>>setting4>>d;
    a+=setting1;
    b+=setting2;
    c+=setting3;
    d+=setting4;
  cout<<(char)a<<" "<<(char)b<<" "<<(char)c<<" "<<(char)d<<endl;

  }
if(opt == 2)
  {
  int setting1,setting2,setting3,setting4;
  char a,b,c,d;
  cout<<"_________________________________________________"<<endl;
  cin>>setting1>>a>>setting2>>b>>setting3>>c>>setting4>>d;
    a-=setting1;
    b-=setting2;
    c-=setting3;
    d-=setting4;
  cout<<(char)a<<(char)b<<(char)c<<(char)d<<endl;

  }
  if(opt !=1 && opt !=2)cout<<"ERROR!"<<endl;

  std::cout << "Press ENTER to continue..."<<endl;
  std::cin.ignore( std::numeric_limits<std::streamsize>::max(),'\n');
  return 0;
}

Also I was told that the last 2 lines would prevent the .exec from closing after it's done doing it's thing.

A: I recommend inputting your data in loops (cycles).  But before that is accomplished, I suggest using a structure (or class) with an overloaded stream extraction operator.
struct Number_Letter
{
  int number;
  char letter;
  friend std::istream& operator>>(std::istream& inp, Number_Letter& nl);
};
std::istream& operator>>(std::istream& inp, Number_Letter& nl)
{
  inp >> nl.number;
  if (inp)
  {
    inp >> nl.letter;
    if (!isalpha(nl.letter))
    {
      // Error recovery for not reading a letter
    }
  }
  else
  {
    // Error recovery for failing to read number.
  }
  return inp;
}

Your input loop would be something like:
Number_Letter nl;
while (std::cin >> nl)
{
  // process the data
}

For cryptography, you may want to keep the data as a string:
std::string message;
getline(cin, message);
for (unsigned int i = 0; i < message.length(); i += 2)
{
  if (!isdigit(message[i]))
  {
    cerr << "Invalid message type at position " << i << endl;
    break;
  }
  if (i + 1 > message.length())
  {
    cerr << "Missing letter at end of message.\n";
    break;
  }
  if (!isalpha(message[i+1]))
  {
    cerr << "Invalid message type at position " << i << endl;
    break;
  }
}

A: It sounds like you're trying to check for an unknown sequence of character/integers and need a loop to do the check?
int opt;
cout<<"Enter 1 for encryption and 2 for decryption. "<<endl;
cin>>opt;

if(opt != 1 && opt != 2)
{
  cout << "Error" << endl;
  return -1;
}

int integer;
char character;
char again;

do
{
    cout<<"_________________________________________________"<<endl;

    cin>>integer>>character;

    if(opt == 1) {
        character+=integer;
    } else if(opt == 2) {
        character-=integer;
    }

    cout << character <<endl;

    cout << "Again (Y)?: ";
    cin>>again;
}while(again == 'Y' || again == 'y');

std::cout << "Press ENTER to continue..."<<endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(),'\n');
return 0;


text:
Q: Error executing Dataflow task from Cloud composer: Log file is not found In one of our Cloud Composer/Airflow jobs, we invoke a number of DataflowTemplateOperator jobs (JDBC to BigQuery) to bring in data from a postgres instance into BigQuery. We are intermittently experiencing an error:
*** Log file is not found: gs://us-east1-xxxxxxx-prod-cfaffd18-bucket/logs/xxxxxx-dag-daily-job/xxxxxxx/2022-01-29T07:30:00+00:00/1.log. The task might not have been executed or worker executing it might have finished abnormally (e.g. was evicted)
*** 404 GET https://storage.googleapis.com/download/storage/v1/b/us-east1-xxxxxx-cfaffd18-bucket/o/logs%2Fprod-xxxxxx-dag-daily-job%2Fdw_load_locations%2F2022-01-29T07%3A30%3A00%2B00%3A00%2F1.log?alt=media: No such object: us-east1-xxxxxx-cfaffd18-bucket/logs/xxxxxx-dag-daily-job/xxxxxxx/2022-01-29T07:30:00+00:00/1.log: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)

Environment:
Composer version: 1.17.7
Aitflow version: 2.1.4
The jobs complete successfully upon retrying.
Is this a known issue? Looking for some guidance on how to debug this. Any help is much appreciated.
Thanks.

A: We get rid of this error after we increased vCPUs for the workers. It turned out that "missing log file" is not the problem but the consequence of the real problem which is:
"The task might not have been executed or worker executing it might have finished abnormally (e.g. was evicted)"


text:
Q: How to show element only if other element contains something using jQuery? My guess is what I want to achieve should be easy, but due to my lack of knowledge of front-end development, I cannot manage to solve issue. Have a page that works with AJAX-filters that users can select. Filters that are currently applied show up within
  with id=current-filters.
HTML looks like this:

        Current filters:

Need to hide the the entire DIV current-filters-box in case no filter is applied.
The page uses a Javascript file, bundle.js which is massive, but contains the following line:
s=document.getElementById("current-filters")

Therefore tried the following if-statement to hide the DIV:
if(s.length<1)$('#current-filters-box').hide()

and
if(s=0)$('#current-filters-box').hide()

But this does not seem to have any effect. Can someone tell, what I did wrong?
Demo of page can be found here
EDIT: this is what the HTML looks like when filters are applied:

    Current filters:

            Humanities & Languages ×

            January ×

A: Both of your conditions are incorrect or I would say they are not doing what you think they do.
s.length will always prints undefined so instead of s.length<1 you could use s.children.length
and the second one is not a condition rather it is an assignment
s==0 // condition
s=0 //assignment

the correct condition for your requirement would be
if(s.children.length<1){

I have assigned snippets for illustration.
Without filters

s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
  $('#current-filters-box').hide(1000)
}

  filter box

    Current filters:

Without filters

s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
  $('#current-filters-box').hide(1000)
}

    Current filters:

        Humanities & Languages ×

        January ×

A: Try this .
if( $('#current-filters').is(':empty') ) {
    $('#current-filters-box').hide()// or $('#current-filters-box').css("display","none")

    }

A: You are performing an assignment, try..
if (s.children.length)

A: Using vanilla JavaScript, you can check if the current-filters div is empty or not and toggle the parent div current-filters-box like this:
s= document.getElementById("current-filters");
t= document.getElementById("current-filters-box");

if(s.children.length<1) {
    t.style.display = 'none';
    // t.style.visibility= 'hidden'; <<-- use this if you want the div to be hidden but maintain space
}
else {
    t.style.display = 'block';
    // t.style.visibility= 'visible'; <<-- use this if you used visibility in the if statement above
}

A: You can achieve this by adding your own variable which counts or maintains your applied filters, e.g.
var applied_filter_count = 0;

at every time filter is applied
applied_filter_count++;
if(applied_filter_count) {
   $('#current-filters-box').show()
}

and at every time filter is removed
applied_filter_count--;
if(!applied_filter_count) {
   $('#current-filters-box').hide()
}

and by default current-filters-box should be display:none


text:
Q: Why orientDB connection to localhost of docker is refused I did build orientDB and appserver on docker. They are running as well. This is list containers on docker:
core@localhost ~ $ docker  ps
CONTAINER ID        IMAGE                      COMMAND                CREATED
       STATUS              PORTS
NAMES
01abef0204a7        fxrialab/appserver:latest   /usr/sbin/httpd -D F   30 minute
s ago      Up 30 minutes       0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp
appserver
f6d0631bb092        fxrialab/orient:latest      /bin/sh -c cd /opt/o   30 minute
s ago      Up 30 minutes       0.0.0.0:2424->2424/tcp, 0.0.0.0:2480->2480/tcp
appserver/db,orient
ebc1386250b9        fxrialab/data:latest        /usr/sbin/sshd -D      30 minute
s ago      Up 30 minutes       0.0.0.0:2200->22/tcp
data

Also i did create database on orientDB. I think orient is working fine. However when i login to my website. I got errors "Connection refused" like this:

Socket error #111: Connection refused
• vendors/OrientDB/OrientDB.php:254
  OrientDBSocket->__construct('localhost','2424',30)
  • apps/models/DB.php:11 OrientDB->__construct('localhost','2424')

I dont know what reason althought i did test fine on local when i enabled server.bat file. Ah, i using orientdb-1.7
Thank for advance !

A: localhost is a synonim for ip address 127.0.0.1
your binds are for 0.0.0.0
I am not familiar with OrientDB, but I believe that what you are facing is ports access problem (server configuration), not software problem (in this case software is OrientDB). Most servers are configured to block all ports, unless specifically allowed - for security reasons, so that noone can connect to the server on those blocked ports.
So, what is probably happening is that your local server is fine with using those ports, and remote server is secured and thus prevents connections.

A: Docker is running a virtual machine with separate network interface for each containers. Thus if your appserver connects to localhost, it won't see the orientdb.
You need to update your configuration to lookup the proper environment variable for the link (see http://docs.docker.com/userguide/dockerlinks/) or just use the db host. Docker injects a hostname into /etc/hosts for each linked container.

A: I've found cause of this issue, because im config HOST to connect is wrong. It's not localhost because docker uses its own internal IP's. In ssh type docker inspect orient then use global variables for config to access to IP & Port.


text:
Q: Inbuilt richtextox shortcuts I once discovered an overview of inbuilt richtextbox shortcuts somewhere on microsoft.com website, but I can't find it. It contained useful hotkeys, like Ctrl+Shift+L for switching bullet style.
Where can I find a list of inbuilt richtextbox shortcuts?
(I need to know the hotkey for changing line spacing.)

A: Found it!
http://msdn.microsoft.com/en-us/library/bb787873(v=vs.85).aspx#rich_edit_shortcut_keys


text:
Q: How to organize a .NET MVC application in Visual Studio I am starting to create a complete application in Visual Studio (.NET MVC).  Does it makes sense if I put everything into a single solution and create three separate projects:  Admin (used by staff to manage the app data), Web (public facing web pages), Shared (common data access and other code).  This seems to make sense as later I might add a project for Mobile or an API or ...
If not, how do you structure your solutions/projects in Visual Studio?

A: If it were me, I'd have everything in one project and use areas to separate my views and models.
Example,
Project
    Areas
        Admin
            Controllers
                AdminController.cs
            Models
                Admin.cs
        Main
            Controllers
                MainController.cs
            Models
                Main.cs
                LoginLogout.cs
                LoginForm.cs
    Views
        Admin
            Shared
                permissions.cshtml
                admin.cshtml
        Main
            Shared
                loginLogout.cshtml
                loginForm.cshtml
            master.cshtml
            Index.cshtml

Walkthrough: Organizing an ASP.NET MVC Application using Areas
Areas provides a really nice way to section off pieces of your web application, and because it's all in the same project you can have all your sections use the same View Layout (Master Page) to make it all look the same from section to section.
Areas will map to urls like
    http://somesite/main/index
http://somesite/admin/manage/index
In that example, you would not put your main section in an area, instead use normal model view controller patterns for the main part of the site, and only introduce an area for admin or other sections.


text:
Q: Black sun animation in iTunes. Does anyone know what it is? I got this black sun animation inside my iTunes.
It was triggered by some shortcut, but I can't remember which one.
Does anyone know what it is?

A: That is the Visualizer.  You can press Command + T (Ctrl + T on Windows) to start it.  Or it is available form the View Menu.
View --> Show Visualizer

Also in the View Menu you can change some of the settings for the way the Visualizer looks.
View --> Visualizer --> <More Options Here>


text:
Q: How to handle nested transaction exception in spring integration I have a DB-based channel and a simple integration flow like following:
        return IntegrationFlows.from("messageChannel")
                .handle(messageHandler, "process", consumer ->
                        consumer.poller(poller -> poller
                                .fixedDelay(3000)
                                .transactional()
                                .transactionSynchronizationFactory(messageStoreSynchronizationFactory)
                                .taskExecutor(taskExecutor)
                                .receiveTimeout(1000)
                                .maxMessagesPerPoll(10)))
                .get();

As a part of message processing (messageHandler.process) I need to open nested transactions to reach out to other databases. The problem is that any unhandled exception that might be thrown from a nested transaction sets my parent transaction to rollback-only which puts my message back to the channel. That creates a loop that blocks the channel until an issue with a nested transaction is fixed.
In theory, I should catch and handle exceptions within a nested transaction and never propagate to the parent one but it's hard to enforce that with my current project architecture.
Removing .transactional() from the poller removes parent transaction out of the picture and "fixes" the issue but then it never calls transaction synchronization factory (which makes sense).
Is there a way to allow the nested transaction to throw an exception and still process the message?

A: You can either add a .gateway() mid-flow and handle the exception via it's errorChannel or you can add an ExpressionEvaluatingRequestHandlerAdvice (or custom advice) to the handler's endpoint to handle the exception there.
See Adding Behavior to Endpoints.


text:
Q: "Might have" vs "could have" What is the difference between might have and could have?

He might have come. He might have studied.
He could have come. He could have studied.

How would you describe a possibility? For example:

It's possible that he came from a different culture.
It's possible that he come from a different cutlure.

A: Could and might are often, but not always, interchangeable. He might have come / studied = 'We don't know whether has come / studied or not', but you could substitute could. If you want to indicate ability or permission, however, you need He could have come  / studied  = 'He had the ability to come / study.'
It's possible that he came from a different culture would be used in considering a historical figure who didn't seem to fit into his environment. If you were talking about a current situation, you'd say It's possible that he comes from a different culture. It's hard to think of any circumstances in which It's possible that he come from a different culture would be used, even if you regard 'come' as subjunctive.
English modal verbs are both important and subtle. You're unlikely to gain a full understanding of their use in exchanges such as this and if, as I assume, Noah, you are a non-native speaker of English you really need the help of a qualified English teacher.

A: It's quite simple really. Consider these examples:
It might be a lie.
It could be a lie.
In these two statements, the first makes room for a 'but' in the equation, such as, 'It might be a lie, but it helped us succeed'. Here the first statement is an admission of the lie. It explicitly states that what you said might be a lie, but it was still beneficial in some sense, so it's acceptable.
Whereas the second statement, make no such admission of guilt. It just states that it could be lie, it couldn't be a lie and such.
I feel this 'could vs might' dilemma only happens when you're using them in a negative sense like, 'It might be a lie', 'He might have killed him' and such.
Anyway, this is just my understanding of the concept, please feel free to debate or message me.


text:
Q: Clear Application's Data Programmatically I want to clear my application's data programmatically.
Application's data may contain anything like databases, shared preferences, Internal-External files or any other files created within the application.
I know we can clear data in the mobile device through:

Settings->Applications-> ManageApplications-> My_application->Clear
  Data

But I need to do the above thing through an Android Program?

A: combine code from 2 answers:

*

*https://stackoverflow.com/a/42228794/1815624

*https://stackoverflow.com/a/29197259/1815624
Here is the resulting combined source based answer
private void clearAppData() {
    try {
        // clearing app data
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData(); // note: it has a return value!
        } else {
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: What I use everywhere :
 Runtime.getRuntime().exec("pm clear me.myapp");

Executing above piece of code closes application and removes all databases and shared preferences

A: There's a new API introduced in API 19 (KitKat):
ActivityManager.clearApplicationUserData().
I highly recommend using it in new applications:
import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.
Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.

Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.
private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

A: I'm just putting the tutorial from the link ihrupin posted here in this post.
package com.hrupin.cleaner;

import java.io.File;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public void clearApplicationData() {
        File cacheDirectory = getCacheDir();
        File applicationDirectory = new File(cacheDirectory.getParent());
        if (applicationDirectory.exists()) {
            String[] fileNames = applicationDirectory.list();
            for (String fileName : fileNames) {
                if (!fileName.equals("lib")) {
                    deleteFile(new File(applicationDirectory, fileName));
                }
            }
        }
    }

    public static boolean deleteFile(File file) {
        boolean deletedAll = true;
        if (file != null) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                }
            } else {
                deletedAll = file.delete();
            }
        }

        return deletedAll;
    }
}

So if you want a button to do this you need to call MyApplication.getInstance(). clearApplicationData() from within an onClickListener
Update:
Your SharedPreferences instance might hold onto your data and recreate the preferences file after you delete it. So your going to want to get your SharedPreferences object and
prefs.edit().clear().commit();

Update:
You need to add android:name="your.package.MyApplication" to the application tag inside AndroidManifest.xml if you had not done so. Else, MyApplication.getInstance() returns null, resulting a NullPointerException.

A: If you want a less verbose hack:
void deleteDirectory(String path) {
  Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}

A: Try this code
private void clearAppData() {
    try {
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
        } else {
            Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: OracleDataAdapter returns no rows, but the query string works in SQLDeveloper visual studion 2008
oracle db 11.1.0.7
oracle client for .NET
I have a relatively simple query, that selects the rows from across multiple tables (up to 4) using joins. OracleDataAdapter returns no rows for the only dataset's table, but if I copy and paste that query in SQLDeveloper then I get the desired results.
I can get the data from other tables using the adapter with no problem, but it seems like it struggles with the bit longer selection query (string length is ~ 300 (not that much at all))
Connection string for the connection is 100% correct.
Any ideas? thank you...

A: *

*Check that you using same oracle user to connect to database. Maybe FGAC hides data.

*Check that there is no temporary tables in you query.

A: Solution by OP.
The problem was, that after I imported the data in the SQLDeveloper in one of the involved tables, this change hasn't been committed automatically as I've falsely presumed... I've figured this out after I edited some data in the same table within the SQLDeveloper, and it has failed with the message that the edit operation on uncommitted action is now allowed. The headache I had was in SQLDeveloper, not the DataAdapter.


text:
Q: access-Control-Allow-Origin when Call functions from your app I am trying to call firebase function from my web app
I am getting

access-Control-Allow-Origin error

My code is from web:
   var createNewUserAndEvent = firebase.functions().httpsCallable('createNewUserAndEvent');
   const data= await  createNewUserAndEvent(userData);

and from firebase function:
const functions = require("firebase-functions");
var admin = require("firebase-admin");
admin.initializeApp();
exports.createNewUserAndEvent = functions.https.onCall((data, context) => {
  cors({ origin: true })(data, context, async () => {
    if (!context.auth) {


text:
Q: why this syntax can pattern this "for" macro? #lang racket
(define-syntax for
  (syntax-rules ()
    ((_ list 'as element body ...)
     (map (lambda (element)
            body ...)
          list))))

>
      (for '(0 1 2 3 4) 'in i
        (print i)
        (newline))

=>
0
1
2
3
4
'(# # # # #)
My question is why the symbol 'in can pattern the symbol 'as ?
The symbol 'in isn't a only pattern with 'in?

A: In the Racket doc, at some point it says

The template is used in place of a form that matches the pattern, except that each instance of a pattern variable in the template is replaced with the part of the macro use the pattern variable matched.

which makes me think that the 'as symbol is simply ignored. And indeed, this
(define-syntax for
  (syntax-rules ()
    ((_ list element body ...)
     (map (lambda (element)
            body ...)
          list))))
(for '(0 1 2 3 4) i (print i) (newline))

works just as well.
To get the behaviour you want, use
(define-syntax for
  (syntax-rules (as)
    ((_ list as element body ...)
     (map (lambda (element)
            body ...)
          list))))

then
>  (for '(0 1 2 3 4) as i (print i) (newline))
0
1
2
3
4
'(#<void> #<void> #<void> #<void> #<void>)

but
>  (for '(0 1 2 3 4) in i (print i) (newline))
for: bad syntax in: (for (quote (0 1 2 3 4)) in i (print i) (newline))

A: Macro patterns are not evaluated. In particular, 'as is not a symbol. It is simply the list (quote as). ('as evaluates to a symbol, but it isn't by itself a symbol.) Thus, your macro is really the same as:
(define-syntax for
  (syntax-rules ()
    ((_ list (quote as) element body ...)
     (map (lambda (element)
            body ...)
          list))))

where quote and as are pattern variables that can match anything whatsoever.
As mentioned in uselpa's answer, the correct way to require the use of as exactly as written is to use the literal list:
(define-syntax for
  (syntax-rules (as)
    ((_ list as element body ...)
     (map (lambda (element)
            body ...)
          list))))

Or, if you're really sadistic and want to make the user quote the as, do this:
(define-syntax for
  (syntax-rules (quote as)
    ((_ list 'as element body ...)
     (map (lambda (element)
            body ...)
          list))))

(Yes, you can even change the literal list to be 'as instead of (quote as) as I have it, but that just makes your macro unreadable. Don't do that. :-P)


text:
Q: How to find polarity of photo interrupter I have scavenged some photo interrupters from multiple printers but I am trying to figure out the polarity and the voltage. I've tried searching up photo interrupter polarity but couldn't find anything. On one of side of a sensor, it is labelled: A and K and on the other side it says E and C. It also says on the sensor H306-41. All the other sensors are unlabelled. Is there an easy way to find the polarity and voltage with a meter?
Edit: Images:
Picture of labelled sensor:

Picture of unlabelled sensor:

A: Usually the labels are as follow:

*

*A - Anode, this is the LED anode (+)

*K - Cathode, this is the LED cathode (-)

*E - Emittor, phototransistor Emittor

*C - Collector, phototransistor Collector.

The photo transistor base is basically the light from the LED.


text:
Q: Laravel - Login to only one browser at a time I am building a simple log in app and I want to allow users to login from one browser at a time.
In other words, if users are logged in in Safari, and then open a Firefox browser and login into the app, Safari app should log them out. Likewise, if users then try to login again into Safari, Firefox app should kick them out. Can some one help me in this. Currently I am using Laravel's out of the box login module to make development fast by using command PHP ARTISAN MAKE:AUTH.
Kindly guide me.

A: How I would do it: I would consider adding a 'user_agent' column to the 'users' table in your database, in which you can record the browser type each time a user logs in (using $_SERVER['HTTP_USER_AGENT'] or the like...). Once that's in place, you can add a Middleware that will compare the stored user agent against the current user agent and initiate a logout if the two don't match.
However, this will only log the user out of the Safari browser once they have logged into the Firefox browser and then they try to go back to Safari. If you need the Safari browser to logout immediately as soon as the user logs into a different browser, you can simply add an ajax polling function that will trigger the Middleware even when the user is not actively using the site (and this way the Safari browser will logout as soon as the user logs into Firefox etc).
Again, I'm sure there are many ways to butter this slice of toast, these are just my initial thoughts...

A: It's pretty simple – when you log users in (most probably postLogin() method of your AuthController), in case of success - store the current session ID in the database, in User model. Then, in your 'auth' middleware, add an extra check – compare user's session ID from the model with PHP session ID. User will be kicked out in other browsers or sessions upon next click.
Steps in more detail:

*

*Add a migration that adds a current_session field to User table.

*Persist current session ID in postLogin()

*Compare session ID from the database with PHP session ID. Optionally, destroy the session in case of mismatch


text:
Q: Best practice to pass input values and variables to POST? I'll try and keep it succinct.
I am using Stripe JS to process payments.The code for my form below:
<form id="payment-form" action="components/charge.php" method="POST" onSubmit={this.submitFormHandler.bind(this)}>

    Name
    <input className="first-name" id="first_name" type="text" size="50" autoComplete="off" data-stripe="first_name"/>
    <input className="card-number" type="text" size="20" autoComplete="off" />
    <input className="card-cvc" type="text" size="4" autoComplete="off" />
    <input className="card-expiry-month" type="text" size="2" />
    <input className="card-expiry-year" type="text" size="4" />
    <input type="submit" id="submitBtn" className="submit" value="Submit Payment" />
</form>

The code that processes the form and charges the user below:
if (!error) {
    // Get the Stripe token:
    Stripe.card.createToken({
        number: ccNum,
        cvc: cvcNum,
        exp_month: expMonth,
        exp_year: expYear
    }, function(status, response){
        console.log(response);
        if (response.error) {
            this.reportError(response.error.message);
        } else { // No errors, submit the form.
            // Get a reference to the form:
            var paymentForm = $("#payment-form");
            // Get the token from the response:
            var token = response.id;
            // Add the token to the form:
            paymentForm.append('<input type="hidden" name="stripeToken" value="' + token + '" />');
            paymentForm.append('<input type="hidden" name="first_name" value="' + firstName + '" />');
            // Submit the form:
            paymentForm.get(0).submit();
        }
    });
 }

I've included paymentForm.append('<input type="hidden" name="first_name" value="' + firstName + '" />'); to save the first_name input value so that when I charge the user I can see further user info.
I've shortened it, the full version has address, post code, email, etc.
charge.php code below:
 <?php
 require_once('vendor/autoload.php');
 \Stripe\Stripe::setApiKey(<MY_KEY_HERE>);
 $token = $_POST['stripeToken'];
 $first_name = $_POST['first_name'];

 try{
     \Stripe\Stripe::setApiKey(<MY_KEY_HERE>);
     $customer = \Stripe\Customer::create(array(
         "source" => $token,
         "description" => "description here",
         "email" => "tester@testemail.com",
         "shipping" => array(
             "name" => "test",
             "address" => array(
                "line1" => "123 Fake St",
                "city" => "Melbourne",
                "country" => "Australia",
                "postal_code" => "6969"
             )
          )
       )
    );
    // Charge the Customer instead of the card
    \Stripe\Charge::create(array(
        "amount" => 1500, // amount in cents, again
        "currency" => "aud",
        "description" => "tester@tester",
        "customer" => $customer->id
    ));
} catch(\Stripe\Error\Card $e) {
    echo  "Your card has been declined";
}
?>

This logic works and adds the customer and charges them as expected. I just don't know if the method to save the first_name input value is the best practice. I've tried to add the input value in the Stripe.card.createToken function, but it doesn't work, I get an undefined variable in the POST process.
I can't find another way to post input values / variables to POST.
What is best practice to POST input values and variables?
Any help is much appreciated.
Thanks
Moe

A: You can't pass a first_name parameter as an argument to Stripe.card.createToken as this call expects no such argument. (There is an optional name argument for the full cardholder's name.)
The simplest way to send a (non-PCI sensitive) field to your server would be to add a name attribute to the field so that it gets submitted to your server, without you having to recreate it as a hidden field.
Basically:

*

*The non-card related input fields should have a name="..." attribute. The card related input fields should not (otherwise they'd get submitted to your server, negating the purpose of tokenization and making you ineligible for PCI SAQ A).

*In the form's submit handler, create the token using Stripe.js and add the token as a hidden field to the form.

*Submit the form. The browser will send every named field to the form's action URL.


text:
Q: extjs itemselector, how to load avialable and selected from store {
    xtype: 'itemselector',
    name: 'psa_id',
    id: 'psa_id',
    store: all_psa_store,
    displayField: 'refrence',
    valueField: 'mspa_id',
    **value: [23,56],
    //howtoloadthisfromstore**allowBlank: true,
    msgTarget: 'side',
    toTitle: '<fontcolor="blue">GAMSelected',
    fromTitle: '<fontcolor="green">GAMAvailable'

}

A: Listen to the afterrender event of your itemselector. In the callback load the store which holds the prioritized id's.
this.control({
    '#youritemselector' : {
        afterrender : this.reloadItemSelector
    }
});

...
reloadItemSelector: function(itemselector) {
    yourPriorityStore.load(function() {
        var selected = [];
        Ext.each(yourPriorityStore.data.items, function(item) {
            selected.push(item['data']['id']);
        });

        itemselector.setValue(selected);
    });
}


text:
Q: WaitForSingleObject called on semaphore fails with last error 183 (ERROR_ALREADY_EXISTS) I am trying to write a class BlockingQueue for producer-consumer style tasks. I'm using WinAPI, but i have a problem with WaitForSingleObject. When i call it on semaphore with value 0, instead of falling asleep it returns -1 (WAIT_FAILED) and GetLastError() gives 183 (ERROR_ALREADY_EXISTS). That makes me no sense, so i think i must be doing something terribly wrong. The method, where appears the problem looks this way:
template<typename elem_t>
elem_t BlockingQueue<elem_t>::pop() {

    WaitForSingleObject(_used_sem, INFINITE);
    WaitForSingleObject(_mutex, INFINITE);
    uint first = _first;
    if (++_first == _length)
        _first = 0;
    _count--;
    ReleaseMutex(_mutex);
    ReleaseSemaphore(_free_sem, 1, NULL);
    return _data[first];

}

both semaphores and the mutex are initialized in the constructor:
template<typename elem_t>
BlockingQueue<elem_t>::BlockingQueue(uint length) {

    _data = new elem_t [length];
    _length = length;
    _count  =  0;
    _first  =  0;
    _last   = -1;
    _mutex    = CreateMutex(NULL, false, NULL);
    _free_sem = CreateSemaphore(NULL, _length, INFINITE, NULL);
    _used_sem = CreateSemaphore(NULL, _count,  INFINITE, NULL);

}

Any ideas why i'm getting such strange error?
EDIT: Error 183 was due to wrong error checking, because it got overwritten by another error before calling GetLastError(). After correcting it, it's just 6 (ERROR_INVALID_HANDLE), much more meaningful.

A: You're not checking the return value of CreateSemaphore. It is likely that it is failing in this case or if it is succeeding it is creating a "impossible" semaphore. This is due to your use of INFINITE for the maximum count parameter. The maximum count argument is a signed long, INFINITE is intended for use with unsigned millisecond duration, and if you interpret as a signed LONG value, you will end up with -1. The documentation states the maximum count value must be above 0. Use LONG_MAX instead of INFINITE when creating your semaphores.


text:
Q: Set result in ViewData using JQuery Ajax call in ASP.NET MVC I am at learning phase and I am developing simple calculator using jquery and ajax in MVC and I want to show a result in viewdata["result"]. how can I do this? Please guide me.
Here is the Example of code.
**Model**

Models.calc c=new Models.calc(string n1,string n2);
c.num1=Convert.toInt32(n1);
c.num2=Convert.toInt32(n2);
int result=c.num1+c.num2;
viewdata["result"]=result;**

**iN AJAX , how i show this viewdata["result"] to show result in label.**

$.ajax({
  url: "@Url.Action("add", "Home")",
  data: JSON.stringify({ 'n1': number1, 'n2': number2 }),
  type: "POST",
  datatype: "JSON",
  contentType: "application/json;charset=utf-8",
  success: function (data) {
             @ViewData["Result"];
           },
  error: function (err) {
           console.log(err);
         }
});
}**

A: Your javascript ajax-request runs on the client side in the users browser.
you cannot access @ViewData["Result"] there, because it is a razor statement, which is interpreted on the server side.
You need to return your result in your controller action, which will be in your data variable.
After that you can pick your label, textbox or other element an set its value or innerHtml property in the "success"-part of your javascript.
e.g.
$.ajax({
  url: "@(Url.Action("add", "Home"))",
  data: JSON.stringify({ 'n1': number1, 'n2': number2 }),
  type: "POST",
  datatype: "JSON",
  contentType: "application/json;charset=utf-8",
  success: function (data) {
     $('#yourLabel').text(data); //<-- here, I look for a label with an ID
  },
  error: function (err) {
     console.log(err);
  }
});


text:
Q: standard feed locations? I want to programmatically check if a site has feeds. How can I do that?
Are there standard feed locations?
Parsing the code for link tags with application/rss+xml attribute would be enough?
Thank you.

A:
Parsing the code for link tags with application/rss+xml attribute would be enough?

As far as I know, it is the only standard way to discover feeds. But that is no guarantee that you'll find them all.

A: You might want to read this resource for information on discovering feeds. Replace "application/atom+xml" with "application/rss+xml" as necessary.

A: Use the Zend_Feed classes from Zend_Framwework. Zend_Feed::findFeeds does what you want.


text:
Q: How to grab first ip address from a string I am trying to grab an ip address from a string and facing an issue.please help.
inet addr:11.11.11.11  Bcast:11.11.11.111  Mask:111.111.11.1.
This is the string I have and I need ip address next to addr:
I have tried the following code and failed to do in python:
ip = re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', line) and get index 0 item.
Result : This is actually giving me nothing in return

A: Your REGEX could be more specific, I think you could use something like :
addr:(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
In python:
match = re.match(r'addr:(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line)
You can then access the ip group by calling match.group('ip').

A: import re

line = "inet addr:11.11.11.11  Bcast:11.11.11.111  Mask:111.111.11.1"

pattern = r"[\d]{2}[.][\d]{2}[.][\d]{2}[.][\d]{2}[\D]"

re.findall(pattern, line)

['11.11.11.11 ']
re.findall(pattern, line)[0].strip()

'11.11.11.11'
if you have more than one element in the list just run a list-comp using .strip()
[i.strip() for i in re.findall(pattern, line)]

['11.11.11.11']
re.match() is not going to work because it will try to match your pattern starting at the beginning of the string (granted that your pattern does not include the "inet addr:" portion.
re.search() works but it misses recurring elements and only returns the first encounter of the pattern upon a successful match, in addition you'll have to use filter to extract the element.
finally, the key to solving this problem lies in the last character of your target, xx.xx.xx.xx[\D]. The [\D] directive ensures that the pattern looks for a no-integer at index 12, [\s] works equally well and it matches a space.


text:
Q: Total Momentum From a Standing Electromagnetic Wave How does one show the momentum imparted to a perfect conducting resonance cavity (boundary) of any shape by a classical standing electromagnetic wave inside is zero?
It should be by conservation of momentum. But I would like to see a detailed treatment argued specifically with the property of the electromagnetic wave, say with Poynting vector or electromagnetic stress-energy tensor.
Specifically, given the boundary condition of the perfect conductor cavity, how does one derive $\frac{\partial \int\mathbf S dV}{\partial t} = 0$ or $\frac{\partial \int \mathbf<S>dV}{\partial t} = 0$ where $\mathbf S$ is the Poynting vector, the integral is over the space of the cavity, $<\cdot>$ denotes time average.
One way of doing this could be to show the temporal spatial separated form of the Poynting vector $S(t,x)=S(x)e^{i\omega t}$ inside of the cavity. That is a Poynting vector of a standing wave. That form of $S(t,x)$ leads to its time average $<S>$ being zero.
I would also suppose the average pressure on the boundary within the scale of the wave length is constant. How would one argue or describe that?

A:
How does one show the momentum imparted to a perfect conducting resonance cavity (boundary) of any shape by a classical standing electromagnetic wave inside is zero?

For a standing EM wave in a cavity, the Poynting energy of the EM field inside is constant. This implies no energy is being transferred to the matter of the cavity from inside so the kinetic energy of the material cavity is constant in time. Therefore momentum of the material cavity is constant in time as well (if the cavity was changing its momentum during some time interval, it would be changing its kinetic energy too).
Of course, the walls of the cavity may experience pressure forces due to the EM forces (calculable with the Maxwell tensor), but if the cavity holds its shape so no work occurs, these forces cancel out and the cavity does not move.

Why is the Poynting energy of standing EM wave constant?

Let $d\boldsymbol \Sigma$ be outward area vector of an element of the inner boundary surface of the cavity. Net flux of Poynting vector
$$
\oint_\Sigma (\mathbf E\times\mathbf B)\cdot d\boldsymbol\Sigma
$$
over the inner boundary of the conductor $\Sigma$ is zero because $\mathbf E\times \mathbf B$ near the wall is parallel to the plane of the surface element nearby; it is perpendicular to $d\boldsymbol \Sigma$. That's because the electric field of a standing wave is perpendicular to the wall or vanishes.

Why is the electric field  perpendicular to the wall? Because the component of $\mathbf E$ parallel to the wall is continuous across the boundary and on the conductor side of it, this component vanishes.


text:
Q: Excel: Finding difference between 2 columns when rows are not matched Column A: 1000 unique names
Column B: A number corresponding with each name in A
Column C: Same 1000 names as A (different order than A, since values in D have changed)
Column D: A number for each name from C (numbers have changed from B)
At the moment, A/B and C/D are sorted from largest to smallest.
I want to create column E with the same 1000 names, but sorted by the difference between the values corresponding with each name from columns B and D. That Difference will be in column F.
Some values have changed a lot, so a name at the top of the column A may be way down the list in column C.
What is the easiest way to do this?
Thank you

A: column E:
(copy of column A)

column F:
=vlookup(E1,A:B,2,false)-vlookup(E1,C:D,2,false)

Then sort E:F on F.
Extra notes by fixer1234


text:
Q: how to handle INSERT on conflict in a has many association in GORM Create, ERROR (SQLSTATE 23505) I have two models as follows:
type OHLCV struct {
    gorm.Model
    Interval         string        `gorm:"uniqueIndex:idx_ohlcv"`
    Pair             string        `gorm:"uniqueIndex:idx_ohlcv"`
    OpenTime         time.Time     `gorm:"uniqueIndex:idx_ohlcv"`
    CloseTime        time.Time     `gorm:"uniqueIndex:idx_ohlcv"`
    Open             float64       `json:"open"`
    High             float64       `json:"high"`
    Low              float64       `json:"low"`
    Close            float64       `json:"close"`
    Volume           float64       `json:"volume"`
    QuoteAssetVolume float64       `json:"quoteAssetVolume"`
    NumberOfTrades   float64       `json:"numberOfTrades"`
    Calculations     []Calculation `gorm:"foreignKey:OhlcvRefer"`
}

and
type Calculation struct {
    gorm.Model
    OhlcvRefer uint   `gorm:"uniqueIndex:idx_calculation"`
    Key        string `gorm:"uniqueIndex:idx_calculation"`
    Config     string `gorm:"uniqueIndex:idx_calculation"`
    Value      float64
}

As you see both tables have unique indexes to prevent inserting duplicate data. The first table foreignKey is a part of the second table's unique index. The problem is how can I handle ON CONFLICT DO NOTHING behavior for both tables with a single GORM Create statement?
Before adding the Calculation association I was able handle CONFLICTS with
err = db.Clauses(clause.OnConflict{DoNothing: true,
        Columns: []clause.Column{{Name: "interval"}, {Name: "pair"}, {Name: "open_time"}, {Name: "close_time"}},
    }).Create(ohlcvs).Error

But now I get the following error:
ERROR: duplicate key value violates unique constraint "idx_calculation" (SQLSTATE 23505)
What I need is to DO NOTHING for the Calculation conflicts as well.

A: To achieve what you need, it should be enough to use the Unique index constraint on the two structs. Let's see how you can implement it.
package main

import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type User struct {
    Id    int
    Name  string `gorm:"uniqueIndex:idx_name"`
    Posts []Post
}

type Post struct {
    Id     int
    Title  string `gorm:"uniqueIndex:idx_title"`
    UserId int
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Post{})
    db.AutoMigrate(&User{})

    db.Create(&User{
        Name: "john doe",
        Posts: []Post{
            {Title: "first"},
            {Title: "second"}, // to generate an error change to "first"
        },
    })
}

In this way, if you're entering duplicates value the db itself will block you. This is valid ono either on the users table and on the posts one. IMO, it's a very clean approach and you can be as flexible as you wish.
Let me know if this solves your issue or there is something else!


text:
Q: groupby columns in awk Hello I'd like to convert a python script in awk, how to do a group by in columns from a data frame.
import pandas as pd
df = pd.read_csv("data.csv")
res0 = df.groupby("genes").agg({'start':'count'}).reset_index()
res0

How to do this using awk or sh?

A: Without more details it's difficult to help you; does this solve your problem?
Minimal reproducible example:
cat test.csv
genes,timepoint,value
P53,1,3.1
P53,2,3.2
P53,3,4.5
P53,4,5.1
P53,5,6.6
TRIM43,1,44
TRIM43,2,50
TRIM43,3,55
TRIM43,4,60
TRIM43,5,67
GAPDH,1,0.1
GAPDH,2,0.1
GAPDH,3,0.1
GAPDH,4,0.1
GAPDH,5,0.1

Run the python script
cat test.py
#!/usr/bin/env python3

import pandas as pd
df = pd.read_csv("test.csv")
res0 = df.groupby("genes").agg({'value':'count'}).reset_index()
print(res0)

./test.py
    genes  value
0   GAPDH      5
1     P53      5
2  TRIM43      5

Replicate it with awk
awk 'BEGIN{FS=","; OFS="\t"}
     NR==1 {print "genes","value"}
     NR>1 {genes[$1]++}
     END {for (i in genes)
              print i, genes[i]
     }' test.csv
genes   value
GAPDH   5
TRIM43  5
P53     5


text:
Q: Keras model.fit causes InvalidArgumentError when training on TPU When running the model.fit function an error is thrown. The main question is, what does this error mean? The code is run on a TPU V3-8 and uses Google cloud for data retrieval. I did try to look up the error on the web, however I could not find a single case of someone else getting this error.
model.fit(
    dataset,
    steps_per_epoch = N_IMGS // BATCH_SIZE,
    epochs = EPOCHS,
)

Throws the error
InvalidArgumentError: {{function_node __inference_train_function_528542}} Compilation failure: Depth of output must be a multiple of the number of groups: 3 vs 2
     [[{{node sequential/conv2d/Conv2D}}]]
    TPU compilation failed
     [[tpu_compile_succeeded_assert/_15965336225898828069/_5]]

The error message is not clear to me, what exactly is going wrong? The following model is used.
def get_model():
    # reset to free memory and training variables
    tf.keras.backend.clear_session()

    with strategy.scope():
        net = efn.EfficientNetB0(include_top=False, weights='noisy-student', input_shape=(HEIGHT, WIDTH, 3))

        model = tf.keras.Sequential([
            tf.keras.layers.Conv2D(3, (3, 3), padding='same', input_shape=(HEIGHT, WIDTH, 1)),
            net,
            tf.keras.layers.GlobalAveragePooling2D(),
            tf.keras.layers.Dropout(0.25),
            tf.keras.layers.Dense(N_LABELS, activation='softmax', dtype='float32'),
        ])

    model.compile(optimizer=tf.keras.optimizers.Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])

    return model

model = get_model()
tf.keras.utils.plot_model(model, 'model.png', show_shapes=True)

The dataset gives the following output
for images, labels in dataset.take(1): # only take first element of dataset
    print(f'images.shape: {images.shape}, images.dtype: {images.dtype}, labels.shape: {labels.shape}, labels.dtype: {labels.dtype}')

images.shape: (64, 224, 400, 1), images.dtype: <dtype: 'float32'>, labels.shape: (64,), labels.dtype: <dtype: 'int32'>


text:
Q: Rails HABTM or has_many? I have two models: Person, and Property.  In the Person model I have a field which stores the role of the person(tenant, owner, admin, contractor, etc).  Since each property will belong to an owner and potentially have one or more tenants, I thought this would be a good opportunity to use the HABTM model relation.
Do I have this right?
Also, how do I reference the attached model?  Assuming my join model is named PropertiesPeople, and I wanted to fetch the tenants for a particular property, would that be the following?
@property.people.where(:role => "tenant")

A: If the same Person can have more than one Property, you should can use HABTM. Something like this:
class Person < ActiveRecord::Base
  # in the people table you are storing the 'role' value
  has_and_belongs_to_many :properties, join_table: 'people_properties'
end

class Property < ActiveRecord::Base
  has_and_belongs_to_many :people, join_table: 'people_properties'
end

You should create the intermidiate table people_properties with the foreign keys, person_id and property_id.
The problem of this approach is that if a Person can be "tenant" in one property and "contractor" in another, for example, you can't store that information. In that case I will suggest using an intermidiate model, like this
class Person < ActiveRecord::Base
    has_many :property_people
    has_many :properties, through: :property_people
end

class PropertyPerson
    # now you store here the 'role' value
    belongs_to :person
    belongs_to :property
end

class Property < ActiveRecord::Base
    has_many :property_people
    has_many :people, through: :property_people
end

I don't know for sure if the class names are successfully inferred from the relationships names, in that case you can always indicate class_name or even the foreign_key for the associations. Also you can indicate the table for a model, using self.table_name=


text:
Q: Linq GroupBy throws an exception in .NET 6 I had the following query running successfully in old .NET framework 4.7.2 project, but the following query breaks in .NET 6 in migrated project
var query = from x in dbContext.table1
            join y in dbContext.table2
                   on x.AccountId equals y.AccountId
            join dbContext.v on x.RecId = v.RecId
            group new
                  {
                      x,
                      y.Name,
                      y.Email,
                      v.SecretKey
                  }
            by new
               {
                   x.CreatedDate,
                   y.Name
               }
            into grp
            orderby grp.Key.Name,
            select grp;

It throws this error:

OrderBy(grp => grp.Key.Name)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

And I can't use ToList() on just the join because on production there are millions of records in database which cannot be fetched each time in client side to apply group by operation.
How can I restructure the query to get it to work in .NET 6 ?
Note: the variable name taken as example as it is not possible to post company code here


text:
Q: Filepath of File Where SRO Method was Called I have a class:
Class General
{
    ...
}

And I am accessing a method, like this, from another file:
General::the_method($params);

Is there a way to determine, from WITHIN the class, the filepath of WHERE the method was called? Not the filepath of the General class, but of the separate function, prbably many folders away, that has called the method?
I've tried ReflectionClass::getFileName(), however it seems this only works on fully instantiated objects (ie, if I'd done $general = new General, which I don't want to do). I figured it wouldn't work given the description of the functionality but I thought I'd give it a try. No dice, sadly.
So: is this possible?
EDIT: We are trying to accomplish this WITHOUT a second parameter passed to the function.


text:
Q: Angular2 ActivatedRoute parameter is undefined Am trying to display the value of activate route param in the screen but fails
In the first component i have
<ul *ngFor="let cate of categories;">
  <li (click)="onviewChecklists(cate.id)">
     <a> {{i+1}} {{cate.category}} </a>
  </li>

</ul>

  onviewChecklists(category:string){
     this._router.navigate(["tsafety/checklist-management/categories/items",
       {category:category}])
 }

Now on the second component to where am naviagting i have
category:any;

constructor(
private _router:Router,private activeRoute:ActivatedRoute
 ) {

 }

ngOnInit() {

   this.category = this.activeRoute.snapshot.params['category'];
   console.log(this.category);  //this works
}
//on this component html {{category}} returns only the first param

In the second component html file when i {{category}} it onl displays the value of the first routing that is
navigate 1 param is checklist display is checklist
navigate 2 param is newcheck  display is checklist

What could be wrong since the console.log() prints the correct value but {{category}} only prints the first value
In the second component ive aso tried
ngOnInit() {
 this.onGetItems(+this.activeRoute.snapshot.params['category']);

 }

 onGetItems(category){
    return this._checklistitemsService.getAllItems(category)
    .subscribe(
       res=>{
         this.checklistitems = res
    }
  )

The onGetItems method is called only once

A: When ever you are passing a route parameter, and raise a service call using that parameter, you should use an Observable<params> to subscribe to the activated route in your constructor as below
category: number = 0;
constructor(private route:ActivatedRoute,
            private checklistitemsService: CheckListItemsService) {

    this.sub = this.route.params.subscribe(params => {

            this.category = + params['category'];
              ......

    });
}

Then your service call should be made in the ngOnInit()
ngOnInit(){
      this._checklistitemsService.getAllItems(category)
          .subscribe(res => {
                          this.checklistitems = res
           }
}

Mistake:
If you are retrieving the route params in ngOnInit, your components will be loaded before the route value is fetched, so you will find explicit delay and so your this.checklistitems remains without value.
My solution:
By retrieving the route parameters, in the constructor, ngOnInit will not execute until the route parameter is retrieved and there by making a service call to get this.checklistitems. Now your component loads correctly.


text:
Q: Pesquisa sql com data limite maior e menor Meu código deve retornar valores do banco de dados, relacionados ao dia atual (hoje), mas somente relacionados ao mês e dia, pesquisei muito mas não consegui encontrar algo que me ajudasse
$data_atual = date("d-m");
$mostraDados = mysqli_query($conecta,  "SELECT * FROM sql WHERE ativo = 's' AND inicio >= '".$data_atual."'")or die (mysqli_error());

na coluna inicio da tabela fica a data, como por exemplo 13-10, então a linha de consulta deveria retornar tudo acima do dia 13 do mês 10, mas esta dando erro. No caso, a variável $data_atual pega o dia e mês do server para fazer a consulta e verificar com a coluna inicio.

A: Você vai ter que usar função DATE() para converter as duas datas para o formato "aaaa-mm-dd" e compará-las. Então pra obter todos os registros da data de hoje, você teria a seguinte query:
SELECT * FROM sql WHERE ativo = 's' AND DATE(inicio) >= DATE(NOW())


text:
Q: IBM WebSphere 7 JNDI Configuration - java.lang.NullPointerException error
Trying to create JNDI connection with MS SQL Server 2008 in IBM Websphere 7 using "sqljdbc4.jar" but I'm getting this following java.lang.NullPointerException error when I click on finish.
DSRA3601E:createDatasource command failed for the following reason: java.lang.NullPointerException.


text:
Q: Display different data in tableView according to which button clicked I have a tableview on the bottom of a view controller. I am trying to display different things on the tableview depending on which button was clicked. I have my different prototype cells and configuration methods for their data set up, however I cannot get the last bit. Here is my code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = Int ()
    if podsButton.isSelected {
        count = pods.count
    } else if subscribedButton.isSelected {
        count = subscribers.count
    } else if subscribersButton.isSelected {
        count = subscribed.count
    }
    return count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell ()
    if podsButton.isSelected{
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell") as? ProfileTableViewCell else {
            return UITableViewCell() }
        let pod = pods[indexPath.row]
        cell.configureCell(pod: pod)
    } else if subscribedButton.isSelected {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "FollowingCell") as? FollowingTableViewCell else {
            return UITableViewCell() }
        let user = subscribed[indexPath.row]
        cell.configureCell(user: user)
    }
    return cell
}

Right now the tableview displays nothing. The cell I am returning in cellForRow, is only the variable and not one of the conditional options that gets dequeued right? This is my issue. Also the first option (ProfileCell) should be the default. Thank you for any help.
UPDATE:
Now using my enum my code looks like this :
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count = 0
    if case .pods = displayState {
        count = pods.count
    } else if case .subscribed = displayState{
        count = subscribers.count
    } else if case .subscribers = displayState {
        count = subscribed.count
    }
    return count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if case .pods = displayState{
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell") as! ProfileTableViewCell
        let pod = pods[indexPath.row]
        cell.configureCell(pod: pod)
        return cell
    } else if case .subscribed = displayState {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FollowingCell") as! FollowingTableViewCell
        let user = subscribed[indexPath.row]
        cell.configureCell(user: user)
        return cell
    } else if case .subscribers = displayState {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FollowingCell") as! FollowingTableViewCell
        let user = subscribers[indexPath.row]
        cell.configureCell(user: user)
        return cell
    } else {
        return UITableViewCell()
    }
}

I am setting the displayStates in the button actions like so:
@IBAction func podsButtonClicked(_ sender: BottomBorderButton) {
    displayState = .pods
    podsButton.addBottomBorderWithColor(color: greenColor(), width: 3)
    subscribedButton.removeBottomBorder()
    subscribersButton.removeBottomBorder()
    self.tableview.reloadData()
}

I think this is working , but I am now having a Parse query issue:
    // Query for the users that the user is subscribed to
    let subscribedQuery = Following.query()
    subscribedQuery?.whereKey("follower", equalTo: PFUser.current()?.objectId as Any)
    subscribedQuery?.findObjectsInBackground(block: { (objects, error) in
        if let objects = objects {
            for object in objects {
                self.subscribed.insert(object as! PFUser, at: 0)
            }
        }
    })

Error:

Could not cast value of type 'Speakable.Following' (0x100552ec0) to 'PFUser' (0x100a12808).

UPDATE***
Fixed this with an includeKey but am now getting
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This query has an outstanding network connection. You have to wait until it's done.'

A: There's a lot you should change in your code.
Make sure you select some initial button in viewDidLoad. Make sure you call reloadData in your button actions.
And you should refactor your cellForRowAt properly. In your current code, the cell variable of the guard is different from the cell variable before the first if so you actually always return the empty UITableViewCell instance you needlessly create.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if podsButton.isSelected{
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell") as! ProfileTableViewCell
        let pod = pods[indexPath.row]
        cell.configureCell(pod: pod)

        return cell
    } else if subscribedButton.isSelected {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FollowingCell") as! FollowingTableViewCell
        let user = subscribed[indexPath.row]
        cell.configureCell(user: user)
        return cell
    } else if subscribersButton.isSelected {
        // similar code to create and return cell
    } else {
        fatalError("Unexpected - no button selected") // Fix your code
        return UITableViewCell()
    }
}

This is a good and proper use of force-casting. There is no need for the guard statements. You want this code to crash during development if your cells are not setup correctly. Once setup properly, it can't be wrong at runtime.
Also, the first line of your numberOfRowsInSection should be:
var count = 0


text:
Q: Ошибка версии ChromeDriver Если после установки хромдрайвера ловите:
version of ChromeDriver only supports Chrome version 84","stacktrace":"#0 '
     '0x5596f6ff3ea

A: https://chromedriver.storage.googleapis.com/index.html
Найти версию драйвера равную вашей версии браузера
$ cd /opt && sudo mkdir webdriver && cd webdriver
$ sudo wget https://chromedriver.storage.googleapis.com/ВЕРСИЯ/chromedriver_linux64.zip

где ВЕРСИЯ - версия нужного вебдрайвера, например, 87.0.4280.88 (https://chromedriver.chromium.org/downloads)
$ sudo unzip chromedriver_linux64.zip && sudo chmod 755 chromedriver && sudo rm chromedriver_linux64.zip

$ sudo ln -s /opt/webdriver/chromedriver /usr/bin/chromedriver

обновите его и перенесите сюда:
$ sudo ln -s /opt/webdriver/chromedriver /usr/local/bin/chromedriver

Если есть проблемы ChromeDriver - напишите ниже. Пригодится.


text:
Q: returning a new array of rankings based on initial array I'm new to javascript and am trying to create a function that accepts an array of any length, and creates a new array with the rankings from that array (ie [10, 5, 20] would output [2, 3, 1]. This is my code so far ( i originally tried with a larger series of for loops finding the max each time but ran into issues getting them to repeat the same number of times as there are numbers in the array, so I switched to a sort method. Let me know if anyone can help point me in the right direction, thank you!!
function rankings(array){
  let finalArray = [];
 for (i = 0; i < array.length; i++) {//set up final array
  finalArray[i] = array[i];
   }
  for(let list of array){
    array.sort((a,b)=>b-a)//array sorted in order
    }
    for (i = array.length-1; i>=0; i--){

    }
  return finalArray;
}

A: Sort a clone (via spread) of the array, according to your ranking logic (descending in this case). Use Array.map() to create tuples of [value, index + 1], and generate a Map from the tuples.
Use Array.map() on the original array, and return the respective ranks from the Map:

function rankings(array) {
  const ranks = new Map([...array].sort((a, b) => b - a)
    .map((v, i) => [v, i + 1]))

  return array.map(v => ranks.get(v));
}

const result = rankings([10, 5, 20]);

console.log(result);

To ignore repeat values, create a Set from the original array before spreading it:

function rankings(array) {
  const ranks = new Map([...new Set(array)].sort((a, b) => b - a)
    .map((v, i) => [v, i + 1]))

  return array.map(v => ranks.get(v));
}

const result = rankings([10, 5, 20, 5]);

console.log(result);

A: If you like to get same ranks fro same values, cou could take the stored value for mapping.

const
    rankings = array => array.map(
        Map.prototype.get,
        [...array]
            .sort((a, b) => b - a)
            .reduce((i => (m, v) => m.set(v, m.get(v) || i++))(1), new Map)
    );

const result = rankings([10, 5, 20, 5]);

console.log(result);

A: You can give this a try:

var data = [10, 5, 20, 5, 4, 25];
var sorted = [...new Set([...data].sort((a,b)=>b-a))] // sorting and filtering the data
var result = data.map(elem=> getIndex = sorted.findIndex(v=>v==elem)+1);
console.log(result);


text:
Q: Create folders when creating a new WPF project I would like to find a way to create four folders when I create a new WPF app/lib. Those four folders would be DAO, Model, ViewModel and View.
Is there a way to do this automatically?
Thanks

A: Solution is described here (http://msdn.microsoft.com/en-us/library/xkh1wxd8.aspx). Creating project templates is standart VS functionality since VS2005


text:
Q: Remove inline styles from text I'm using Trumbowyg which is a javascript text editor. My problem is, when I paste text from another site into the editor, it adopts the style of the text from that site. How can I prevent this?
My editor is rendered in my Django template like this:
{{ post.content }}

Is there a template tag I can use to remove HTML? Because the external styling is inline styles, e.g. <span style='font-family: Arial;font-size:30px' etc..?

A: To remove styles from a formatted paste (styles pasted from clipboard) in Trumbowyg, set the removeformatPasted option to true:
$('.trumbowyg').trumbowyg({
  removeformatPasted: true
});

But also keep in mind:

*

*In order to use this option, you need to define a font size in your CSS or use a reset like normalize.

*Remove format pasted is not active by default (set to false).

A: You want to remove HTML tags? If yes just use:
{{ post.content|striptags }}


text:
Q: Is there a command block command, or something to do with redstone that activates randomly? i'm trying to create a redstone game that a has component that has to be random, and i was wondering, if there is a command block command, that when the command block is activated, has a 50% chance of creating a temporary redstone charge? If not, then is there a way to do it with redstone?
I tried making it so it is the same every time, but that would get boring.
Any help would be appreciated.
i'm using 1.13

A: Place an impulse command block and 2 armor stands on top of it. Tag one of the armor stands with some tag.
Use this command in the command block, you can use any other tag, too, but it has to be the same as one of your armor stands. I used the tag win:
/execute as @e[type=minecraft:armor_stand,sort=random,limit=1,distance=..1] if entity @s[tag=win]

The command will randomly select one of the two armor stands and execute as that armor stand. It then tests if it has the win tag.
Use a comparator to get your redstone signal. You can have an observer obeserve the comparator if you want redstone pulses instead.
You can easily vary the chance of winning by using more armor stands, for a 60% chance of winning you could use 5 armor stands and tag 3 of them.


text:
Q: Wired connection problem Ubuntu 14.04 LTS I recently added a partition to my computer with Ubuntu 14.04 LTS 64-bit.
It is Turbo-X dual-boot with Windows 7. The Ethernet works good in Windows but in
Ubuntu does not work.
The wired connection is trying to connect to the switch all the time but it does not connect.
george@myia:~$ ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:90:f5:8c:2e:04
          inet6 addr: fe80::290:f5ff:fe8c:2e04/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:72 errors:0 dropped:0 overruns:0 frame:0
          TX packets:310 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4920 (4.9 KB)  TX bytes:56934 (56.9 KB)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:410 errors:0 dropped:0 overruns:0 frame:0
          TX packets:410 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:33513 (33.5 KB)  TX bytes:33513 (33.5 KB)

wlan0     Link encap:Ethernet  HWaddr 00:1d:e0:84:b6:39
          inet addr:192.168.0.102  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::21d:e0ff:fe84:b639/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:254 errors:0 dropped:0 overruns:0 frame:0
          TX packets:318 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:45164 (45.1 KB)  TX bytes:38175 (38.1 KB)

george@myia:~$ nm-tool

NetworkManager Tool

State: connected (global)

- Device: eth0 -----------------------------------------------------------------
  Type:              Wired
  Driver:            r8169
  State:             disconnected
  Default:           no
  HW Address:        00:90:F5:8C:2E:04

  Capabilities:
    Carrier Detect:  yes
    Speed:           1000 Mb/s

  Wired Properties
    Carrier:         on

- Device: wlan0  [MF60_B6EF5F] -------------------------------------------------
  Type:              802.11 WiFi
  Driver:            iwl4965
  State:             connected
  Default:           yes
  HW Address:        00:1D:E0:84:B6:39

  Capabilities:
    Speed:           54 Mb/s

  Wireless Properties
    WEP Encryption:  yes
    WPA Encryption:  yes
    WPA2 Encryption: yes

  Wireless Access Points (* = current AP)
    *MF60_B6EF5F:    Infra, 78:E8:B6:B6:EF:5F, Freq 2437 MHz, Rate 54 Mb/s, Strength 79 WPA

  IPv4 Settings:
    Address:         192.168.0.102
    Prefix:          24 (255.255.255.0)
    Gateway:         192.168.0.1

    DNS:             192.168.0.1

george@myia:~$ lspci -nn | grep Ethernet
07:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 02)

A: sudo dhclient -r and sudo dhclient eth0

A: I had this very same issue.
Went into my bios and turned on the IOMMU option for my motherboard.
After that, Ubuntu saw the ethernet and worked properly.


text:
Q: When can $ x = \bigcup \mathscr{P}(x)$ become $ x = \mathscr{P}(\bigcup x)$ When can $ x = \bigcup \mathscr{P}(x)$ become $ x = \mathscr{P}(\bigcup x)$ where $\mathscr{P}$ is the power set? I know the first is true by checking $\subseteq $ and $\supseteq$, however I'm not quite sure when the second part is true?
Can anyone give any examples

A: Thanks for Sassatelli Giulio for giving some guidance.
Suppose there is some $y$ such that $x= \mathscr{P} \left(y\right)$, then, using the $x= \bigcup \mathscr {P} \left(x\right) $ equality, $$\bigcup x= \bigcup \mathscr{P} \left(y\right) = y$$
Therefore, $x= \mathscr{P} \left(\bigcup x\right)$.
Suppose $x= \mathscr{P} \left(\bigcup x\right)$, take $y=\bigcup x$. So there is one $y$ with $x = \mathscr{P} \left(y\right)$.
Therefore, $x= \mathscr{P} \left(\bigcup x\right)$ if and only if there is some $y$ such that $x = \mathscr{P} \left(y\right)$.
Some examples:
$$\{ \emptyset \} = \mathscr{P} \left(\emptyset\right) = \mathscr{P} \left(\bigcup \{ \emptyset \}\right) $$
$$\{\emptyset, \{ \emptyset \} \} = \mathscr {P} \left(\{\emptyset \}\right) = \mathscr {P} \left(\bigcup \{\emptyset, \{\emptyset \} \}\right) $$


text:
Q: How is malice different from aggression? I am having trouble understanding exactly what malice is and how it is different from aggression? In social psychology, aggression (which is contrasted with accidental harm) is defined as intentional act to cause harm, whether it is as means to an achieve some other goal (instrumental aggression) or as an end in itself (hostile/impulse aggression). On the other hand, malice is also defined as intentional or purposeful desire to do harm. So keeping this in mind, would it be appropriate to think that every act of aggression, whether instrumental or impulse, is essentially malicious?

A: From Lexico:

malice: The intention or desire to do evil; ill will.
aggression: Hostile or violent behavior or attitudes toward another; readiness to attack or confront.

You should probably consult a lawyer, :-) but malice involves intent or desire, whereas aggression goes beyond malice into the realm of action or readiness for action.
In a way, you answered your own question by characterizing, in social psychological terms, aggression as an act and malice as a desire.
Addendum: Given the definitions of aggression and malice you provided, you asked if it would be appropriate to think that every act of aggression, whether instrumental or impulse, is essentially malicious? I would say no. Take corporal punishment, for example, which could involve an intentional act to cause harm with no intentional or purposeful desire to do harm. As many an "old-school" parent has said, "This will hurt me a lot more than it hurts you."


text:
Q: Reading JSON data into an array/list with Jackson I have seen and read several questions on this subject, but none seem to address my problem.  In all likelihood, I am making one (or two) minor but critical mistakes, but I don't see them.
My JSON looks like this (the real example is much more complex but this is what I have whittled it down to):
[
  {
    "atcID": "AL011851"
  },
  {
   "atcID": "AL021851"
  }
]

The code I used to read it is:
StormData.java:
public class StormData {

@JsonCreator
StormData ( String atcID, String name ) {
    this.atcID = atcID;
    this.name = name;
};

public String getAtcID()    {
    return atcID;
}

public void setAtcID( String atcID )    {
    this.atcID = atcID;
}

String      atcID;
String      name;

}

Main file:
byte[] jsonData = Files.readAllBytes(Paths.get(fileName));

ObjectMapper objectMapper = new ObjectMapper();

List<StormData> myObjects = objectMapper.readValue(jsonData , new TypeReference<List<StormData>>(){});

But the error I get is:
Cannot construct instance of `StormData` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

So what am I missing?  TIA.

A: You need to use both annotations: @JsonCreator on constructor and @JsonProperty on each argument:
@JsonCreator
StormData (@JsonProperty("atcID") String atcID, @JsonProperty("name") String name) {
    this.atcID = atcID;
    this.name = name;
}

See the official documentation.
Since JDK 8 you can also register Jackson ParameterNamesModule and compile your code with -parameters option.
See the details in the documentation.


text:
Q: Apache server being shutdown after a few minutes on OS X 10.10 I'm trying to run a PHP application in my intranet using Apache on OS X 10.10. I can successfully launch Apache using:
sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist

The PHP app works correctly and can be accessed from other machines. However, apache is being shit down after a few minutes with no helpful error messages in the /var/log/apache2/error_log
[Sat Jan 02 22:21:38.685725 2016] [mpm_prefork:notice] [pid 112] AH00163: Apache/2.4.16 (Unix) PHP/5.5.29 configured -- resuming normal operation
[Sat Jan 02 22:21:38.685807 2016] [mpm_prefork:info] [pid 112] AH00164: Server built: Jul 22 2015 21:03:09
[Sat Jan 02 22:21:38.685828 2016] [core:notice] [pid 112] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Sat Jan 02 22:21:38.685839 2016] [mpm_prefork:debug] [pid 112] prefork.c(992): AH00165: Accept mutex: flock (default: flock) [Sat Jan 02 22:21:40.000785 2016] [core:info] [pid 112] AH00096: removed PID file /private/var/run/httpd.pid (pid=112)
[Sat Jan 02 22:21:40.000820 2016] [mpm_prefork:notice] [pid 112] AH00169: caught SIGTERM, shutting down
[Sun Jan 03 07:49:55.202584 2016] [mpm_prefork:notice] [pid 6104] AH00163: Apache/2.4.16 (Unix) PHP/5.5.29 configured -- resuming normal operation
[Sun Jan 03 07:49:55.202661 2016] [core:notice] [pid 6104] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Sun Jan 03 08:16:48.067316 2016] [mpm_prefork:notice] [pid 6104] AH00169: caught SIGTERM, shutting down
[Sun Jan 03 08:59:41.027663 2016] [mpm_prefork:notice] [pid 50443] AH00163: Apache/2.4.16 (Unix) PHP/5.5.29 configured -- resuming normal operations
[Sun Jan 03 08:59:41.027735 2016] [core:notice] [pid 50443] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Sun Jan 03 09:18:07.822248 2016] [mpm_prefork:notice] [pid 50443] AH00169: caught SIGTERM, shutting down

My org.apache.httpd.plist is as follws:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabled</key>
        <false/>
        <key>EnvironmentVariables</key>
        <dict>
                <key>XPC_SERVICES_UNAVAILABLE</key>
                <string>1</string>
                <key>PATH</key>
                <string>/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        </dict>
        <key>Label</key>
        <string>org.apache.httpd</string>
        <key>KeepAlive</key>
        <true/>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/sbin/httpd-wrapper</string>
                <string>-D</string>
                <string>FOREGROUND</string>
        </array>
</dict>
</plist>

There is no php_error log in /var/log/apache2 .
Related to this problem might be this issue I have where Apache is shutdown after 2 seconds on reboot: https://stackoverflow.com/questions/34571520/apache-wont-start-on-boot-on-os-x-10-10


text:
Q: jQuery : Chrome textareas and resize event Chrome makes textareas resizable by default. How can I attach events to the resizing events for the textareas ? Doing the naive $('textarea').resize(function(){...}) does nothing.

A: It doesn't look like you can specifically attach events to resizing a textarea. The resize event fires when the window is resized.

A: I can't test this right now, but according to this forum entry it can be disabled using:
style="resize: none;"

unlike stated in that entry, max-width and max-height won't cut it - thanks to @Jonathan Sampson for the info.

A: Here's a jQuery plugin written using CoffeeScript. Idea from Jonathan Sampson.
$.fn.sizeId = ->
    return this.height() + "" + this.width()

$.fn.textAreaResized = (callback) ->
    this.each ->
        that = $ this
        last = that.sizeId()
        that.mousedown ->
            last = that.sizeId()
        that.mousemove ->
            callback(that.get(0)) if last isnt that.sizeId()

You can build it to Javascript on the CoffeeScript's homepage
http://jashkenas.github.com/coffee-script/
Use the "Try CoffeeScript" button.

A: This is an old question, but someone else had the same one in IRC, so I decided to solve it here: http://jsfiddle.net/vol7ron/Z7HDn/
Everyone's right that Chrome doesn't capture the resize event and that Chrome doesn't capture the mousedown, so you need to set the init state and then handle changes through mouseup:
jQuery(document).ready(function(){
   // set init (default) state
   var $test = jQuery('#test');

   $test.data('w', $test.outerWidth());
   $test.data('h', $test.outerHeight());

   $test.mouseup(function(){
      var $this = jQuery(this);
      if (  $this.outerWidth()  != $this.data('w')
         || $this.outerHeight() != $this.data('h')
         )
         alert( $this.outerWidth()  + ' - ' + $this.data('w') + '\n'
              + $this.outerHeight() + ' - ' + $this.data('h'));

      // set new height/width
      $this.data('w', $this.outerWidth());
      $this.data('h', $this.outerHeight());
   });

});

HTML
<textarea id="test"></textarea>

A: There is jquery-resize which once included just makes your given line work:
http://benalman.com/projects/jquery-resize-plugin/

A: Similar to Epeli's answer I've tried to start on a clean solution to trigger a resize() event on mousedown: http://jsfiddle.net/cburgmer/jv5Yj/3/
However it only works with Firefox as Chrome doesn't seem to trigger mousedown on the resize handler. However it does trigger mouseup.


text:
Q: Localisation of sharepoint server For legal reasons, I would like to know if cloud document servers are in Quebec. if not, are they in Canada?

A: Office 365 is now Multie-Geo Location supported. Yes it has the dataCenter in the canada. you can check it here.
Here are the list of all available data centers:  Australia, Asia Pacific, **Canada**, European Union, France, India, Japan, Korea, United Kingdom, and United States.
Note: Multi-Geo is currently available to customers with a minimum of 5,000 Office 365 services subscriptions. Contact your Microsoft representative for details.

A: Are you the Tenant / Global admin? If so, go to the https://admin.microsoft.com/ site, click Settings and the Organization Profile. Scroll down and find:

Or in the portal click Support and make a Service Request to ask for the exact location.


text:
Q: Difference between .space and .word directives I am just starting to learn assembly code for ARM-family processors in class. I know that the .word directive declares a variable of one word size and that the .space directory skips over a certain number of bytes. So my question is, how would the following two differ? (Assuming a word size of 32 bits)
foo: .word 0

vs.
bar: .space 4

Also, (a somewhat tangential question but) is there any way to declare uninitialized variables in assembly? It seems to me you always have to assign an initial value.
Thanks in advance!

A: .space means that advances the location counter by the number of bytes specified by the value of expression. The assembler fills the space with zeros.
.word means
Truncates the values of the expressions specified in the comma-separated list to 16-bit values, and assembles the values in successive locations. The values of the expressions must be absolute.
The operands for the .word directive can optionally have the following form:
The expressionVal is a 16-bit value.
The optional expressionRep is a non-negative expression that specifies how many times to replicate the value of expressionVal.
The expression value (expressionVal) and repetition count (expressionRep) must be absolute.
The .word directive automatically aligns its data and preceding labels on a word boundary. You can disable this feature with the .align 0 directive.


text:
Q: What is the performace of PHPs strtotime()? I am doing some large timestamp-list iterations: Putting them in tables with date-ranges, and grouping them by ranges.
In order to do that, I found strtotime() a very helpfull function, but I am worried about its performance.
For example, a function that loops over a list of weeks (say, week 49 to 05) and has to decide the beginning of the week and the timestamp at the end of that week. A usefull way to do that, would be:
foreach ($this->weeks($first, $amount) as $starts_at) {
  $ends_at = strtotime('+1 week', $starts_at);
  $groups[$week_key] = $this->slice($timestamps, $starts_at, $ends_at);
}

//$this->weeks returns a list of timestamps at which each week starts.
//$this->slice is a simple helper that returns only the timestamps within a range, from a list of timestamps.

Instead of strtotime(), I could, potentially, find out the amount of seconds between begin and end of the week, 99% of the times that would be 24 * 60 * 60 * 7. But in these rare cases where there is a DST-switch, that 24 should either be 23 or 25. Code to sort that out, will probably be a lot slower then strtotime(), not?
I use the same patterns for ranges of years, months (months, being very inconsistent!), days and hours. Only with hours would I suspect simply adding 3600 to the timestamp is faster.
Any other gotcha's? Are there ways (that do not depend on PHP5.3!) that offer better routes for consistent, DST and leap-year safe dateranges?

A: Why are you worried about its performance? Do you have evidence that it's slowing down your system? If not, don't try to over-complicate the solution for unnecessary reasons. Remember that premature optimization is the root of all evil. Write readable code that makes sense, and only optimize if you KNOW it's going to be an issue...
But something else to consider is that it's also compiled C code, so it should be quite efficient for what it does. You MIGHT be able to build a sub-set of the code in PHP land and make it faster, but it's going to be a difficult job (due to all the overhead involved in PHP code).
Like I said before, use it until you prove it's a problem, then fix that problem. Don't forget re-writing it for you needs isn't free either. It takes time and introduces bugs. Is it worth it if the gain is minimal (meaning it wasn't a performance problem to begin with). So don't bother trying to micro-optimize unless you KNOW it's a problem...

A: I know this probably isn't the answer you're looking for, but your best bet is profiling it with a real use case in mind.
My instinct is that, as you think, strtotime will be slower. But even if it's, say, 3 times slower, this is only meaningful in context. Maybe your routine, with real data, takes 60 ms using strtotime, so in most cases, you'd be just saving 40 ms (I totally made up these numbers, but you get the idea). So, you might find out that optimising this wouldn't really pay off (considering you're opening your code to more potential bugs and you'll have to invest more time to get it right).
By the way, if you have good profiling tools, awesome, but even if you don't comparing timestamps should give you a rough idea.

A: To respond to the question, finaly :
Based on many benchmarks like this one: https://en.code-bude.net/2013/12/19/benchmark-strtotime-vs-datetime-vs-gettimestamp-in-php/
We can see that strtotime() is more effective that we can think.
So yes, to convert a string to a timestamp, the strtotime function has pretty good performance.

A: Very interesting question. I'd say that the only way you can really figure this out, is to set up your own performance test. Observe the value of microtime() at the beginning and end of the script, to determine performance. Run a ridiculous number of values through a loop with one method, then the other method. Compare times.


text:
Q: webkit property not working in blackberry 6 I tried the following code to give gradient property  (through webkit) to button in my mobile webpage.
Gradient works fine in Iphone & Android, but it is not working in Blackberry 6.0 native browser.
<style>
.btnclass
{
height:70px;
width:300px;
background-image: -webkit-linear-gradient(bottom, #B56D73 20%, #CFDC8E 60%, #F9FFAB 80%);
background-image:linear-gradient(bottom, #B56D73 20%, #CFDC8E 60%, #F9FFAB 80%);
}
</style>

<body>
<form><input type="button" class="btnclass"></form>
</body>

A: Check this page, CSS Gradients in Blackberry is only available from the version 7. If you want to mimic the same behaviour you will need to have an image with the gradient and apply it in this case (you can use Modernizr to detect CSS Gradients).


text:
Q: For two data sets with different means but the same standard deviations, would the SD for the data set with a higher mean indicate lower spread? I understand the actual math, but I don't understand how it makes sense.
For example, if I were working with two data sets (ex. below) and one had higher values than the other but the sizes of the standard deviation were similar would I conclude that the level of spread is more acceptable for the data set with the higher mean.
Typically, I would think no, but the coefficient of variation makes me confused.
For ex. assume for data set 1, the mean is 200 and the SD is 50. Now for data set 2 assume the mean is 500 and the SD is 50. Wouldn't the second data set result in a lower CV, meaning the data is less spread around the mean?


text:
Q: RSpec unit testing parameters I have the following code:
RSpec.describe OtsState do

  let(:campaign) { build(:campaign, from: Time.now+1.weeks, to: Time.now+2.weeks) }

  subject { campaign.deployment.ots_state }
  before { campaign.deployment.build_ots_state }

  describe "#set_target" do

    def check_ots_target(target,expected)
      ots_state = subject
      ots_state.set_target(target)

      expect(ots_state.ots_target).to eq(expected)
    end

    it 'should set target to 5 when 1 week period and set target to 5' do
      check_ots_target(5,5)
    end

    it 'should set target to 2 when 2 week period and set target to 1' do
      campaign.set(to: campaign.from+2.weeks)
      check_ots_target(1,2)
    end

    it 'should set target to 1 when 1 day period and set target to 7' do
      campaign.set(to: campaign.from+1.days)
      check_ots_target(7,1)
    end
  end

end

is there a way in RSpec to write it as a single test with 3 parameter sets?

A: You could use RSpec matchers with a fluent interface:
RSpec::Matchers.define :have_ots_target do |expected|
  match do |ots_state|
    ots_state.ots_target == expected
  end

  description do
    "have ots_target #{expected} when period is #{@period.inspect} and target is #{@target}"
  end

  chain :when_period_is do |period|
    @period = period
  end

  chain :and_target_is do |target|
    @target = target
  end
end

which allows something like this:
describe do
  let(:period) { 1.weeks }
  let(:target) { 5 }
  it { is_expected.to have_ots_target(5).when_period_is(period).and_target_is(target) }
end

but I prefer to just repeat the example and change the inputs:
describe "#set_target" do
  describe "when period is 2 weeks" do
    let(:period) { 2.weeks }
    describe "and target is 1" do
      it "returns 2" do
        expect(subject.set_target(1).to eq 2
       end
    end
  end
end

which is easier to write and easier to read.


text:
Q: How to make wx wizard respond to keyboard accelerators like a normal Microsoft Windows application The wizard in wxpython automatically responds to keyboard accelerators for the buttons on the page (for example "Alt-N" to activate the next button). I want this but ...
It only does this if there is at least one interactive widget on the visible wizard page. If the page only has static text then accelerator keystrokes don't do anything.
The wizard also responds to keys that shouldn't do anything at all, eg "C" or "c" activates the cancel button whenever the focus is on an image button (note that it doesn't do that if the focus is on a text entry widget - in that case the corresponding character is entered into the text box).
How can I change the behaviour of the wxpython wizard so that:

*

*"Alt-N" and "Alt-C" should activate the next and cancel buttons even on pages that only have static text controls

*"N" and "C" should NOT activate the next and cancel buttons regardless of which widget has the current focus.

A: The problem with Alt-N not having any effect seems to be a wxWidgets bug, so I don't think you can work around it in wxPython. Perhaps you could try to catch EVT_CHAR for them in the wizard itself and see if you get the event there.
As for disabling some keys when some specific control has focus, you definitely should be able to catch EVT_KEY_DOWN in this control. Although I don't really understand why would you want to do this.