text:
Q: Can't get a proper image source with laravel-mix + vueJS I'm using laravel-mix withe vueJS and I'm having issue on how to properly set-up the image directory.
Here's my initial mix set-up
mix
  .js("resources/js/app.js", "public/js")
  .sass("resources/sass/app.scss", "public/css")
  .copy("resources/assets", "public/images/" );

as you can see, I'm copying all the content of resources/assets folder to public/images/ folder
so this image assets/svg/logo-white.svg will be on images/svg/logo-white.svg
Now here's where I'm lost.
//using this
src="/assets/svg/logo-white.svg"
//result is obviously same (wrong url)
src="/assets/svg/logo-white.svg"

//using this
src="@/assets/svg/logo-white.svg"
// the result is (wrong url it lacks svg folder)
src="/images/logo-white.svg?c381d0781c93aa7ea138a64f7ea3f17d"

//using this
:src="'@/assets/svg/logo-white.svg'"
//result (another wrong)
src="@/assets/svg/logo-white.svg"

if I add .setResourceRoot("") to my mix config
//using this
src="@/assets/svg/logo-white.svg"
//results to this,
src="http://localhost:8080/images/logo-white.svg?c381d0781c93aa7ea138a64f7ea3f17d"
//which supposedly a wrong URL but its weirdly working
//I have no idea why its showing the images when the image is on /images/svg/ folder not in /images/

So as you can see, using src="@/assets/blabla.jpg" only work if all my images are inside the root of images folder, but doesn't work inside child folder of the images folder.
and adding .setResourceRoot("") works in a mysterious way which I dont really want to gamble as I'm not sure what will happen with this on production
would appreciate any help on this and clarification on how I can properly get the image url and why its behaving this way


text:
Q: Stop Browser at any spot I have checked many questions and answers regarding how to stop any browser at any time, but I have not found a solution to my problem.
I have a logout button in my application, and when I press it, it adds some classes to an <a> tag. Is there any key/shortcut to stop the Mozilla/Chrome (any browser) to perform the actions or stay the same page?

A: What I believe you're looking for is a debugger with breakpoints.  Breakpoints allow you to mark certain sections of your code as points where you want the execution of that code to temporarily pause its state until a point in which you are ready to proceed to the next breakpoint.
Modern browsers, such as Google Chrome (or any other WebKit browser like Safari) or Mozilla Firefox with the Firebug Firefox extension have this capability.
Chrome (WebKit Browsers):
You can set breakpoints in your JavaScript in the "Scripts" tab of Chrome (and most WebKit browsers):
From Chrome Developer Tools: Script Breakpoints:

*

*Open the Developer Tools by hitting the Control-Shift-I shortcut

*Open Scripts panel and select "script.js" from scripts drop-down

*Set breakpoint on line 19 by clicking the line gutter (you can use the Control-G shortcut to reveal a line in a large file)

*Move your mouse over this page

*You should stop on the breakpoint

*Hover over the source code to inspect local and global variables, function arguments etc.

*Delete the breakpoint by clicking the blue tag breakpoint indicator

*Click the Continue  button or hit F8 in Developer Tools window to resume

Firefox with Firebug:
There are countless demonstrations of Firebug Breakpoints and other debugger functionality located on this page.
The functionality is very similar to that of the Developer Tools in  WebKit browsers.

Internet Explorer:
Internet Explorer also has built in Developer Tools, which among many other features gives users the ability to set breakpoints and stop execution of the scripts. While the Chrome Debugger is sufficient in many cases, there are certain bugs and cross-browser issues that tend to affect Internet Explorer more so than other browsers.
Thus, the Setting Breakpoints section of the "Debugging Script with the Developer Tools" page will be most helpful when attempting to resolve issues that only affect Internet Explorer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic data with Flask and Mongodb data I am a beginner in Flask. Instead of static data delivery (due to size) I would like to make database calls based on the interactions (queries) of the end-user in the frontend.
I can't find any example on the net about how to proceed. I have been thinking about something like:
@app.route("/")
def index():
    return render_template('index.html')

@app.before_first_request
def initialize_database():
    pass

@app.route('api/data')
def get_data_by_selecting_bounding_box():
    pass

data are tweets and the user shall be able to select an area (bounding-box) on a map and get back a response retrieved from the Mongodb database of data included in the area.

A: So you have a few problems to solve:

*

*Manage the db connection.

*Query the DB

*Return the result

Let's start with the mongo connection:
from pymongo import MongoClient
client = MongoClient(URI_STRING)

Here you establish the mongodb client with pymongo. Now you can access your db on the mongodb service as:
db = client["my-DB-name"]

From here, you can access collections like your collection of locations, which I will assume is called locations. You can access it like db.locations.find(...)
Now you need to query the db. Your API needs to accept lat1, lat2, long1, long2 to represent the bounds of the bounding box. Here I'm going to assume they are .args as described in the docs
@app.route('api/data')
def get_data_by_selecting_bounding_box():
    cursor = db.locations.find(
    "$and":[
    {"lat": {"$gt": requests.args.get("lat1", 0)}},
    {"lat": {"$lt": requests.args.get("lat2", 0)}},
    {"long": {"$gt": requests.args.get("long1", 0)}},
    {"long": {"$lt": requests.args.get("long2", 0)}}
    ])

Now you can return the cursor at the end of this route handler, in whatever manner your html template calls for. It could be as simple as:
    return [doc for docs in cursor]


text:
Q: Can't find MiniZinc driver I'm trying to run a Python script on Ubuntu that uses the minizinc module.
The script runs fine on a Windows machine. However, when I try to run the same script on Ubuntu, I get the following error:
RuntimeWarning: MiniZinc was not found on the system. No default driver could be initialized.

The minizinc module documentation warns about this error on Linux systems and states that the path to the driver can manually be provided using minizinc.find_driver() function. I've attempted to manually set the driver path using that function but the same error occurs (I'm maybe setting it the wrong way).
I'm new to this as you can probably tell and am just wondering if anyone can enlighten me as to how to fix this issue?

A: There are two ways to make MiniZinc Python aware of where MiniZinc was installed:

*

*You can append your PATH environment variable with the directory where the minizinc executable was installed.

*You can select a specific driver using the find_driver function and then use the make_default method on Driver object that is returned.

For either method you first need to find where you have installed the minizinc executable. If you installed using the AppImage, then you can create a symlink:
$ ln -s MiniZinc<something>.AppImage /my/path/to/minizinc

This symlink will then function as the MiniZinc executable. In the following examples I will use /my/path/to/minizinc as the location of MiniZinc, but you find where it is on your own computer.
Method 1
Using the first method is usually preferred unless you want to use multiple versions of MiniZinc. If you have a MiniZinc Python script script.py that you want to execute. You simply first add the executable location to the PATH environment variable, and then run your script.
$ export PATH=$PATH:/my/path/to
$ python script.py

You only have to set the PATH once per terminal session, so afterwards you can just repeatedly run the second line. If you use MiniZinc often, then it might be a good idea to this export line to you .bashrc (or depending on what shell you use a different file).
Method 2
The other method is to edit your MiniZinc Python script. Where you used to have
import minizinc

[SOMETHING]

You would now write
import minizinc

my_driver = minizinc.find_driver("/my/path/to")
my_driver.make_default()

[SOMETHING]

To make sure it found the executable you can even add print(my_driver) so see which MiniZinc executable it found.
Note that this method will still give you a warning since, at import time, MiniZinc Python cannot find the driver. It also makes your Python code less portable, since someone else might have installed MiniZinc in a different location.


text:
Q: Can't serialize access for this transaction with isolation to ISOLATION_READ_UNCOMMITTED Using spring-batch, I have 2 datasources : one for the spring batch called centralDataSource and one for the business called localDataSource.
I've set the isolation level to ISOLATION_READ_UNCOMMITTED to avoid problems with concurrent transactions as below.
@Bean
public Job myJob(Step firstStep,
                     Step secondStep,
                     JobCompletionNotificationListener listener,
                     JobRepository customJobRepository) {
    return jobBuilderFactory.get("my-job")
                           .repository(customJobRepository)
                           .listener(listener)
                           .incrementer(new RunIdIncrementer())
                           .start(firstStep)
                           .next(secondStep)
                           .build();
}

@Bean
public JobRepository customJobRepository(
        @Qualifier("centralDataSource") DataSource centralDataSource,
        @Qualifier("centralTransactionManager") PlatformTransactionManager centralTransactionManager)
            throws Exception {
    JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
    factoryBean.setDatabaseType("ORACLE");
    factoryBean.setDataSource(centralDataSource);
    factoryBean.setTransactionManager(centralTransactionManager);
    factoryBean.setIsolationLevelForCreate("ISOLATION_READ_UNCOMMITTED");
    return factoryBean.getObject();
}

I still have Application run failed with SQLException: ORA-08177: can't serialize access for this transaction.
I don't understand why. There are not even 2 concurrent spring batch jobs running at the same time. Jobs are run sequentially so why does this happen and how can I solve it ?
Can anyone help me ?

A: I don't know Spring and how it can change transaction isolation level but:
First, Oracle database does not support READ_UNCOMMITTED isolation level:
alter session set isolation_level=read_uncommitted
                                  *
ERROR at line 1:
ORA-02183: valid options: ISOLATION_LEVEL { SERIALIZABLE | READ COMMITTED }

Second if you have ORA-8177 it means you are using SERIALIZABLE isolation level.
$ oerr ora 8177
08177, 00000, "can't serialize access for this transaction"
// *Cause:   Encountered data changed by an operation that occurred after
//           the start of this serializable transaction.
// *Action:  In read/write transactions, retry the intended operation or
//           transaction.

You need to check what ALTER SESSION statements to change isolation level are run by Spring.


text: Q: Power Analysis for Logistic Regression with one nominal variable How do I estimate sample size or do power analysis for logistic regression with one nominal independent variable? Is there a way to do it with Stata?


text:
Q: Lagrange inversion theorem applied on $f(x)=x-x^p$ I was looking at the Wikipedia page of the Lagrange inversion theorem and stumbled upon the example. It says that to find the root of the polynomial $x^p-x+z=0$ we can find the inverse of the function $f(x)=x-x^p$ using the theorem. So we have $f(x)=z$, therefore the inverse is $x=g(z)$ where
$$
g(z)=x_0+\sum_{n=1}^\infty \frac{g_n}{n!}(z-f(x_0))^n \qquad g_n=\lim_{w\to x_0}\frac{\partial^{n-1}}{\partial w^{n-1}}\left[\left(\frac{w-x_0}{f(w)-f(x_0)}\right)^n\right]
$$
The result should be, according to Wikipedia:
$$
g(z)=\sum_{n=1}^\infty\binom{pk}{k}\frac{z^{(p-1)k+1}}{(p-1)k+1}
$$
So, I decided to try it myself. First I put $x_0=0$, because $f'(0)=1$, and calculated $g_n$
$$
g_n=\lim_{w\to0}\frac{\partial^{n-1}}{\partial w^{n-1}}\left[(1-w^{p-1})^{-n}\right]
$$
Using the negative binomial theorem we obtain
$$
g_n=\lim_{w\to0}\frac{\partial^{n-1}}{\partial w^{n-1}}\left[\sum_{k=0}^\infty(-1)^k\binom{n+k-1}{k}w^{-(n+k)(p-1)}\right]= \qquad |w|<1\\
=\lim_{w\to0}\sum_{k=0}^\infty(-1)^k\binom{n+k-1}{k}(-(n+k)(p-1))...(-(n+k)(p-1)-n-2)w^{-(n+k)(p-1)-n-1}
$$
Now, this implies that $g_n=0$ $\forall n\geq2$, which isn't right. What did I do wrong?
Thanks.


text:
Q: How to use chain calls Promise? Now in .then section I all another promise http request:
.then(result => { this.service().then(data => {}); });

Is it a correct way to use chained promises?

A: Almost! You need to return the promise in the function, either like this:
.then(result => { return this.service().then(data => {}); });

or like this:
.then(result => this.service().then(data => {}));

A: Since you are using Typescript, you could use async/await to chain promises in a more readable way:
function firstCall(): Promise<any> { /* return a promise */ }
function service(): Promise<any>{ /* return a promise */ }

async function runPromisses() {
    var result = await firstCall();
    var data = await service();
    // ...
}

A: Yes, your two promises are resolved sequentially. But remember that your second (the inner) promise will only be called when the first then was successfully resolved.
An even cleaner solution would be:
.then(result => this.service()).then(data => {});

As elaborated in this SO answer by Hrishi, returning a "thenable" (for example a Promise) inside your then() function, makes the old promise adopt the state of the new promise.


text:
Q: How to get value of jquery nice select I'm developing an script that using nice select :

تعداد حمام

1 حمام

2 حمام

3 حمام

4 حمام

I check the documention and it have just two method:
$('select').niceSelect('update');

$('select').niceSelect('destroy');

It didn't say how to get the selected value , i google it too but anyway i couldn't get the selected value and another point is that i have more than one nice select in one page
How can i handle it?
Edited:
Thanks @jorge-fuentes-gonzález  and this is the snippet/fiddle  , can you help to get the selected value?

A: You have incorrect HTML. As you can see in the documentation, you have to create a normal HTML <select>, like this:
<select id="myselect">
  <option data-display="Select">Nothing</option>
  <option value="1">Some option</option>
  <option value="2">Another option</option>
  <option value="3" disabled>A disabled option</option>
  <option value="4">Potato</option>
</select>

Then pass to it the niceSelect plugin:
$("#myselect").niceSelect();

And you will be able to get the value using simple JavaScript over your <select> tag:
var selected = $("#myselect").val();

niceSelect plugin is simply a wrapper. Creates HTML over your <select> HTML, but your <select> HTML still exists on the page, but hidden, and you can continue working with it:

BUT you need to use <select> tags, not

 tags. I don't know where you got your code, but documentation is your friend. I've updated your fiddle here: https://jsfiddle.net/o7a4dtwv/


text:
Q: EF 4.1 Insert/Update Logic Best Practices I'm inserting a lot of data, wrapped in a transaction (like 2 million+ rows) at a time, using EF 4.1. Now I'd like to add UPDATE logic. Keep in mind, change-tracking is disabled given the volume of data. Off the top of my head, I'd do something like this:
// Obviously simplified code...
public void AddOrUpdate(Foo foo)
{
    if(!db.Foos.Any(x => someEqualityTest(foo)))
    {
        db.Foos.Add(foo);
    }

    else
    {
        var f = db.Foos.First(x => someEqualityTest(foo));
        f = foo;
    }

    db.SaveChanges();
}

Any ideas on how possibly to improve on this?

A: I would keep the inserts separate from the updates.
For inserts, I would recommend using SqlBulkCopy to insert all records which don't already exist and it's going to be way faster.
First, the Bulk Insert method in your DbContext:
public class YourDbContext : DbContext
{
    public void BulkInsert<T>(string tableName, IList<T> list)
    {
        using (var bulkCopy = new SqlBulkCopy(base.Database.Connection))
        {
            bulkCopy.BatchSize = list.Count;
            bulkCopy.DestinationTableName = tableName;

            var table = new DataTable();
            var props = TypeDescriptor.GetProperties(typeof(T))
                          // Dirty hack to make sure we only have system
                          // data types (i.e. filter out the
                          // relationships/collections)
                          .Cast<PropertyDescriptor>()
                          .Where(p => "System" == p.PropertyType.Namespace)
                          .ToArray();

            foreach (var prop in props)
            {
                bulkCopy.ColumnMappings.Add(prop.Name, prop.Name);

                var type = Nullable.GetUnderlyingType(prop.PropertyType)
                           ?? prop.PropertyType;

                table.Columns.Add(prop.Name, type);
            }

            var values = new object[props.Length];
            foreach (var item in list)
            {
                for (var i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }

                table.Rows.Add(values);
            }

            bulkCopy.WriteToServer(table);
        }
    }
}

Then, for your insert/update:
public void AddOrUpdate(IList<Foo> foos)
{
    var foosToUpdate = db.Foos.Where(x => foos.Contains(x)).ToList();

    var foosToInsert = foos.Except(foosToUpdate).ToList();

    foreach (var foo in foosToUpdate)
    {
        var f = db.Foos.First(x => someEqualityTest(x));

        // update the existing foo `f` with values from `foo`
    }

    // Insert the new Foos to the table named "Foos"
    db.BulkInsert("Foos", foosToinsert);

    db.SaveChanges();
}

A: Your update...
var f = db.Foos.First(x => someEqualityTest(foo));
f = foo;

...won't work because you are not changing the loaded and attached object f at all, you just overwrite the variable f with the detached object foo. The attached object is still in the context, but it has not been changed after loading and you don't have a variable anymore which points to it. SaveChanges will do nothing in this case.
The "standard options" you have are:
var f = db.Foos.First(x => someEqualityTest(foo));
db.Entry(f).State = EntityState.Modified;

or just
db.Entry(foo).State = EntityState.Modified;
// attaches as Modified, no need to load f

This marks ALL properties as modified - no matter if they really changed or not - and will send an UPDATE for each column to the database.
The second option which will only mark the really changed properties as modified and only send an UPDATE for the changed columns:
var f = db.Foos.First(x => someEqualityTest(foo));
db.Entry(f).CurrentValues.SetValues(foo);

Now, with 2 million objects to update you don't have a "standard" situation and it is possible that both options - especially the second which likely uses reflection internally to match property names of source and target object - are too slow.
The best option when it comes to performance of updates are Change Tracking Proxies. This would mean that you need to mark EVERY property in your entity class as virtual (not only the navigation properties, but also the scalar properties) and that you don't disable creation of change tracking proxies (it is enabled by default).
When you load your object f from the database EF will create then a dynamic proxy object (derived from your entity), similar to lazy loading proxies, which has code injected into every property setter to maintain a flag if the property has been changed or not.
The change tracking provided by proxies is much faster than the snapshot based change tracking (which happens in SaveChanges or DetectChanges).
I am not sure though if the two options mentioned above are faster if you use change tracking proxies. It is possible that you need manual property assignments to get the best performance:
var f = db.Foos.First(x => someEqualityTest(foo));
f.Property1 = foo.Property1;
f.Property2 = foo.Property2;
// ...
f.PropertyN = foo.PropertyN;

In my experience in a similar update situation with a few thousand of objects there is no real alternative to change tracking proxies regarding performance.


text:
Q: Junit testcase - error - status expected:<200> but was:<500> Am running Junit test cases for my project module. After the execution of the test case am getting the below error report.
ClaimControllerTest.shouldReturnClaimWithValidationResult:417 Status expected:<200> but was:<500>
Am using the below maven comment to execute the test case for a specific module.
mvn clean compile verify -Ptest
But, my project have many module dependency. How can i execute my test case for my complete project ( will all modules )
The above error is pointing to the below piece of test case code
 mockMvc.perform(get(String.format("/claims/%d/validation-result", claim.getId())))
  .andExpect(status().isOk())
  .andExpect(jsonPath("$.catClaimNumber").value(claim.getCatClaimNumber().intValue()))
  .andExpect(jsonPath("$.validationResult.programErrorCode").value("UNTHRZD_EXTRNL_USR"))
  .andExpect(jsonPath("$.validationResult.hasErrors").value(true));

Update 1 :
Am seeing the below null pointer exception after doing Sys out
2019-01-03 15:46:27,401 [main] ERROR   api.controller.BaseController:  83 - Unhandled exception while processing request for URL : http://localhost/claims/1901/validation-result with exception : null
java.lang.NullPointerException
For the below code :
mockMvc.perform(get(String.format("/claims/%d/validation-result", claim.getId()))).andDo(print());

A: It is telling you that instead of a success code 200 from calling your rest endpoint, it received an error code of 500. It means that your rest end point threw an exception.
you may want to print the full response with exception to further debug
mockMvc.perform(get(String.format("/claims/%d/validation-result", claim.getId()))).andDo(print());

A: You have two questions:

*

*Getting 500 instead of 200 - This is already answered by @mkjh

*How to execute test case for complete project ( will all modules ) - For this you should try mockito (mocking other modules) because you cannot and should not take into account of all modules until and unless it's an integration test where in you make sure all the modules are up and running or else you will again end up getting 500 error which basically tells that there is some internal server error happened and in most of the cases it happens because of some services are not up


text: Q: ASP.NET and WCF Session We have WCF based SOA architecture and ASP.NET web application consume the services hosted. Within each method that needs service call, we create a proxy instance and close when the results are returned. The binding is basicHttpBinding.  By default InstanceContextMode is per session, do we need to change this to Percall as we do not require any state full calls in the application. Does this improve any performance?


text:
Q: JS filtering array using regexp on value I have arr with categories tree. Example: category yy is subcategory of ww and ww is subcategory of zz. I want to filter this array and get this output: ['aa_bb', 'aa_cc', 'zz_ww_yy']. So I don't want zz and zz_ww becouse i have this in zz_ww_yy. I think that I must use filter function and maybe some regexp? hmmm and maybe foreach? What you think?
var arr = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww','zz_ww_yy'];

var filtered = arr.filter(function(a){
    //???
})

console.log(filtered);

A: You could take String#indexOf and filter the temporary result array with the given string.
Then check if the string is not a substring of the result set and push it if not.

var array = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww','zz_ww_yy'],
    result = array.reduce(function (r, a) {
        r = r.filter(b => a.indexOf(b) === -1);
        if (r.every(b => b.indexOf(a) === -1)) {
            r.push(a);
        }
        return r;
    }, []);

console.log(result);

A: try that on also, you could easely change the logic.

var arr = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww', 'zz_ww_yy'];

function shoulFilterCategory(arr, itemToTest, itemIndex) {
  var shouldFilter = false;

  arr.filter((item, index) => index !== itemIndex)
     .forEach(item => {
    if (item.startsWith(itemToTest) && itemToTest.length < item.length)         {
      shouldFilter = true;
    }
  });
  return shouldFilter;
}

var filtered = arr.filter(
  (item, index) => !shoulFilterCategory(arr, item, index)
);

console.log('filtered', filtered);


text:
Q: Having trouble with one way adio on an asterisk sip phone I have an asterisk server (Elastix on CentOS 7) that I am currently running in Amazon Web Services.  The server works great and clients can connect without issue using a stun server.  However I have several Digium phones (D-50) that I need to connect.  These phones do not have an option to use a stun setting that I have been able to find, and currently when behind our firewall only have one way audio.
I have tried to find a solution but so far have been unsuccessful.  Are there any changes I Can make server side or client side to facilitate this?
I could forward ports, but as far as I can tell that would only work for one phone and I need to use several.

A: Actually, we've found that the easiest answer to putting a phone behind NAT to connect to an Asterisk server on a public internet server is to set the SIP registration timeout to less than 120 seconds (usually 100 seconds). This ensures that NAT is always forwarding the port back to the phone. It also ensures that the phone's private IP address is always up to date in the NAT settings, and basically, that everything "just works".
Other schemes like STUN don't work anywhere near as well, and this solution is really quite robust.


text:
Q: Does Circle CI 2.0 invalidate cache key when changing docker images I want my cache to become invalid when I change container build images. Does that happen automatically or do I need to marry the cache key to the build container image?

A: From support ticket:
If you're using a new container build image, the old cache shouldn't be used (since it's irrelevant), and a new one will be created. Of course, rotating cache keys will also ensure a fresh cache.


text:
Q: How to fix FireFly Fabconnect container start issue: "User credentials store creation failed. User credentials store path is empty" Sorry upfront for the long question. I wanted to make sure all the information was laid out for you.
I am having issues getting my FireFly Fabconnect container to be able to read/see/recognize my user credentials for my Fabric network. I have tried everything, so I am hoping someone here can help me. When I start the Fabconnect container, this error is outputted to the logs (and then the container terminates):
User credentials store creation failed. User credentials store path is empty

I have tried a variety of things with little luck. I know for a fact the path isn't empty, so I am not sure what the issue could be. Here are pertinent sections of the config files...hopefully someone can spot something and help me out (this is for a production env as well. I am not using the CLI):
ccp.yaml:
credentialStore:
    path: /etc/firefly/organizations/peerOrgs/Org1/users
    cryptoStore:
      path: /etc/firefly/organizations/peerOrgs/Org1/users
  cryptoconfig:
    path: /etc/firefly/organizations/peerOrgs/Org1/users

fabconnect.yaml:
http:
  port: 3000
rpc:
  useGatewayClient: true
  configpath: /fabconnect/ccp.yaml

docker-compose.yaml:
volumes:
      - fabconnect_receipts_0:/fabconnect/receipts
      - fabconnect_events_0:/fabconnect/events
      - ./fabconnect.yaml:/fabconnect/fabconnect.yaml
      - ./ccp.yaml:/fabconnect/ccp.yaml
      - ../../../fabric-prod/_dockerTesting/organizations:/etc/firefly/organizations
      - ../../../fabric-prod/_dockerTesting/client:/etc/firefly/client

Folders/files pulled from Fabric Org directory:
afcranmer@LAPTOP-3KCE1D20:/mnt/c/Users/afcra/Documents/_WD/fabric-prod/_dockerTesting/organizations/peerOrgs/Org1/users/org1admin/msp$ ls
IssuerPublicKey  IssuerRevocationPublicKey  cacerts  config.yaml  keystore  signcerts  user

The only difference I can see is the folder structure that is created when running fabric-ca-client enroll is slightly different than the one that is created with the FireFly CLI or the Fabric samples test-network. Mine just has an MSP folder (shown above), but the test-network creates an MSP folder and a TLS folder with 3 certs in it. I don't think that should be an issue but I am not sure.
In regards to my underlying Fabric network, I followed the instructions shown in the "Deploying a production network" section of the Hyperledger Fabric documents. I am just user containers rather than the CLI to stand up stuff.
I have an the following Fabric coponents:

*

*TLS CA

*Org1 CA

*Orderer Node

*Org1 Peer Node

Any help at all would be appreciated. I have tried everything at this point. I am happy to provide more information if needed.


text:
Q: Django/Python - Updating the database every second I'm working on creating a browser-based game in Django and Python, and I'm trying to come up with a solution to one of the problems I'm having.
Essentially, every second, multiple user variables need to be updated. For example, there's a currency variable that should increase by some amount every second, progressively getting larger as you level-up and all of that jazz.
I feel like it's a bad idea to do this with cronjobs (and from my research, other people think that too), so right now I'm thinking I should just create a thread that loops through all of the users in the database that performs these updates.
Am I on the right track here, or is there a better solution? In Django, how can I start a thread the second the server starts?
I appreciate the insight.

A: One of the possible solutions would be to use separate daemonized lightweight python script to perform all the in-game business logic and left django be just the frontend to your game. To bind them together you might pick any of high-performance asynchronous messaging library like ZeroMQ (for instance to pass player's actions to that script). This stack would also have a benefit of a frontend being separated and completely agnostic of a backend implementation.

A: Generally a better solution would be to not update everyone's currency every second. Instead, store the timestamp of the user's most recent transaction, their income rate, and their latest balance. With these three pieces of data, you can calculate their current balance whenever needed.
When the user makes a purchase for example, do the math to calculate what their new balance is. Some pseudocode:
def current_balance(user):
    return user.latest_balance + user.income * (now() - user.last_timestamp)

def purchase(user, price):
    if price > current_balance(user):
        print("You don't have enough cash.")
        return

    user.balance = current_balance(user) - price
    user.last_timestamp = now()
    user.save()
    print("You just bought a thing!")

With a system like this, your database will only get updated upon user interaction, which will make your system scale oodles better.


text:
Q: How to define one static folder for all routes I use github.com/gorilla/mux router and I need include my static files for all routes or notFound routes.
Now refreshing only page by / works but other urls doesn't.
package main

import (
    "fmt"
    "log"
    "net/http"
    "crudgo/backend/home"
    "github.com/gorilla/mux"
  )

func main() {
     http.FileServer(http.Dir("./public/p/dist"))
     log.Println("Listening...")

     router := mux.NewRouter();

     home.HomeRoute(router)

     router.PathPrefix("/{_:.*}").Handler(http.FileServer(http.Dir("./public/p/dist")))

     http.ListenAndServe("localhost:3000", router)
}


text:
Q: Powershell Invoke-CImMethod type mismatch Why does this work?
Get-CimInstance -Namespace "root/CIMV2/TerminalServices" -ClassName "Win32_TSGatewayServerSettings" | Invoke-CimMethod -MethodName "SetIPAndPort" -Arguments @{TransportType=1; IPAddress="*"; Port=4443; OverrideExisting=1}

But this:
Invoke-CimMethod -Namespace "root/CIMV2/TerminalServices" -ClassName "Win32_TSGatewayServerSettings" -MethodName "SetIPAndPort" -Arguments @{TransportType=1; IPAddress="*"; Port=4443; OverrideExisting=1}

Gives an error:

Invoke-CimMethod : Type mismatch for parameter "Port"

The Port argument should be an unit16 I can cast it as such but then it trips over the other boolean values.
Invoke-CimMethod -Namespace "root/CIMV2/TerminalServices" -ClassName "Win32_TSGatewayServerSettings" -MethodName "SetIPAndPort" -Arguments @{TransportType=1; IPAddress="*"; Port=[uint16]4443; OverrideExisting=1}

Invoke-CimMethod : Type mismatch for parameter "OverrideExisting"

I don't understand why using Get-CimInstance changes anything about casting variables.


text:
Q: show an unknown number of graphs in a grid RShiny I have looked at all the solutions on SO using grid.arrange but it doesn't really achieve what I want.
Let's assume I have a list of grobs that are generated within a reactive environment in RShiny.
I would like to create a mainPanel where those graphs are on 2 columns (until that point, it's all feasible with grid.arrange) but where each line corresponds to a fluidRow element.
A barebone example of this would be
ui <- fluidPage(

    titlePanel("TEST"),
    sidebarPanel(width=3,
        actionButton(inputId = 'launchCalcButton',label = 'Launch Calc')
    ),
    mainPanel(
        uiOutput("resultsPlotUI")
    )
)

server <- function(input,output){

    graphsList <- eventReactive(input$launchCalcButton, {
        a <- lapply(1:10,function(i){
            return(
                ggplot(data = data.frame(a=rnorm(10),b=rnorm(10)),aes(x=a,y=b))
                +geom_point()
            )
        })
        return(a)
    })
    output$resultsPlot <- renderPlot({
        do.call(grid.arrange,c(graphsList(),ncol=2))
    })

    output$resultsPlotUI <- renderUI({
        fluidRow(
            column(12,
                plotOutput(
                    outputId = 'resultsPlot'
                )
            )
        )
    })
}

app = shinyApp(ui,server)
runApp(app)

All the graphs end up squeezed into one single line whereas I would want them to be split between lines.

A: You just need to set up height parameter for the plotOutput:
library(shiny)
library(gridExtra)
ui <- fluidPage(

  titlePanel("TEST"),
  sidebarPanel(width=3,
               actionButton(inputId = 'launchCalcButton',label = 'Launch Calc')
  ),
  mainPanel(
    uiOutput("resultsPlotUI")
  )
)

server <- function(input,output){

  graphsList <- eventReactive(input$launchCalcButton, {
    a <- lapply(1:10,function(i){
      return(
        ggplot(data = data.frame(a=rnorm(10),b=rnorm(10)),aes(x=a,y=b))
        +geom_point()
      )
    })
    return(a)
  })
  output$resultsPlot <- renderPlot({
    l <- length(graphsList())/2
    print(l)
    do.call(grid.arrange,c(graphsList(),ncol=2))
  })

  output$resultsPlotUI <- renderUI({
    fluidRow(
      column(12,
             plotOutput(
               outputId = 'resultsPlot', height = 600
             )
      )
    )
  })
}

app = shinyApp(ui,server)
runApp(app)

Exactly in this place:
 output$resultsPlotUI <- renderUI({
    fluidRow(
      column(12,
             plotOutput(
               outputId = 'resultsPlot', height = 600
             )
      )
    )
  })

I have set it up to 600 px (height = 600) but you can choose whatever you want.


text:
Q: is there an anova/linear model function that will work for both emmeans and resid_panel in a shiny app? I am trying to write a shiny app that can upload an excel file, select any variables, and output an anova table, plot, multiple comparisons, and residual plots. because resid_panel() does not accept output from aov(), I have been using lm(). I am trying to use emmeans to generate my multiple comparisons output.
This is my code for the multiple comparisons section of my app:
`** ##Outputting the Tukey adjusted multiple comparisons for my model
  output$MultComp <- renderPrint({
    req(input$X, input$Y)
     X <- as.name(input$X)
     Y <- as.name(input$Y)
     aov1 <- lm(get(Y)~ get(X), data = data())
     means <- emmeans::emmeans(aov1, specs = dQuote(get(X)))
     pw <- emmeans::contrast(means, method = "pairwise", adjust = "tukey")
     pw
  })**`

when I select my variables/dataset in the app I get the following error message in my comparisons tab:
`
**Error: We are unable to reconstruct the data.
The variables needed are:
    X
Are any of these actually constants? (specify via 'params = ')
The dataset name is:
    data
Does the data still exist? Or you can specify a dataset via 'data = '**`

I suspect the problem may lie in emmeans where I have to specify my X variable for comparisons, as the following code using an example data set works perfectly outside of the shiny app. emmeans wants the X variable to be in quotes, which I think may be the issue but I just cant figure it out
`**X <- as.name(dat1$Log10dose)
Y <- as.name(dat1$Logres)
aov2 <- lm(Logres~ Log10dose, data = dat1)
means <- emmeans::emmeans(aov2, specs = "Log10dose")
pw <- emmeans::contrast(means, method = "pairwise", adjust = "tukey")
pw**`

I have tried using dquote(), get(), and just X, and input$X in emmeans to specify my variable and all of them give me the same error, for reference the lm() line works fine in other sections of the app where I display the anova table or residual plots using resid_panel()


text:
Q: Why do I always get a null object while receiving contact numbers? I'm accessing the phone numbers of all the contacts and sending it to Parse Cloud database, but I always get a NullPointerException

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.parse.ParseUser.put(java.lang.String, java.lang.Object)' on a null object reference

This is the class where I'm executing the above:
package com.weet.weet; /**
* Created by Ashish on 11/10/15.
*/
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;

import com.parse.ParseUser;

import java.util.ArrayList;

public class getContacts {
ArrayList<String> allNumbers = new ArrayList<String>();
public ArrayList ReadPhoneContacts(Context cntx) //This Context parameter is nothing but your Activity class's Context
{
    Cursor cursor = cntx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
    if (contactsCount > 0)
    {
        while(cursor.moveToNext())
        {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                //the below cursor will give you details for multiple contacts
                Cursor pCursor = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                        new String[]{id}, null);
                // continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
                while (pCursor.moveToNext())
                {
                    int phoneType       = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                    //String isStarred      = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
                    String phoneNo  = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //you will get all phone numbers according to it's type as below switch case.
                    //Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
                    switch (phoneType)
                    {
                        case Phone.TYPE_MOBILE:
                            //Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
                            allNumbers.add(phoneNo);
                            break;
                        case Phone.TYPE_HOME:
                            //Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
                            allNumbers.add(phoneNo);
                            break;
                        case Phone.TYPE_WORK:
                            //Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
                            allNumbers.add(phoneNo);
                            break;
                        case Phone.TYPE_WORK_MOBILE:
                            //Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
                            allNumbers.add(phoneNo);
                            break;
                        case Phone.TYPE_OTHER:
                            //Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
                            allNumbers.add(phoneNo);
                            break;
                        default:
                            break;
                    }
                }
                pCursor.close();
            }
        }
        cursor.close();
    }
    ParseUser currentUser = ParseUser.getCurrentUser();
    currentUser.put("friends", allNumbers);

    return allNumbers;
}

}


text:
Q: Deploying an ECS application to AWS using docker compose I am following the AWS tutorial on deploying an ECS application using docker compose.
When I run docker compose up, I only receive the message docker  UpdateInProgress User Initiated, but nothing else happens:
[+] Running 0/0
 - docker  UpdateInProgress User Initiated                                                                 0.0s

Previously, this worked fine and all the ECS resources (cluster, task definitions, services, load balancer) had been created.
For some reason, now, this does not work anymore (although I have not changed my docker-compose.yml file).
docker-compose.yml:
version: '3'

services:
  postgres:
    image: ${AWS_DOCKER_REGISTRY}/postgres
    networks:
      - my-network
    ports:
      - "5432:5432"
    volumes:
      - postgres:/data/postgres

  server:
    image: ${AWS_DOCKER_REGISTRY}/server
    networks:
      - my-network
    env_file:
    - .env
    ports:
      - "${PORT}:${PORT}"
    depends_on:
    - postgres
    entrypoint: "/server/run.sh"

  pgadmin:
    image: ${AWS_DOCKER_REGISTRY}/pgadmin
    networks:
      - my-network
    depends_on:
    - postgres
    volumes:
       - pgadmin:/root/.pgadmin
    ports:
      - "${PGADMIN_PORT:-5050}:${PGADMIN_PORT:-5050}"

networks:
  my-network:
    #driver: bridge

volumes:
    postgres:
    pgadmin:

I also switched to the correct Docker context before (docker context use my-aws-context).
And I have updated to the latest version of Docker Desktop for Windows and AWS CLI.
Did someone already have a similar problem?

A: From the message it appears that you are trying to compose up a stack that is existing already (on AWS) and so it's trying to update the CFN stack. Can you check if this is the case? You have a couple of options if that is what's happening: 1) delete the CFN stack (either in AWS or with docker compose down) or 2) launch the docker compose up with the flag --project-name string (where string is an arbitrary name of your choice). By default compose will use the directory name as the project name so if you compose up twice it will try to work on the same stack.


text:
Q: ansible changing nested dict variable After deployment of a VM with a DHCP IP I would like to get the IP and append it to the guests dictionary.
For the first VM (testvm2) the code perfoms as expected and updates the tempip variable for the testvm2 VM.
But with the second VM (testvm1), it updates the tempip variable of the first VM (testvm2) with the IP of the second VM (testvm1), and updates the tempip variable of the second VM (testvm1) with the code of the variable '{{ tempip_reg.stdout_lines }}'
Can anyone explain to me why this happens?
I would appreciate the help.
I copied all the relevant code and output below:
guests dictionary:
---
guests:
  testvm1:
    mem: 512
    cpus: 1
    clone: template-centos
    vmid: 102
    tempip:

  testvm2:
    mem: 1536
    cpus: 2
    clone: template-centos
    vmid: 102
    tempip:

Ansible Playbook that starts the task:
---
- name: Provision VMs
  hosts: infra
  become: true
  vars_files:
    - group_vars/vms.yml
    - group_vars/vars.yml
  tasks:
    - include_tasks: roles/tasks/provision-tasks.yml
      with_dict: "{{ guests }}"

Ansible Tasks:
- name: Run proxmox-get-ip-linux.sh script to register DHCP IP of VM
  script: proxmox-get-ip-linux.sh "{{ item.key }}"
  register: tempip_reg

- name: temporary IP of VM "{{ item.key }}"
  debug:
    var: tempip_reg

- name: current host in item.key
  set_fact:
    current_host: "{{ item.key }}"

- name: current_host variable set to
  debug:
    var: current_host

- name: append item.value.tempip with the DHCP IP of the VM registered in
 last task
  set_fact:
    guests: "{{ guests|combine({ current_host: {'tempip': '{{ tempip_reg.stdout_lines }}' }}, recursive=True) }}"

- name: temporary IP of "{{ item.key }}"
  debug: var=guests

Result first VM:
"tempip_reg": {
    "stdout": "192.168.1.21\r\n",
    "stdout_lines": [
        "192.168.1.21"
    }

"current_host": "testvm2"

"guests": {
    "testvm1": {
        "clone": "template-centos",
        "cpus": 1,
        "ip": "192.168.1.60",
        "mem": 512,
        "tempip": null,
        "vmid": 102
    },
    "testvm2": {
        "clone": "template-centos",
        "cpus": 2,
        "ip": "192.168.1.61",
        "mem": 1536,
        "tempip": [
            "192.168.1.21"
        ],
        "vmid": 102
    }
}

Result 2nd VM:
"tempip_reg": {
    "stdout": "192.168.1.22\r\n",
    "stdout_lines": [
        "192.168.1.22"
    }

    "current_host": "testvm1"

"guests": {
    "testvm1": {
        "clone": "template-centos",
        "cpus": 1,
        "ip": "192.168.1.60",
        "mem": 512,
        "tempip": "{{ tempip_reg.stdout_lines }}",
        "vmid": 102
    },
    "testvm2": {
        "clone": "template-centos",
        "cpus": 2,
        "ip": "192.168.1.61",
        "mem": 1536,
        "tempip": [
            "192.168.1.22"
        ],
        "vmid": 102
    }
}

A: TL;DR
Using Ansible code, you are trying to implement what Ansible already does for you.
Your attempts superimpose with built-in functionality and you get results which look nondeterministic.

Explanation:

*

*The main problem with your code is a completely unnecessary loop declared with with_dict: "{{ guests }}" which causes to include the file 4 times.
It runs 4 times because you change the guests dictionary, which it loops over inside the included tasks-file.
In effect you get something which looks like an nondeterministic result.

*The second problem is a trivial one: you always replace the value of tempip with a string {{ tempip_reg.stdout_lines }}.

*Now, because of the unnecessary with_dict loop over a dictionary which you dynamically change, and because Jinja2 uses lazy variable evaluation, strings from previous iterations are interpreted as templates and get evaluated with incorrect values in subsequent iterations.
The last iteration leaves the string {{ tempip_reg.stdout_lines }} intact.

*You also define and print two different facts.

What you should do:

*

*You should not declare arbitrary iterations at all. Ansible implements a loop for all hosts itself. That is, if you declare a task:
- include_tasks: roles/tasks/provision-tasks.yml

the file will be included for each of the hosts in infra group (twice in your example).

*You seem to want to have a single copy of your data structure with updated values for each VM.
At the same time, you create a fact, which is a separate data object maintained for each host separately.
So you should refer to and modify (combine) a single fact - you can do it for example on localhost.

You should structure your code like this:
---
- name: Provision VMs
  hosts: infra
  become: true
  vars_files:
    - group_vars/vms.yml
    - group_vars/vars.yml
  tasks:
    - include_tasks: roles/tasks/provision-tasks.yml
    - debug:
        var: hostvars['localhost'].guests

and provision-tasks.yml:
- set_fact:
    guests: "{{ guests|combine({ current_host: {'tempip': tempip_reg.stdout_lines }}, recursive=True) }}"
  delegate_to: localhost

This will get you the following result:
"hostvars['localhost'].guests": {
    "testvm1": {
        "clone": "template-centos",
        "cpus": 1,
        "ip": "192.168.1.60",
        "mem": 512,
        "tempip": [
            "192.168.1.21"
        ],
        "vmid": 102
    },
    "testvm2": {
        "clone": "template-centos",
        "cpus": 2,
        "ip": "192.168.1.61",
        "mem": 1536,
        "tempip": [
            "192.168.1.22"
        ],
        "vmid": 102
    }
}

Finally, in the above play, you used group_vars and roles/tasks directories in wrong context. I left the paths intact and they will work for the above code, but basically you should never use them this way, because again, they have special meaning and treatment in Ansible.


text:
Q: Convert time to double in ssrs I have a time parameter in SSRS report whose value is like "14:07:58". How can I convert it to double?
The data type of this parameter is string(text) and I want to convert this time to double.
I tried using CDble("14:07:58") but it returns error.
Any suggestions ?

A: You could calculate "ticks" (100 nanoseconds) since midnight and divide it by the number of ticks per day:
=CDate("14:07:58").Ticks/TimeSpan.TicksPerDay


text:
Q: Extract data from a list within dictionary using JSON I am working with an OKR program where I am trying to extract the Objectives and Key Results from its API (sample anonymized JSON output below). I want to use a while loop to iterate through the one or many key results an objective may have. However, I get a traceback error with [keymetric_start] in the line "metric_name =(u['people_goals'][0]['goal_metrics'][keymetric_start]['metric_name'])" saying "IndexErrorL list index out of range".  How do I get it to accept the keymetric_start as a variable? Thanks so much!

{
  "success": true,
  "message": "",
  "data": {
    "totalCount": 14,
    "goal": [{
        "user_id": 12345,
        "people_goals": [{
            "goal_id": 13579,
            "goal_name": "move the business forward",
            "goal_metrics": [{
                "metric_id": "2468",
                "metric_name": "Raise more money",
                "metric_progress": "50"
              },
              {
                "metric_id": "2469",
                "metric_name": "Get more financing",
                "metric_progress": "25"
              },
              {
                "metric_id": "2470",
                "metric_name": "Understand risks",
                "metric_progress": "75"
              }
            ],
            "goal_metrics_count": 3
          },
        }
      ]
    }
  ]
}
}
for u in js['data']['goal']:
  goal_name = (u['people_goals'][0]['goal_name'])
  keymetric_count = (u['people_goals'][0]['goal_metrics_count'])
  keymetric_start = 0
  while keymetric_start <= keymetric_count:
    metric_name =(u['people_goals'][0]['goal_metrics'][keymetric_start]['metric_name'])
    keymetric_start = keymetric_start +1

A: I feel the issue is this line - while keymetric_start <= keymetric_count:
you are saying they both can be equal which means keymetric_start could have a maximum value of 3.
However, there are only 3 elements inside goal_metrics so the highest allowed value for keymetric_start should be 2 (not 3) due to zero based indexing of arrays.
You can try doing this in your while clause:
while keymetric_start < keymetric_count:


text:
Q: Clear forest / improvement before building? Should I use a builder to clear forest before building on top of it?
(When there's a red question mark icon saying "Building here will remove the forest")

A: This is a rather subjective question, and the "correct" answer will vary according to game situation. It all depends on your priority.
I will say that I typically do not remove forrest by putting a district on top of it. Instead, I will produce something else, and chop the forrest to help produce it faster. When I have finished that thing, I will then start the district on the tile that previously had a forrest.


text:
Q: Remove punctation from every value in Python dictionary I have a long dictionary which looks like this:
name = 'Barack.'
name_last = 'Obama!'
street_name = "President Streeet?"

list_of_slot_names = {'name':name, 'name_last':name_last, 'street_name':street_name}

I want to remove the punctation for every slot (name, name_last,...).
I could do it this way:
name = name.translate(str.maketrans('', '', string.punctuation))
name_last = name_last.translate(str.maketrans('', '', string.punctuation))
street_name = street_name.translate(str.maketrans('', '', string.punctuation))

Do you know a shorter (more compact) way to write this?
Result:
>>> print(name, name_last, street_name)
>>> Barack Obama President Streeet

A: Use a loop / dictionary comprehension
{k: v.translate(str.maketrans('', '', string.punctuation)) for k, v in list_of_slot_names.items()}

You can either assign this back to list_of_slot_names if you want to overwrite existing values or assign to a new variable
You can also then print via
print(*list_of_slot_names.values())

A: name = 'Barack.'
name_last = 'Obama!'
empty_slot = None
street_name = "President Streeet?"

print([str_.strip('.?!') for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])

-> Barack Obama President Streeet

Unless you also want to remove them from the middle. Then do this
import re

name = 'Barack.'
name_last = 'Obama!'
empty_slot = None
street_name = "President Streeet?"

print([re.sub('[.?!]+',"",str_) for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])

A: import re, string

s = 'hell:o? wor!d.'

clean = re.sub(rf"[{string.punctuation}]", "", s)

print(clean)

output
hello world


text:
Q: Programatically download a plugin I'd like to programmatically download a plugin from the WordPress official repo, using a link/id/whatever identifier token.
How could this be achieved?

A: WP CLI is best tool out there to manage plugins/ themes through command line, instead of uploading plugins through FTP or admin panel.
Once you Install WP-CLI on your machine then run below command and see magic.

wp plugin install bbpress --activate

Please check WP-CLI official documentation for further understanding.

A: Found: https://gist.github.com/squarestar/37fe1ff964adaddc0697dd03155cf0d0 as well as https://stackoverflow.com/questions/10353859/is-it-possible-to-programmatically-install-plugins-from-wordpress-theme
Turns out there are quite a number of ways to do it, just not mentioned here at the wordpress stack exchange.

A: PHP has a de-facto standard package manager called Composer. This does not only download packages (themes, plugins, the core) for you, but also solves dependency conflicts in case two of your dependencies/ packages request the same sub-package (de-duplication) and maybe even in different versions.
There's the WordPress specific extension called WP Starter that does all the heavy lifting for you in this case. I'd recommend to go with that.
If that is too much for you, you can build a monorepo and use version control systems like SVN, Git, mercurial and others to download content and later on even update those packages. Be aware that while VCS are capable of managing packages, they are not meant to do so (even with their extensions). Better use the right tool for the job and use a dedicated package manager or above mentioned abstraction/ simplification/ empowerification that is specific to Wordpress.


text:
Q: Table with an array, return hash I have an array ["1","1","a","b","y"] and table1:
table1

POSITION    NAME     VALUE     CODE
1           Animal   Dog       1
1           Animal   Cat       2
1           Animal   Bird      3
2           Place    USA       1
2           Place    Other     2
3           Color    Red       a
3           Color    Blue      b
3           Color    Orange    c
4           Age      Young     a
4           Age      Middle    b
4           Age      Old       c
5           Alive    Yes       y
5           Alive    No        n

For each element in the array, I would like to find a matching POSITION-CODE combination in table1, where POSITION is the index of the element (base 1) and CODE is the element in the array. Then, I want to return a hash that contains  the corresponding NAME and VALUE for the matches as a key and its value. The output would be:
{"Animal" => "Dog", "Place" => "USA", "Color" => "Red", "Age" => "Middle", "Alive" => "Yes"}

How would I go about this?

A: I assume you want to map several codes arrays against the same table. Suppose you first read the table into an array:
a = [["1", "Animal", "Dog", "1"],
     ["1", "Animal", "Cat", "2"],
     ["1", "Animal", "Bird", "3"],
     ["2", "Place", "USA", "1"],
     ["2", "Place", "Other", "2"],
     ["3", "Color", "Red", "a"],
     ["3", "Color", "Blue", "b"],
     ["3", "Color", "Orange", "c"],
     ["4", "Age", "Young", "a"],
     ["4", "Age", "Middle", "b"],
     ["4", "Age", "Old", "c"],
     ["5", "Alive", "Yes", "y"],
     ["5", "Alive", "No", "n"]]

and
codes = ["1","1","a","b","y"]

Then you could do this:
codes.zip(a.chunk { |a| a.first }).map { |l,(_,b)|
  b.find { |c| c.last == l}[1...-1] }.to_h
  #=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
  #    "Age"=>"Middle", "Alive"=>"Yes"}

The steps:
enum0 = a.chunk { |a| a.first }
  #=> #<Enumerator:
  #   #<Enumerator::Generator:0x007f8d6a0269b8>:each>

To see the contents of the enumerator,
enum0.to_a
  #=> [["1", [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
  #           ["1", "Animal", "Bird", "3"]]],
  #    ["2", [["2", "Place", "USA", "1"], ["2", "Place", "Other", "2"]]],
  #    ["3", [["3", "Color", "Red", "a"], ["3", "Color", "Blue", "b"],
              ["3", "Color", "Orange", "c"]]],
  #    ["4", [["4", "Age", "Young", "a"], ["4", "Age", "Middle", "b"],
  #           ["4", "Age", "Old", "c"]]],
  #    ["5", [["5", "Alive", "Yes", "y"], ["5", "Alive", "No", "n"]]]]

p = codes.zip(enum0)
  #=> [["1", ["1", [["1", "Animal", "Dog", "1"],
  #                 ["1", "Animal", "Cat", "2"],
  #                 ["1", "Animal", "Bird", "3"]]]],
  #    ["1", ["2", [["2", "Place", "USA", "1"],
  #                 ["2", "Place", "Other", "2"]]]],
  #    ["a", ["3", [["3", "Color", "Red", "a"],
  #                 ["3", "Color", "Blue", "b"],
  #                 ["3", "Color", "Orange", "c"]]]],
  #    ["b", ["4", [["4", "Age", "Young", "a"],
  #                 ["4", "Age", "Middle", "b"],
  #                 ["4", "Age", "Old", "c"]]]],
  #    ["y", ["5", [["5", "Alive", "Yes", "y"],
  #                 ["5", "Alive", "No", "n"]]]]]

l,(_,b) = enum1.next
l #=> "1"
b #=> [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
  #    ["1", "Animal", "Bird", "3"]]
enum1 = b.find
  #=> #<Enumerator: [["1", "Animal", "Dog", "1"],
  #                  ["1", "Animal", "Cat", "2"],
  #                  ["1", "Animal", "Bird", "3"]]:find>
c = enum1.next
  #=> ["1", "Animal", "Dog", "1"]
c.last == l
  #=> true

so enum1 returns
d = ["1", "Animal", "Dog", "1"]
e = d[1...-1]
  #=> ["Animal", "Dog"]

So the first element of x.zip(y) is mapped to ["Animal", "Dog"].
After performing the same operations for each of the other elements of enum1, x.zip(y) equals:
f = [["Animal", "Dog"], ["Place", "USA"], ["Color","Red"],
     ["Age",  "Middle"], ["Alive", "Yes"]]

The final steps is
f.to_h
  #=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
  #    "Age"=>"Middle", "Alive"=>"Yes"}

or for < v2.0
Hash[f]


text:
Q: Command raised an exception: AttributeError: 'Context' object has no attribute 'id' discord.py I want to delete the Guild ID in a JSON file with an Command.
This is my code:
 @welcome.command(pass_context=True)
    @commands.has_permissions(administrator=True)
    async def reset(guild):
        with open('welcome.json', 'r') as f:
            welcome = json.load(f)

        welcome.pop(str(guild.id))
        with open('welcome.json', 'w',) as f:
            json.dump(welcomereset, f, indent=4)

This is the Error Message: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'id'
How can i fix this?

A:  @welcome.command() #pass_context is deprecated, every command will always get passes Context as first param.
 @commands.has_permissions(administrator=True)
 async def reset(ctx: commands.Context): #Just normal typehint for you to easily understand.
        with open('welcome.json', 'r') as f:
            welcome = json.load(f)

        welcome.pop(str(ctx.guild.id)) #ctx.guild -> discord.Guild and than .id for it's id. I would put an if statement to check if the command was even in a guild, so NoneType attribute error won't raise.
        with open('welcome.json', 'w',) as f:
            json.dump(welcomereset, f, indent=4)

The first parameter in each command is ctx or context the represents discord.ext.commands.Context object, which as you can see, doesn't have id. If you are trying to get the guild id of where the command was invoked, doing ctx.guild will return Optional[discord.Guild](if command was invoked in a private channel). And than if it is not None, you can do ctx.guild.id, which is probably what you want. And you no longer need pass_context(which was used to pass discord.ext.commands.Context btw). Which means the right now, guild is your Context object.

A: The first parameter in each command is ctx or context the represents discord.ext.commands.Context object, which as you can see, doesn't have id. If you are trying to get the guild id of where the command was invoked, doing ctx.guild will return Optional[discord.Guild](if command was invoked in a private channel). And than if it is not None, you can do ctx.guild.id, which is probably what you want. And you no longer need pass_context(which was used to pass discord.ext.commands.Context btw)

A: Since you didn't mentioned your discord.py version, I assume:
- It's before version 1.0:
You have pass_context=True, so Context will be passed as the first argument in the function.
async def reset(guild): # The word 'guild' is actually a Context object

The name guild is defined as Context so regardless of the name, it follows the properties of Context and not a Guild. Therefore you can still use guild and follow properties of Context but it's recommended to edit guild to context or ctx to prevent confusion.
You can also just do pass_context=False and make the guild argument to be accepted as an input via the user.
- It's after version 1.0:
The pass_context parameter is removed since then, so regardless if you use this or not, Context is always passed.
As above, you need to follow the properties of Context and use proper attributes. In your case, if you need to access id of the guild the command is invoked, you can do ctx.guild.id (ctx refers to Context object passed).
async def reset(ctx):
    ...
    welcome.pop(str(ctx.guild.id))
    ...

and this will work fine.
P.S.: I'm not sure but by looking at the code, I think you have passed wrong argument (welcomereset) in the .dump() and want to pass welcome instead. Ignore this if I'm wrong :P


text:
Q: Functions on Superspace I find the definition of a function $\phi$ on a superspace $(z,\theta)$ confusing for the following reason. $\phi(z,\theta)$ can be expanded as $$\phi(z,\theta) = \phi_0(z) + \theta \psi(z)\tag{1}.$$ Now, it is usually said that $\phi_0(z)$ is a smooth function. However, $z$ has a body $z_b$ (which is a complex number) and a soul $z_s$ (which is a sum of product of even number of Grassmann numbers). Perhaps what is meant is following. Let $x \mapsto f(x)$ be any smooth function. Then $$\phi_0(z) = \phi_0(z_b+z_s) \equiv f(z_b)+\sum_{n=1}^\infty \frac{1}{n!} f^{(n)}(z_b)z_s^n\tag{2}$$ seems a possible definition. Is this what is meant when one considers a function on a superspace?

A: The Taylor expansion (1) of a superfield $\phi(\theta)$ in component fields should not be conflated with the Taylor expansion (2) of a component field/function $\phi_0(z)\equiv f(z)$ at the body $z_b$.
Note in particular that not all functions of supernumbers are superfields; and that the Grassmann numbers in the soul $z_s$ have nothing to do with Grassmann number $\theta$ in the superfield (1).
For more information, see e.g. this related Phys.SE post.


text:
Q: PLN similitud entre textos cortos Soy nuevo en el mundo de data science y estoy haciendo un proyecto para un empresa de venta de comida preparada del que tengo el histórico de los 2 últimos años pero cada plato está escrito de diferentes formas lo que hace que a la hora de analizar, los resultados serán erróneos.
Una vez obtenidos los unique() del histórico, estos son el tipo de diferencias que deberían de figurar como el mismo plato:

*

*"quesadilla de jamón york y nachos con queso y guacamole"

*"quesadilla de jamón york y queso con nachos y guacamole"

*"quesadilla de jamón york, y nachos con queso y guacamole"

*

*'Albóndigas con espaguetis'

*'Albóndigas con Espaguetti'

*'Espagueti con albóndigas'

*'Espaguetis con albóndigas'

*'Espaguettis con salsa de tomate y albóndigas'

*

*"arroz a la cubana"

*"arroz a la cubana (1 huevo frito/ración)"

*"arroz a la cubana (plato maestro)"

No obstante, hay platos que aunque sean muy similares se deben conservar como diferentes. En el siguiente ejemplo, solamente "crema de puerro" y "crema de puerros" serían el mismo plato, mientras que con el resto se desea conservar dicha diferencia:

*

*"crema de puerro y patata"

*"crema de puerro"

*"crema de puerros"

*"crema de puerro y calabacín"

*"crema de puerro y calabacín con quesito"

*"crema de puerro y calabaza"

He utilizado el paquete fuzzybuzzy, con el que he podido iterar cada uno de los unique() con el resto, devolviendome ratios de similitud (fuzz.ratio y fuzz.partial_ratio). Un ejemplo de las entradas que más parecidas a "crema de puerro":

*

*crema de puerro || 100 || 100

*crema de puerro y calabacín || 100 || 71

*crema de puerro y calabacín con quesito || 100 || 56

*crema de puerro y calabaza || 100 || 73

*crema de puerro y patata || 100 || 77

*crema de puerros || 100 || 97

*gourmet - bocadillo de crema de queso || 83 || 46

*sandwich de pavo y crema de queso || 83 || 50

*tomates rellenos de atún y crema de queso || 83 || 43

He leído también sobre la distancia de Levenshtein, pero no sabría cómo aplicarlo.

A: Lo mas sencillo que se me ocurre es probar por eliminar las stopwords(signos, pronombres, artículos, preposiciones, etc.) de cada platillo, (entre mas stopwords consideres podria ser mas optimo pero no siempre, ten cuidado con esa parte) y ordenarlos por palabra, de esta manera siento que se solucionaría en gran medida el problema.
Para el primero ejemplo quedaría así
stopwords = [" de ", " o ", " y ", " con ", " la ", " su ", " en "]
signos = [",",".","!"]

platillos = [
    "quesadilla de jamón york y nachos con queso y guacamole",
    "quesadilla de jamón york y queso con nachos y guacamole",
    "quesadilla de jamón york, y nachos con queso y guacamole"
]

for i in range(len(platillos)):
    platillos[i] = platillos[i].lower()
    for word in stopwords:
        platillos[i] = platillos[i].replace(word," ")

    for sig in signos:
        platillos[i] = platillos[i].replace(sig,"")

    platillo_lista = sorted(platillos[i].split(" "))
    platillos[i] = " ".join(platillo_lista)
    print(platillos[i])

La salida obtenida seria la siguiente:
guacamole jamón nachos quesadilla queso york
guacamole jamón nachos quesadilla queso york
guacamole jamón nachos quesadilla queso york

Tambien puedes aplicarle a toda la cadena un lower() que convierte todo en minúsculas o un upper() para mayúsculas y así evitar que te las procese como cadenas diferentes.
Ahora para los casos donde se están escribiendo diferentes las palabras como por ejemplo Espagueti y Espaguettis podrías usar un lematizador, el cual toma la raiz (lema) de una palabra dada, es decir para palabras como programa, programador, programando el lema podría ser program
Hay un paquete en python llamado nltk, que contiene herramientas para el lenguaje natural y hace este proceso mas sencillo el cual te pude servir para esos casos.
Te pongo unos ejemplos de palabras lematizadas con este paquete.
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("spanish")

palabras = ["correr", "corriendo", "corre", "programar", "programando","programa"]
lema =  [stemmer.stem(palabra) for palabra in palabras]
print(lema)

Y esta es la salida del codigo:
['corr', 'corr', 'corr', 'program', 'program', 'program']

Aun así con palabras mas complejas puede que no funcione, de cualquier manera te dejo una liga donde puedes encontrar información así como la pagina oficial del paquete, donde hay muchas herramientas y podrás encontrar mas métodos o los parámetros adecuados para tu problema.
Pagina oficial
Información de lematizador en su pagina oficial
Tutorial completo en ingles
Espero te pueda servir de algo.
Saludos


text:
Q: Sublime Text: Make cursor stay put upon pasting? For example:

somestuff

somemorestuff

somestuff

somestuff

somestuff

somestuff

somestuff

Want to assign class="abc" to each one.
Now I realize there is the Ctrl+Alt+Arrows to "carve" out a vertical path of cursors (neat trick!) after which point I can paste in my class, but that won't work if my div's are separated by some lines.
So I'd like to paste:

somestuff

somemorestuff

somestuff

somestuff

somestuff

somestuff

somestuff

But it puts my cursor HERE

somestuff

I'd like for it to stay here

somestuff

so that I can just repeat ↓Ctrl+V

A: What I would do would be to select <div, then do CTRL+D to select each identical text.  Then you can move your cursor on every one accordingly.

A: I think that the best way to achieve what you need is to use command split selection into lines, Ctrl+Shift+L (Cmd+Shift+L on Mac).

*

*Select all the lines that you need to edit

*Press Ctrl+Shift+L

*Move the cursors (with arrow keys) in the position where you want to paste your code

*Paste your code.

If you really want the the cursor to stay at the beginning of the pasted text, you can create a plug-in. Tools/New Plugin...:
import sublime_plugin

class PasteAndResetCursorPositionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        start_region = self.view.sel()[0]
        self.view.window().run_command("paste")
        self.view.sel().clear()
        self.view.sel().add(start_region)

Save this in your Packages/User directory.
Then add the key binding to your Key Bindings - User:
{ "keys": ["ctrl+alt+shift+v"], "command": "paste_and_reset_cursor_position" }

Of course you can use the shortcut that you prefer.

A: I like the plugin solution, and think that there's one more solution worth mentioning, especially since the question specifically calls for the simplicity of just hitting "down, ctrl+v" repeatedly...
Put your cursor where you want to enter the text, and use shift+ctrl+down to "multiply" your cursor points onto as many lines as necessary. Type what you want, and hit esc to return to a single point cursor.
Similar to @derek_duncan's answer, but with more granular control, assuming the text you're editing is lined up as in your example.


text:
Q: How do I fix this simple CSS floating issue in IE? I've got four div elements floated to the left. The third div is cleared.
In Firefox and Chrome the elements are positioned as expected: The first and second divs are adjacent to each other and are above the third and fourth divs which are also adjacent to each other.
IE7 on the other hand places the fourth div adjacent to the first and second divs with the third div below.
I know I can fix it by adding a br element after the second div but I'd rather not edit the markup if I don't have to. Is there a more elegant way of fixing the problem?
I've been trying to Google for a fix for a while now but haven't found one, which is rather surprising considering how elementary the problem seems. Perhaps I'm missing something obvious, is there a reference site that lists simple CSS issues like this one or am I just ignorant about basic CSS?
Edit: I've made the sample code slightly more complex after Nazgulled "solved" the problem (see the comments). There are now four divs instead of three and the third div is cleared instead of the second.
Here is the complete source code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

one

two

three

four

Here is what is looks like in Chrome:

Here is what is looks like in IE7:

A: I don't know if this fixes your real problem, but I fixed your sample like this:

*

*Remove the float attribute from div

*Remove the clear attribute from #divtwo

*Add float: left to #divtwo and #divthree
This makes it look like your chrome sample both in Firefox and IE 7 (browsers I tested).

A: Several months later...
I gave up on trying to solve this problem with CSS alone. This is an IE7 bug that you cannot avoid without touching your HTML.
The ultimate application of this floating pattern was in a form, where two of the divs were input elements and the other two divs were their corresponding labels. The pattern was used multiple times in a large form and I really wanted to find an elegant CSS-only solution.
I eventually ended up using the Object Oriented CSS Framework and wrapping all the elements with additional divs in order to create the desired layout, as OOCSS dictates. It was the only way to save my soul from IE7's CSS hell and OOCSS is not so bad once you complete your initial layout.

In truth, the general answer is that this is the sort of question you pose when you don't really know what you're doing with CSS. If you have to create a complex layout once in a blue moon then you probably don't know what you're doing; as was the case when I asked this question.
Although it is true that IE7 fails to render the CSS properly, it was also a case of mistaken scope on my part. CSS is not the ultimate layout language that a naive programmer would make it out to be and CSS is not truly independent of the structure of your HTML. Once again I've opted to take the easier way out by using the OOCSS framework when I should actually take the time to learn the fundamentals of CSS.
Alas, such is the consequence of deadlines.

A: I am unsure what your ultimate goal is here, but I would suggest enclosing all four
s inside a container element and applying a width to it, then removing the clear style from #divthree.  Doing it this way will allow #divthree and #divfour to move below #divone and #divtwo without clearing them:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>IE Float Test</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

one

two

three

four

The zoom property on #container is necessary to avoid the IE6/7 Escaping Floats Bug.
If the above solution isn't viable, you can add a
 or
 after #divtwo with the style clear: left;:

one

two

three

four

This is the technique used in a floated page layout example on westciv.com.

A: Try adding:
display:inline-block;

in #divtwo.  If that works, I would of course add some conditional commenting for IE7


text:
Q: One game center account for two iOS apps Anyone knows what I need to do to have both my free and paid versions feed the same Game Center leader board?

A: I'm afraid that's not possible, because the Game Center uses the application's "bundle identifier" (such as com.myCompany.myCoolGame) to identify a game -- and two apps cannot have the same identifier.
That's at least the status in iOS 4.1.

A: Provide a complete app, but disable features. Then use an in-app purchase to unlock these functionality. This way, 'both' Apps will have the same identifier.

A: Starting from iOS 6.0 there is a functionality called Game Center Groups. You can set these groups in iTunes Connect and assign multiple applications to them. This way they can share leaderboards and achievements.


text:
Q: How to validate mobile app facebook/google access token on spring boot 2.0 OAuth2 Authorization server? I'm trying to validate Android/iOS client phone number or email address using Facebook Account-Kit service. I'm not sure how to validate the authorization code or access token with spring boot based back-end server and return the my own access token.
Between, I have gone thorough this blog https://www.baeldung.com/spring-security-5-oauth2-login, but it session based. I'm not clear how to change this to stateless  (e.g /oauth/token).
Could anyone please let me know how to solve the issue ?
Reference : [https://developers.facebook.com/docs/accountkit/graphapi][1]
Here is my code :
@Configuration
@EnableOAuth2Client
public class SocialConfig extends WebSecurityConfigurerAdapter {

@Autowired
OAuth2ClientContext oauth2ClientContext;

private String[] PUBLIC_URL = { "/*", "/api/v1/account/validate", "login/accountkit", "/api/v1/account" };

@Override
protected void configure(HttpSecurity http) throws Exception {
    // super.configure(http);
    http.authorizeRequests()
    .antMatchers(PUBLIC_URL).permitAll()
    .anyRequest().authenticated()
    .and().csrf()
    .disable()
    .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);

}

private Filter ssoFilter() {
    OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
            "/login/accountkit");
    OAuth2ProtectedResourceDetails accountkit = accountKit();
    OAuth2RestTemplate template = new OAuth2RestTemplate(accountkit, oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices userInfo = new UserInfoTokenServices(accountKitResource().getUserInfoUri(),
            accountkit.getClientId());
    userInfo.setRestTemplate(template);
    filter.setTokenServices(userInfo);
    return filter;
}

@Bean
@ConfigurationProperties("accountkit.client")
protected OAuth2ProtectedResourceDetails accountKit() {
    AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
    resource.setAccessTokenUri("https://graph.accountkit.com/v1.2/me");
    resource.setUserAuthorizationUri("https://graph.accountkit.com/v1.2/access_token");
    resource.setClientId("AA|xxxx|xxx");
    resource.setGrantType("authorization_code");
    resource.setTokenName("access_token");
    resource.setAuthenticationScheme(AuthenticationScheme.form);
    resource.setPreEstablishedRedirectUri("http://localhost:8080/login/accountkit");
    return resource;
}

@Bean
@ConfigurationProperties("accountkit.resource")
protected ResourceServerProperties accountKitResource() {
    return new ResourceServerProperties();
}

}


text:
Q: Difficult definite integral with a possibly real finite answer
I'm stumped here.The interval of integration would make me think to look for symmetry, but it's clearly not even or odd. I asked wolfram alpha to get any ideas, and it gave me a complex number as the value of the integral, which makes no sense. The graph seems to enclose a finite area in the interval, making me think it has a real finite answer. How do I solve this?


text:
Q: Select to constructor OneToMany relationship in QueryDsl I want to select elements from a database using QueryDsl.
    final QUserEntity user = QUserEntity.userEntity;
    new JPAQuery<UserResponse>(em)
                    .select(Projections.constructor(User.class, user.id, user.name,
                            Projections.constructor(AddressResponse.class, user.address.id, user.address.name),
                            user.pets))
                    .from(user).fetch();

I want this to use the constructor in User:
public UserResponse(final String id, final String name, final AddressResponse address, Set<pets> pets) {
    this.id = id;
    this.name = name;
    this.address = address;
    this.pets = pets;
}

The user and address works fine, but I don't know how to handle the pets, which is a OneToMany-entity and thus a set of entities.
'Pets' has the following relation in User:
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = 'petId', referencedColumnName = 'petId')
private Set<Pet> pets;

However, when I try to run this a I get the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'as'.

And the generated SQL has a syntax error:
SELECT
  chargepoin0_.userid    AS col_0_0_,
  chargepoin0_.username  AS col_1_0_,
  chargepoin0_.addressid   AS col_2_0_,
  addressent5_.addressname AS col_3_0_,.AS col_4_0_, pets6_.itemid AS itemid1_4_, pets6_.connected AS connecte2_4_, pets6_.objectstatecode AS objectst3_4_ FROM user user0_

Thanks in advance,
Markus


text:
Q: Is this a properly formatted POST request? Is the below code a properly formatted POST request? It seems as those the entire contents are being passed via the URI and not via POST. I only have a very primitive understanding of PHP and URL requests in general so the server-side code has been included below as well.
I noticed this was an issue while attempting to upload base64 encoded images (as demonstrated below) to the server. Upon submitting the request, the server would return an error stating the that URI exceeds the maximum length, which leads me to believe that this isn't a proper approach to submitting a POST request. The entire process works if the image is only 10x10px, but that isn't going to do the trick and the main priority here is understanding the correct approach.

*

*What is the proper approach to submitting a POST request, similar to the below example?

*How can the POST data be received by the server and will the JSON need slashed stripped if it is properly submitted via POST?

Swift
if let imageData = UIImagePNGRepresentation(self.image!) {
            let encodedImage = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    let dict = ["barcode":self.barcode, "imageData":encodedImage]

    let json = JSONStringify(dict, prettyPrinted: false)
    let jsonEncoded = CFURLCreateStringByAddingPercentEscapes(
        nil, json, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue)

    let server:String = GlobalVars.serverAddress
    let phpFile:String = "/php/Inventory/UpdateItemImage.php"
    let baseURL = NSURL(string: "\(server)\(phpFile)")
    let url = NSURL(string: "?json=\(jsonEncoded)", relativeToURL: baseURL)
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)
    request.HTTPMethod = "POST"
    let dataString = ""
    let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPBody = requestBodyData
    var response: NSURLResponse? = nil
    do {
        let reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
        return true
    } catch {
        return false
    }
}

PHP
<?php
    // Setup DB connection etc..
    //..
    //Define passed variables
    $json = $_GET['json'];
    $json = stripslashes($json);
    $fieldArray = json_decode($json);
    $barcode = $fieldArray->{"barcode"};
    $imageData = $fieldArray->{"imageData"};
    // etc....
?>


text:
Q: Windows.h cannot be found using Winemaker/Winelib currently i'm trying to port a Windows program to Linux, more specific a DLL. The code is written in C++ and uses many Winapi calls. Since i don't want to rebuild the whole thing from scratch i thought recompiling with Winelib is a good start and worth a try but i have never used it before. So i used Winemaker to prepare the code and create a Makefile. Using make prints out an error that says windows.h cannot be found. Well, i'm using Ubuntu right now, so of course it can't be found but i thought using wineg++ would take care of such things by underlaying a wineapi-layer.
I read the Winelib Userguide but it seems like i don't really get the concept.  What am i missing here? This surely won't be the last Problem i'm encountering with Winelib

A: It's not a perfectly fitting solution but drdobbs.com posted in interesting article about wine, winelib and porting to Linux here.
So using winemaker and wineg++ is a good start but one also have to add the Compiler directive -Iwine/include. there are the equivalents to windows.h etc. hidden.
It also says that code compiled that way still needs Wine to work properly to ensure that hardcoded paths like C:\Program Files\... are still available. If These aren't existing, it may work without Wine, but i'm absolutely NOT sure about this.


text:
Q: Adsense not displaying on HTC Hero We've been developing an Android application which includes Google Adsense. However there seems to be a problem with the ads not showing on HTC Hero phones. It does show on HTC Magic. Have anyone else had the same problem? Are there any Hero-specific settings which is needed?

A: Sure, It used to be a common problem in the early stage of AdSense SDK for Android. But now they have fixed it. Actually it was fixed in early january 2010. Shame on me for not seeing your question before now...
;-)


text:
Q: Linq To Objects, List, where Items consist of List I have List<Book>, where
public class Book
{
    public string Name {get; set;}
    public List<Author> Authors {get; set;}
}

public class Author
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

I need to get <FirstName, BooksCount>, for each author count number of books.
I understand, that I need to use GroupBy, but get List<Author> instead of  <FirstName, BooksCount>.

A: Give this a try. I'm groupping by FullName instead of FirstName, because i highly doubt FirstName could be unique identifier. FullName is better, but still could not be unique. You could change .GroupBy(a => $"{a.FirstName} {a.LastName}") to .GroupBy(a => a.FirstName") if you want
            List<Book> books = new List<Book>() {
            new Book { Name = "b1",
                Authors = new List<Author>() {
                    new Author { FirstName = "a1fn", LastName = "a1ln" },
                    new Author { FirstName = "a2fn", LastName = "a2ln" } }
            },
            new Book { Name = "b2",
                Authors = new List<Author>() {
                    new Author { FirstName = "a1fn", LastName = "a1ln" } }
            }, new Book { Name = "b3",
                Authors = new List<Author>() {
                    new Author { FirstName = "a2fn", LastName = "a2ln" } }
            }, new Book { Name = "b4",
                Authors = new List<Author>() {
                    new Author { FirstName = "a2fn", LastName = "a2ln" } }
            } };

            var result = books.SelectMany(b => b.Authors)
                .GroupBy(a => $"{a.FirstName} {a.LastName}")
                .Select(g => new { FullName = g.Key, BooksCount = g.Count() });

A: Apparently some Books are written by several Authors.
You have a sequence of Books written by one or more Authors, and you want a method to transform this sequence into a sequence of Authors with the Books the wrote.
Book     Author(s)
  A      author1
  B      author2
  C      author3
  D      author1, author3
  E      author2, author3

We'll first flatten it: get combinations [Book, Author], then group by the same Author:
After Flatten:
 Book    Author(s)
  A      author1
  B      author2
  C      author3
  D      author1,
  D      author3
  E      author2,
  E      author3

After Group by same Author:
Author      Books
author1     A, D
author2     B, E
author3     C, D, E

Flattening is done using SelectMany
Making groups of items where every group member has a common value is done using GroupBy
IEnumerable<Book> books = ...
var authorsWithTheirBooks = books.SelectMany(book => book.Authors,

    // parameter ResultSelector: take every [book, author] combination to make one new
    (book, author) => new
    {
        Book = book,
        Author = author,
    })

    // now make groups with same Author:
    .GroupBy(flattenResult => flattenResult.Author,

    // resultSelector: take every author, and the books of this author to make one new
    (author, booksOfThisAuthor => new
    {
        Author = author,
        Books = booksOfThisAuthor.ToList(),
    });

Well, you don't want all books of this author, you only want the number of books:
    (author, booksOfThisAuthor => new
    {
        Author = author,
        Books = booksOfThisAuthor.Count(),
    });


text:
Q: Standardization for regularized, sparse hashed logistic regression As the question states, I'm fitting large, sparse logistic regressions (with hashed interactions, a la vowpal wabbit) for a machine learning system.  The features are on different scales, and I'm a little nervous that dividing by the feature standard deviation really isn't suitable, because it seems that features that are mostly zero but are occasionally very large (I have a number of these) aren't scaled enough.  Since I have a number of hash collisions, it seems that the large values might be effectively 'swamping' the larger ones.
So, my question is: what is the advantage of scaling by the standard deviation (or root-mean-squares) instead of just dividing each feature by its maximum value, which would scale everything to the unit interval? Thanks for any help.
(note: I can't center features as that would destroy the sparsity)

A: Its bad policity to normalize by the maximum value since the maximum is likely to change as you observe more data, thus your normalization would be inconsistent.

A: Recent Edit: Speaking directly to your comment "(note: I can't center features as that would destroy the sparsity)," actually that's not necessarily true. I've recently learned there are easy ways to have non-zero-based sparse data storage (in this case the base could be the center that you shift your data by). Something to look into...

It's not uncommon in data that exhibit sparsity (or in data that are not as smooth and well-behaved as Euclid would like) for measures such as standard deviation to be misleading or contaminated by outliers. Your intuition is correct: the variance estimator does emphasize larger values.
One solution to this problem is to consider using a robust measure of standard error. For example, consider some function of the absolute deviation—this will provide an estimate of variation or error that is far less susceptible to the extremities you see in your data.
Why not use the max? Think about stability for a moment. If you standardize by using the standard deviation and move (i.e. perturb) your data around just a bit, it's likely your standardization won't change at all because all those movements will sort of cancel out. However, if you standardize by maximum (or more accurately, $\|\cdot \|_\infty$) and again move your data around a bit, your estimate of the normalizing constant (the max) will change tremendously. Why? Because it only depends on one value (the biggest value), whereas the variance depends on all of your observations. In other words, it's sensitive, but in a different way than variance is. It's sensitive in the sense that it's unstable. Variance on the other hands has, under certain conditions, the highest level of stability of any estimator of spread, but it lacks robustness. Thus, you as a practitioner and data scientist need to strike the balances between these two kinds of estimator sensitivity—statistical efficiency and robustness. And that's why I recommend the using the absolute deviation $\|\cdot\|_1$.
In case you're wondering: Why do we standardize? Because, with several measurements that aren't naturally on the same scale, it's not easy to know what is extreme and not extreme. For example, you may have data on car speeds and airplane ground speeds per geographical region. You may see that, for a particular region, the city's car speed is perhaps 100km/hr while for an airplane, it's something like 800km/hr. Can you really compare thesd quantities and say that people in this area drive slow and fly fast? Not at all. In fact, this car speed is far above average, and the airplane ground speed is far below average. Therefore the goal of standardizing (which should truly be called normalizing) is to compare things to what is normal.


text:
Q: How can I print the entire database I have a table called ClientsTable and a database called myDb .
How can I print with System.out.prinln() the entire database ? I just want to select all the rows and present all the fields to the screen .
Thanks
EDIT: what should I put instead of rs.getString() , here (since it doesn't compile):
    ResultSet rs = this.m_statement.executeQuery("SELECT * FROM CheckingAccountsTable");
    while (rs.next())
        System.out.println(rs.getString());

A: if you don't know how many colums are in the table, try something like this :
    ResultSet rs = this.m_statement.executeQuery("SELECT * FROM CheckingAccountsTable");
    int columnCount = rs.getMetaData().getColumnCount();
    while (rs.next()) {
        for (int i = 1; i <= columnCount; i++) {
            System.out.print(rs.getString(i));
        }
        System.out.println();
    }

A: The SQL query would be:
SELECT * FROM DB_TABLE_NAME

Then you can loop through your result set and print it out.
Edit:
You aren't specifying what column you want to print out.
Example below:
System.out.println(rs.getString("COLUMN_NAME"));

Second edit:
ResultSet rs = this.m_statement.executeQuery("SELECT * FROM CheckingAccountsTable");
int colCount = rs.getMetaData().getColumnCount();
while (rs.next()){
    for(int i = 1; i < colCount + 1; i++){
       System.out.println(rs.getString(i));
    }
}


text:
Q: Why does Stripe API output "Request metrics buffer is full, dropping telemetry message."? In Node v12 with the Stripe API client v, I am running a client.getSubscription() call on about 200 items in a loop.
I get this message in the output (--trace-warnings is turned on):
Getting subscription data for a@email.com...
Getting subscription data for b@email.com...
Getting subscription data for c@email.com...
(node:25078) Stripe: Request metrics buffer is full, dropping telemetry message.
    at Object.emitWarning (/home/nick/src/project/node_modules/stripe/lib/utils.js:437:18)
    at Constructor._recordRequestMetrics (/home/nick/src/project/node_modules/stripe/lib/StripeResource.js:370:15)
    at IncomingMessage.<anonymous> (/home/nick/src/project/node_modules/stripe/lib/StripeResource.js:192:14)
    at Object.onceWrapper (events.js:481:28)
    at IncomingMessage.emit (events.js:387:35)
    at IncomingMessage.emit (domain.js:470:12)
    at endReadableNT (internal/streams/readable.js:1317:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)
(node:25078) Stripe: Request metrics buffer is full, dropping telemetry message.
    at Object.emitWarning (/home/nick/src/project/node_modules/stripe/lib/utils.js:437:18)
    at Constructor._recordRequestMetrics (/home/nick/src/project/node_modules/stripe/lib/StripeResource.js:370:15)
    at IncomingMessage.<anonymous> (/home/nick/src/project/node_modules/stripe/lib/StripeResource.js:192:14)
    at Object.onceWrapper (events.js:481:28)
    at IncomingMessage.emit (events.js:387:35)
    at IncomingMessage.emit (domain.js:470:12)
    at endReadableNT (internal/streams/readable.js:1317:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)
(node:15748) Stripe: Request metrics buffer is full, dropping telemetry message.
...

I think this error is coming from an underlying library that Stripe is using, since I cannot find any information on Google or Stripe's docs with that specific error in it.
It also does not appear to be a critical error, the calls succeed.

A: This is a warning that's emitted from stripe-node when request telemetry can't be sent because the buffer is full: https://github.com/stripe/stripe-node/blob/12ebce4220c22e1e1a6a0480ba96c2baffe01b8c/lib/StripeResource.js#L395
The telemetry is latency information which is sent to Stripe for metrics purposes.
It's safe to ignore these as they are just warnings and won't affect the actual API operations. If however they are a bit too noisy for your liking you can disable telemetry entirely with the config object:
const stripe = Stripe('sk_test_...', {
  telemetry: false,
});