text:
Q: MongoDB returns nothing when placing the model in another file I have a very basic server, which can be run in three ways:

*

*[BLOCK 2 ENABLED] / [BLOCK 1 DISABLED]
Defining interfaces, schema and model in the same file.

*[BLOCK 1 ENABLED] / [BLOCK 2 DISABLED]
Defining interfaces, schema and model in an external file: ./models/user.ts
The content of [BLOCK 2] is exactly the same as the content of file: ./models/user.ts.

*In the other hand, if I move the file: user.ts to:
./server/models/user.ts
  then the code works properly, but for some specific reasons I need it at:
./models/user.ts

Just in case here you have the repository:
https://github.com/napolev/mongodb-experiments
Here is the code:
./server/server.ts [BLOCK 2 ENABLED]
import * as mongoose from 'mongoose';
import * as colors from 'colors';
/*/
// BLOCK 1:
import { User, IUserDocument } from '../models/user';
/*/
// BLOCK 2:
import { Document, Schema, Model, model} from "mongoose";
export interface IUser {
    username:   string,
    password:   string,
    email:      string,
    company:    string,
}
export interface IUserDocument extends IUser, Document {

}
export var UserSchema: Schema = new Schema({
    username:   String,
    password:   String,
    email:      String,
    company:    String,
});
export const User: Model<IUserDocument> = model<IUserDocument>("User", UserSchema);
//*/

mongoose.connect('mongodb://localhost:9100/mongodb-experiments');

User.find({}, function(err, users: IUserDocument[]){
    console.log(users);
});

let message = colors.green('Hello') + ' '  + colors.red.bgYellow.underline('World') + ' ' +  colors.blue.bgRed('!!!');

console.log(message);

// To work with the Mongo Shell:
// $ cd /path/to/mongodb/bin"
// $ mongo --port 9100
// use mongodb-experiments
// db.users.insert( { username: "bill.gates", password: "windows", email: "billgates@microsoft.com", company: "Microsoft" } )
// db.users.insert( { username: "steve.jobs", password: "mac", email: "stevejobs@apple.com", company: "Apple" } );
// db.getCollection("users").find()

./models/user.ts
import { Document, Schema, Model, model} from "mongoose";

export interface IUser {
    username:   string,
    password:   string,
    email:      string,
    company:    string,
}
export interface IUserDocument extends IUser, Document {

}
export var UserSchema: Schema = new Schema({
    username:   String,
    password:   String,
    email:      String,
    company:    String,
});

export const User: Model<IUserDocument> = model<IUserDocument>("User", UserSchema);

Suppose we have some dummy data on the database:
$ cd /path/to/mongodb/bin"
$ mongo --port 9100
use mongodb-experiments
db.users.insert( { username: "bill.gates", password: "windows", email: "billgates@microsoft.com", company: "Microsoft" } )
db.users.insert( { username: "steve.jobs", password: "mac", email: "stevejobs@apple.com", company: "Apple" } );

If I run the server with [BLOCK 2] enabled:
$ ts-node server.ts

I get the following output:
Hello World !!!
[ { _id: 5b3561bbcde3135b908cb51b,
    username: 'bill.gates',
    password: 'windows',
    email: 'billgates@microsoft.com',
    company: 'Microsoft' },
  { _id: 5b3561c1cde3135b908cb51c,
    username: 'steve.jobs',
    password: 'mac',
    email: 'stevejobs@apple.com',
    company: 'Apple' } ]

But If I run the server with [BLOCK 1] enabled:
I just get the following output:
Hello World !!!

without the previous entries.
The only difference I see between both ways is where are defined the interfaces, schema and model.
EDIT 1
I did some experiments:
With way 1 and way 3 mentioned above, if I do:
$ cd ./server/
$ tsc server.ts
$ node server.js

then I get the expected output.
But with way 2 mentioned above, If I do:
$ cd ./server/
$ tsc server.ts

I get the following output:
node_modules/@types/mongoose/index.d.ts(61,9): error TS2300: Duplicate identifier 'NativeBuffer'.
node_modules/@types/mongoose/index.d.ts(62,9): error TS2300: Duplicate identifier 'NativeDate'.
node_modules/@types/mongoose/index.d.ts(63,9): error TS2300: Duplicate identifier 'NativeError'.
node_modules/@types/mongoose/index.d.ts(71,14): error TS2300: Duplicate identifier 'Mongoose'.
node_modules/@types/mongoose/index.d.ts(72,8): error TS2300: Duplicate identifier 'Mongoose'.
node_modules/@types/mongoose/index.d.ts(156,9): error TS2300: Duplicate identifier 'CastError'.
node_modules/@types/mongoose/index.d.ts(177,18): error TS2300: Duplicate identifier 'ConnectionBase'.
node_modules/@types/mongoose/index.d.ts(447,9): error TS2300: Duplicate identifier 'Connection'.
node_modules/@types/mongoose/index.d.ts(463,9): error TS2300: Duplicate identifier 'ValidationError'.
node_modules/@types/mongoose/index.d.ts(472,9): error TS2300: Duplicate identifier 'Error'.
node_modules/@types/mongoose/index.d.ts(562,9): error TS2300: Duplicate identifier 'VirtualType'.
node_modules/@types/mongoose/index.d.ts(579,9): error TS2300: Duplicate identifier 'Schema'.
node_modules/@types/mongoose/index.d.ts(888,5): error TS2374: Duplicate string index signature.
node_modules/@types/mongoose/index.d.ts(1018,5): error TS2374: Duplicate string index signature.
node_modules/@types/mongoose/index.d.ts(1072,13): error TS2300: Duplicate identifier 'MongooseDocument'.
node_modules/@types/mongoose/index.d.ts(1073,9): error TS2300: Duplicate identifier 'MongooseDocument'.
node_modules/@types/mongoose/index.d.ts(1275,11): error TS2300: Duplicate identifier 'Subdocument'.
node_modules/@types/mongoose/index.d.ts(1291,11): error TS2300: Duplicate identifier 'Array'.
node_modules/@types/mongoose/index.d.ts(1400,11): error TS2300: Duplicate identifier 'DocumentArray'.
node_modules/@types/mongoose/index.d.ts(1429,11): error TS2300: Duplicate identifier 'Buffer'.
node_modules/@types/mongoose/index.d.ts(1461,10): error TS2300: Duplicate identifier 'ObjectIdConstructor'.
node_modules/@types/mongoose/index.d.ts(1469,11): error TS2300: Duplicate identifier 'Decimal128'.
node_modules/@types/mongoose/index.d.ts(1475,11): error TS2300: Duplicate identifier 'Embedded'.
node_modules/@types/mongoose/index.d.ts(1515,9): error TS2300: Duplicate identifier 'Query'.
node_modules/@types/mongoose/index.d.ts(1516,9): error TS2300: Duplicate identifier 'DocumentQuery'.
node_modules/@types/mongoose/index.d.ts(1948,9): error TS2300: Duplicate identifier 'mquery'.
node_modules/@types/mongoose/index.d.ts(2000,13): error TS2300: Duplicate identifier 'Schema'.
node_modules/@types/mongoose/index.d.ts(2248,9): error TS2300: Duplicate identifier 'Aggregate'.
node_modules/@types/mongoose/index.d.ts(2411,9): error TS2300: Duplicate identifier 'SchemaType'.
node_modules/@types/mongoose/index.d.ts(2864,5): error TS2374: Duplicate string index signature.
node_modules/@types/mongoose/index.d.ts(2966,5): error TS2374: Duplicate string index signature.

I think there are conflicts because the directory: ./models/ has its own node_modules directory.
Do you think is there a way to NOT include the dependencies:
{mongoose, @types/mongoose} on the ./server/ directory and just do it on the ./models/ directory to prevent these conflicts?
Any idea on how to make the way 2 work?
Thanks!


text:
Q: Filter MYSQL results based on a LEFT JOIN I am trying to filter results based on a left join so that IF the join is successful it only pulls the matching record. But I am just getting a blank result.
Table users
user_id | user_name

Table skills
skill_id | user_id | boss_id | date_acquired

The statement I am trying to use (PDO in PHP)
SELECT
    users.user_id,
    users.user_name,
    skills.date_acquired
FROM
    users
LEFT JOIN skills ON
    users.user_id=skills.user_id
    AND
    boss_id=?
WHERE
    user_id=?

In my execute statement I have insured that I have values for both parameters. I get the user but not the date_acquired field and I am sure there is an entry that matches the parameters. Am I joining incorrectly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is time complexity of update in binary heap? For a binary heap we have O(log(n)) for insert, O(log(n)) for delete min and heap construction can be done in O(n).
In the context of using a binary heap in Djikstra, my exam paper involved an "update" in the heap where the priority of a vertex is changed.
I assumed that the time complexity of this update would be O(n) since it seemed to me that locating the vertex in the heap would require something in the order of a linear search, followed by an upheap or downheap. This would be O(n + log(n)) which is simply O(n).
Unfortunately I think this lead me to the wrong answer.
So, what is the actual time complexity of a priority update in a binary heap?

A: The key to resolving your problem is to return a special object on the insertion of a element. When you move the real object in the heap, you update the position in this object.
To call decrease-priority you pass this object so you can go right to the position in the heap and bubble up the element if necessary.
In this way it's O(log(n)). In fact finding the element is O(1) and restoring the heap property is O(log(n)).
P.s. You should check whether the new priority actually decreases.

A: I'm going to disagree a bit with Scara95.  With out context of your answer this seems like whether or not your answer is wrong could possibly be a matter of pedantry.  Technically, yes, its not O(N) + O(log(N)) because it is possible to find the location of elements in constant time.  However, this requires an entirely different data-structure to go along with your binary heap.  You have to map inserted elements to a hash table, such that when you insert elements into the priority you also insert a new entry into the hashtable, a unique hash of the element you just inserted, with the location as the value.
To update, you query the hashtable with the ID of the element in the priority queue you want to update, and grab the hashtable elements value to find out where to update the priority queue element, where you percolate up/heapify up / down
But at this point, you no longer have just a binary heap, you have a binary heap and a hash-table, arguably a new data structure as the actual functions to update the heap can't be separated from the two data-structures.  You can actually implement binary heaps where the update complexity can't get better than O(N) given that you simply don't include a hashtable.  Often you'll even find papers on new algorithms/data-structures are actually the same data structures but with new components often other datastructures mixed in the same way the hash-table would have to be, so this makes this whole exercise extra confusing.
Bottom line is that if the question asked you about what the best possible update complexity would be for a binary heap, your answer was wrong, no questions asked, but if the question was more specific in terms of what you guys talked about in class, talking about a binary heap formed in a specific way, things get a lot more complicated.


text:
Q: Why are interemdiate "filters" of SI "pipes-and-filters" architecture called Message Endpoints? A fragment from doc

A Message Endpoint represents the "filter" of a pipes-and-filters
  architecture. As mentioned earlier, the endpoint's primary role is to
  connect application code to the messaging framework and to do so in a
  non-invasive manner. In other words, the application code should
  ideally have no awareness of the message objects or the message
  channels.

Transformers, Filters, Service Activators are all Message Endpoints.
What I don't understand is why they are called so as an application actually can send messages into input channels and these "endpoints" are used in the middle of the chain. In other words, the app is aware about a channel, and not about endpoints.
Example:
@SpringBootApplication
@IntegrationComponentScan
public class SendToInputChannel {

    @Bean
        public IntegrationFlow flow() {
            return IntegrationFlows.from("input")
                .handle(System.out::println).get();
        }

    public static void main(String[] args) throws IOException {
        ConfigurableApplicationContext ctx = SpringApplication.run(SendToInputChannel.class, args);

        MessageChannel inputChannel = ctx.getBean("input", MessageChannel.class);
        for (int i = 0; i < 10; i++) {
            inputChannel.send(MessageBuilder.withPayload(i)
                .build());
        }

        ctx.close();

    }

}

A: Ekaterina, It all started from the Enterprise Integration Patterns (EIP) book and Spring Integration (SI) is effectively a Reference Implementation of the EIP. We were trying to stay pretty close to "that script". So as you can see from this excerpt - Message Endpoint is used to connect an application to a messaging channels. In other words SI in itself is a messaging framework since it provides internal channels to which various Filters/Endpoints could be connected.
Keep in mind that MessageChannel is an interface and could represent not only the internal channels implemented in SI. For example one can implement a MessageChannel interface that provides some proxy to a JMS queue or anything else, while Filters/Endpoints will remain the same/unchanged.
I can go on, but I hope that is enough for now, but fee free to follow up.


text:
Q: R filter per group for first and last timepoints only I have a dataset with column names ID, date, coverage. Each ID has a different number of dates. Coverage is an integer 0-3. I want to filter this dataset so that coverage==3 for the earliest and last time point only.
Example input:
ID date coverage
001 2012-12-24 2
001 2013-12-04 3
001 2014-12-14 1
001 2015-12-02 3
001 2016-12-02 0
002 2012-01-15 3
002 2013-11-15 1
002 2014-11-15 3
003 2019-01-15 1
003 2020-11-15 1
003 2021-11-15 3

Example output:
ID date coverage
001 2013-12-04 3
001 2014-12-14 1
001 2015-12-02 3
002 2012-01-15 3
002 2013-11-15 1
002 2014-11-15 3
003 2021-11-15 3

A: We arrange the 'ID', 'date', grouped by 'ID', slice the rows from the first coverage of 3 value to the last.  Note that if there are no 3 values in coverage, we may need a condition to either drop the IDs by having an if/else condition with else returning NULL (or if we want the full data rows for those IDs, use row_number())
library(dplyr)
df1 %>%
   arrange(ID, date) %>%
   group_by(ID) %>%
   slice(if(3 %in% coverage)
      match(3, coverage):last(which(coverage == 3)) else NULL)  %>%
   # if we want to keep the full rows
   #  slice(if(3 %in% coverage)
   #    match(3, coverage):last(which(coverage == 3)) else row_number())  %>%
   ungroup

-output
# A tibble: 7 × 3
     ID date       coverage
  <int> <date>        <int>
1     1 2013-12-04        3
2     1 2014-12-14        1
3     1 2015-12-02        3
4     2 2012-01-15        3
5     2 2013-11-15        1
6     2 2014-11-15        3
7     3 2021-11-15        3

data
df1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), date = structure(c(15698, 16043, 16418, 16771, 17137, 15354,
16024, 16389, 17911, 18581, 18946), class = "Date"), coverage = c(2L,
3L, 1L, 3L, 0L, 3L, 1L, 3L, 1L, 1L, 3L)), row.names = c(NA, -11L
), class = "data.frame")


text:
Q: Dont try to evaluate data-bind before variable is set In knockout is there a way to tell it to wait with evaluating certain parts of the html until a value is set?
This first method is what I currently do to make it work and the bottom one is what I would like to have (or similar).

I'm certain someone has been annoyed at this before and solved it.. if it's not already built in and Im just not finding it.
Edit: for some more context. The Observable thing is defined like this: model.ObservableThing = ko.observable(); and it is set by a jQuery.Get call at some point by this code: model.ObservableThing (resultData);

A: Was easy enough, use an if.

and it all works.

A: Since 'ObservableThing' is a complex object, bind it using a with binding and all descendants can be bound to 'ObservableThing's properties. It'll be cleaner and better than using an if as knockout will determine when to render 'ObservableThing' and its elements.

have a look at this link for more info: http://knockoutjs.com/documentation/with-binding.html


text:
Q: Apache HttpComponents EntityUtils memory leak? I executed a 12-hour load test on my Java servlet-based server (Java 1.7 running under WebLogic 12 and Oracle Enterprise Linux). After test has finished, I observed that the memory consumption gradually went up from 500Mb in the beginning of the test to around 3.5Gb (and fluctuated there +/- 500Mb for several hours). 3 days later (server was doing nothing during these 3 days) - I examined memory again, and noticed that nothing out of these 3.5Gb was freed.
To make sure GC is executing, I mad explicit GC using jcmd:

*

*GC.run

*GC.run_finalization

*GC.run

Then, I made a heap snapshot and analyzed with YourKit analyzer (same results with jvisualvm as well).
I noticed that I have 2.5Gb of "Unreachable" objects still being there after 3 days of inactivity. A typical object's incoming references look like this (I'm having ~700K of such objects):

I examined Apache HttpComponents code (HttpCore version 4.3.2), and I noticed the following strange code in EntityUtils.toString (which I'm using in my server):

It looks to me that since reader object is not closed - it can create references, eventually causing the leaks I'm observing.

*

*Is this a leaky code of Apache HttpCore EntityUtils?

*Any other reason to have so many unreachable objects after 3 days and after GC.run?

Thank you.

A: Consider extending AsyncCharConsumer as shown here to produce a string with response content or using a HttpAsyncResponseConsumer if need a more sophisticated response processing.
EntityUtil methods are generally intended for entities backed by a blocking InputStream. And even then I would generally recommend consuming entity content directly from the content stream instead of converting it to a string.


text:
Q: MySQL deactivated in Lampp, Xampp on Linux 12.04 I have freshly installed xampp-linux-1.8.1 on my Ubuntu 12.04 (Mint 13 maya) Operating system.
When run lampp, I get :
/opt/lampp/lampp start
Starting XAMPP for Linux 1.8.1...
XAMPP: XAMPP-Apache is already running.
XAMPP: Another MySQL daemon is already running.
XAMPP: XAMPP-ProFTPD is already running.
XAMPP for Linux started.

In the : localhost/xampp/
MySQL DataBase is Deactivated !!!
ps -aux | grep 'mysql'
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html     mysql     3159  0.0  0.9 316264 31880 ?        Ssl  16:48   0:00 /usr/sbin/mysqld
root      4745  0.0  0.0   4648   840 pts/5    S+   17:02   0:00 grep --color=auto mysql

When I tried to stop /usr/sbin/mysqld but it can't be stopped with this command !!!
/usr/sbin/mysqld stop

Please I need Help, Thanks.

A: i've resolved the issue in this way:
sudo chmod -R 777 /opt/lampp
sudo chown -hR nobody /opt/lampp
sudo chmod -R 755 /opt/lampp

then stop other mysqld running with:
sudo service mysql stop

A: Also had this issue, after troubleshooting for almost 2 hours I found that it was because of other Apache and MySQL packages also running on my system. Removed all Apache and MySQL packages and reinstalled XAMPP again. Success.


text:
Q: Matlab - effect of different sampling rates on FFT phase spectrum I am new to Matlab and still getting to grips with FFT. I am currently working on a project where I have two cosine signals, both having a frequency of 100 Hz, but the second signal is delayed by a certain time - say 0.0030 seconds.
Knowing the frequency and the time delay, the expected phase difference between the two signals should be w*T where T is the time delay. To calculate the actual phase difference, I used the FFT function and had a look at the phase spectrum for both the signals.
For a time delay of 0.0030 seconds, the phase difference should be 108 degrees. When I use a sampling rate of 1000 Hz to sample the two cosine signals I see that the phase difference between the two signals is indeed 108 degrees, but when I use a sampling rate of 1024 Hz, the phase difference is 114 degrees.
For both the cases I used a frequency resolution of 1 Hz.
Can anybody tell me why there is this discrepancy?

A: When your sampling rate is an exact multiple of the frequency of the signal, your cosine signal falls exactly in one bin of the FFT. When you use 1024 samples per second the signal is spread across multiple bins (exactly how depends on the windowing function you used). This means the frequency for which you are determining the phase shift is not exactly 100 Hz...


text:
Q: Can I check the condition and change the value of variable in ng-click ng-click="(document.getElementById('procheck1').checked)?showme=true:showme=false"

(or)
ng-click="if(document.getElementById('procheck1').checked){showme=true;}else{showme=false;}"

A: Use some function name like this , ng-click="myFunction()"  and write whole condition inside that.
  myFunction(){
    if(document.getElementById('procheck1').checked) {
      showme=true;
    } else {
      showme=false;
    }
  }

A: Try this in html page

            <input type="checkbox" id="chkPassport" ng- model="ShowPassport" ng-change="ShowHide()" />
            Do you have Passport?

            Passport Number:
            <input type="text" id="txtPassportNumber" />

and this part in controller
var app = angular.module('MyApp', [])
  app.controller('MyController', function ($scope) {
            //This will hide the DIV by default.
            $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.ShowPassport;
            }
        });


text:
Q: Trying to express a function with comprehension list, GHC attempts to make an enum of Doubles I'm trying to express the following function:
gregoryleibnitz :: [Double]
gregoryleibnitz = map mul ( zipWith (/) (map num [0..]) (map den [0..]))
    where
        mul x = 4*x
        num x = (-1)^x
        den x = 2*x+1

into the same one using a comprehension list:
gregoryleibniz :: [Double]
gregoryleibniz = map mul ([x | n <- [0..], x <- (num n) / (den n)])
    where mul n = 4*n
          num n = (-1)^n
          den n = 2*n+1

However, the one using a comprehension list catches fire with the following errors:
ej3.hs:2:38: error:
    • No instance for (Enum [Double])
        arising from the arithmetic sequence '0 .. '
    • In the expression: [0 .. ]
      In a stmt of a list comprehension: n <- [0 .. ]
      In the second argument of 'map', namely
        '([x | n <- [0 .. ], x <- ((num n) / (den n))])'
  |
2 | gregoryleibnitz = map mul ([x | n <- [0..], x <- ((num n) / (den n))])
  |                                      ^^^^^

ej3.hs:2:39: error:
    • No instance for (Num [Double]) arising from the literal '0'
    • In the expression: 0
      In the expression: [0 .. ]
      In a stmt of a list comprehension: n <- [0 .. ]
  |
2 | gregoryleibnitz = map mul ([x | n <- [0..], x <- ((num n) / (den n))])
  |                                       ^

ej3.hs:2:51: error:
    • No instance for (Fractional [Double]) arising from a use of '/'
    • In the expression: ((num n) / (den n))
      In a stmt of a list comprehension: x <- ((num n) / (den n))
      In the second argument of 'map', namely
        '([x | n <- [0 .. ], x <- ((num n) / (den n))])'
  |
2 | gregoryleibnitz = map mul ([x | n <- [0..], x <- ((num n) / (den n))])
  |                                                   ^^^^^^^^^^^^^^^^^

ej3.hs:2:52: error:
    • No instance for (Integral [Double]) arising from a use of 'num'
    • In the first argument of '(/)', namely '(num n)'
      In the expression: ((num n) / (den n))
      In a stmt of a list comprehension: x <- ((num n) / (den n))
  |
2 | gregoryleibnitz = map mul ([x | n <- [0..], x <- ((num n) / (den n))])

From what I can understand, GHC is attempting to make an Enum of Doubles...
If that is correct, how can I force it to be Integer?

A: In a list comprehension, a binding like x <- foo expects foo to be a list. But you wrote a single number there! Instead of <- binding, you can use let:
map mul [x | n <- [0..], let x = (num n) / (den n)]

or simply inline the definition of x:
map mul [(num n) / (den n) | n <- [0..]]

It's a little bit unusual to do a list comprehension and a map; instead of map f [e | ...], consider [f e | ...], so:
[mul ((num n) / (den n)) | n <- [0..]]

I'm not sure the names mul, num, den are actually doing anything to enlighten. I'd probably inline those, too.
[4 * ((-1)^n) / (2*n+1) | n <- [0..]]

Unfortunately, (-1)^n doesn't quite work out, because (^) expects its exponent to be Integral -- i.e. a type like Int, Integer, or Word that can't represent fractions. You could use (**) (check out the types of (^), (^^), and (**), they're quite instructive) or use some variant of zipping:
[4 * ((-1)**n) / (2*n+1) | n <- [0..]]
[4 * sign / (2*n+1) | (n, sign) <- zip [0..] (cycle [1, -1])]
[4 * sign / (2*n+1) | n <- [0..] | sign <- cycle [1, -1]] -- with ParallelListComp

In the latter two cases, I'd be tempted to roll the 4* into the cycle, as in:
[num / (2*n+1) | n <- [0..] | num <- cycle [4, -4]]

You could also consider modifying that first list to just have the denominators you care about in it in the first place:
[num / den | den <- [1,3..] | num <- cycle [4, -4]]

That said, after all that work to make it beautiful, it now looks so directly like a zip that I'd almost consider writing it as a list comprehension a mistake! Converting back to zip-land, we'd have:
zipWith (/) (cycle [4, -4]) [1,3..]

...and this is where I'd stop my refactoring.


text:
Q: Elastic Beanstalk, Nginx configuration with Docker I have an application working on Elastic Beanstalk. This application exports two ports of the Docker container. Nginx only takes the first one, so I have to change the configuration to add another one.
Following this post and AWS documentation I'm trying to extend nginx configuration to add another upstream, so I have created further file to do that:
files:
  "/etc/nginx/conf.d/api-port.conf":
    mode: "000644"
    owner: root
    group: root
    content: |

      upstream docker {
        server 172.17.0.2:4003;
        keepalive 256;
      }

      server {
          listen 4003;

        if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
          set $year $1;
          set $month $2;
          set $day $3;
          set $hour $4;
        }
          access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;

        access_log    /var/log/nginx/access.log;

        location / {
          proxy_pass            http://docker;
          proxy_http_version    1.1;

          proxy_set_header    Connection        $connection_upgrade;
          proxy_set_header    Upgrade           $http_upgrade;
          proxy_set_header    Host              $host;
          proxy_set_header    X-Real-IP         $remote_addr;
          proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
        }
      }

This file is deployed within the folder .ebextensions/nginx/conf.d/api-port.conf and copied to EC2 instance, but it is not working and it is not copied to /etc/nginx/conf.d either.
Any idea about what is happening?
Thanks in advance

A: You may want to move the file from .ebextensions/nginx/conf.d/api-port.conf to .ebextensions/api-port.config. That should fix the file not copied to /etc/nginx/conf.d


text:
Q: How to get visited websites history (Android)? I want to develop an Android app which can get all visited websites
Does any one know how to do it?

A: every browser does save a history for itself. so you would need an implementation for every browsers (if that is possible). and i hope most browsers encrypt the history files to make them unreadable. i wouldn't like to have an app look at my browsing history unless i explicitly permit it. but there is not android permission for that, so that wouldnt be possible. maybe there is a way to access the history files of the browsers, but that would probably need root, and i still think you shouldnt do that.


text:
Q: Genexus: Error CS0234 calling External Object with stored procedure in Gx Ev 3 U5 I'm trying to execute a stored procedure in Genexus X Evolution 3 Upgrade 5 and it doesn't generate the C# External Object code, so it gives me an error:

error CS0234: El tipo o el nombre del espacio de nombres 'SdtdynQuery' no existe en el espacio de nombres 'GeneXus.Programs' (¨falta una referencia de ensamblado?)

How can I solve this?

A: Ariel,
You could wrap the External Object Code inside a Procedure and use it that way from Transaction Rules.


text:
Q: Phonegap inappbroswer events w'ont fire i am using phonegap latest version (3.4.0) and i am trying to implement google aOuth login.
i have added the InAppbroswer plugin to my project, and tryed to use the object events (loadstart,loadstop,loaderor,exit) but is seems that they just dont fire.
my code is very simple, it looks like this:
ref  = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start' ); });

i am running the app on Ripple eulator
i have looked for solution all over the web and have'nt fine one.
so my question is if anybody know of a working sulotion for this?
Thanks for All.
UPDATE
. i have tryed inappbroswer plugin on a fresh new Phonegap app i created just for testing this, and the plugin doesn't work! my phone gap version is 3.4.0-0.19.7 and the inappbroswer version is the latest. i installed the plugin via the CLI with the command cordova plugin add org.apache.cordova.inappbrowser
Also i have tryred to run this on normal android emulator and nothing good so far..
the plugin docs is right there

A: This is not an answer to your question but rather an alternative easy solution, Its easy to use and you don't need to go about listening to browser events. https://github.com/oauth-io/oauth-phonegap


text:
Q: Discord.py bot events formatted exactly the same yet one runs and one won't run I've recently been experimenting with discord bots and the discord API, but I have come to a problem with bot events.  When made two events using the discord.py module, only one would work while the other one did not, yet both were formatted exactly the same.  Why is this happening and how can I fix this problem?  Here is my code:
@bot.event
async def on_message(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!genlifetime password'):
        global amount
        amount = message.content[len('!genlifetime password'):].strip()
        num = int(amount)
        chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        for x in range(0, num):
            authkey1 = ''
            authkey2 = ''
            authkey3 = ''
            authkey4 = ''
            for i in range(0,4):
                authkey1 = authkey1 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey2 = authkey2 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey3 = authkey3 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey4 = authkey4 + chars[random.randrange(0,35)]
            authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
            print(authkey)
            with open(keyfile, 'a') as f:
                f.write(authkey + ' LIFETIME \n')

@bot.event
async def authorize(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!activate'):
        global key
        key = message.content[len('!activate'):].strip()
        print(key)

bot.run("NTM3Mzk1NDQzNzAxNjQ1MzEz.DykoDA.x5PrEwxZ0hlY2TeCtKVlg1QsbfQ")

When I run my bot and type in !genlifetime password 10, the bot will generate 10 keys like it is supposed to, print them in the shell, and put them in keys.txt.  However, the authorize event does not work at all.  If I type in !authorize key nothing happens in the shell.  The key is not printed at all.  I even tried putting a print before the message = await bot.wait_for_message(author=message.author) but that print would not print out either.  Both events are formatted the same way, so why does one work while the other does not?

A: I am thinking that the code should maybe look like this:
@bot.event
async def on_message(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!activate'):
        global key
        key = message.content[len('!activate'):].strip()
        print(key)
    if message.content.startswith('!genlifetime password'):
        global amount
        amount = message.content[len('!genlifetime password'):].strip()
        num = int(amount)
        chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        for x in range(0, num):
            authkey1 = ''
            authkey2 = ''
            authkey3 = ''
            authkey4 = ''
            for i in range(0,4):
                authkey1 = authkey1 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey2 = authkey2 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey3 = authkey3 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey4 = authkey4 + chars[random.randrange(0,35)]
            authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
            print(authkey)
            with open(keyfile, 'a') as f:
                f.write(authkey + ' LIFETIME \n')

Although, I haven't tested this.

A: The wait_for_message calls seem superfluous: according to the docs, the message argument passed into the callbacks is the message you want. If you were to remove the calls to wait_for_message and just use the message passed in directly, it would probably work as expected.


text:
Q: Execute prepared statement in a batch in NodeJS using node-mssql? In java I can send multiple set of parameters of a parameterized query in one go (see code example below).
How can I accomplish the same result in NodeJs, using node-mssql package?
  PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");
  ps.setString(1, "John");
  ps.setString(2,"Doe");
  ps.addBatch();
  ps.clearParameters();
  ps.setString(1, "Dave");
  ps.setString(2,"Smith");
  ps.addBatch();
  ps.clearParameters();
  int[] results = ps.executeBatch();

A: You could bulk insert using request.bulk method.
This example is node-mssql driver package.

bulk (table, [options,] [callback])
Perform a bulk insert.
Arguments
table - sql.Table instance.
options - Options object to be passed through to driver (currently tedious only). Optional. If argument is a function it will be treated as the callback.
callback(err, rowCount) - A callback which is called after bulk insert has completed, or an error has occurred. Optional. If omitted, returns Promise.

Example:
const request = new sql.Request(/* [pool or transaction] */)

try {
    const table = new sql.Table('employees ') // or temporary table, e.g. #temptable
    table.rows.add(1, "John");
    table.rows.add(2,"Doe");
    table.rows.add(1, "Dave");
    table.rows.add(2,"Smith");

    const request = new sql.Request()
    await request.bulk(table);
} catch(error) {
    console.error(error.message);
}

You could read more about bulk insert here

A: Not sure if this helps.
See if it is useful:
https://blog.stvmlbrn.com/2018/07/27/dynamic-where-clauses-with-parameterized-queries-in-node-mysql.html


text:
Q: OpenCart enable / disable entire shop I once wanted to hide my OpenCart webshop from the public until I finished it.
Somewhere in the OpenCart Admin panel there was an option to enable / disable the entire shop.
Unfortunately I do not find this option anymore.
Could anybody please tell me where this option is located at?

A: *

*Login in to admin panel.

*Go to System > Settings

*Click on Edit button of your store.

*Select Server tab.

*Set Maintenance Mode: option as Yes.

This setting prevents customers from browsing your store. They will instead see a maintenance message. If logged in as admin, you will see the store as normal.
That's it.
Have a nice day !!


text:
Q: Symfony2 enable profiler but cannot reach it I am working on a Symfony2 project, I am trying to enable the profiler so i can do further debugging. I expect to see X-debug-token-link under Response Headers but i dont see it and i cant see the toolbar at the bottom of my page.
In my routing_dev.yml it seems that these options are enabled:
framework:
    router: { resource: "%kernel.root_dir%/config/routing_dev.yml" }
    profiler: { only_exceptions: true }

web_profiler:
    toolbar: true
    intercept_redirects: false

Yet I cannot reach the profiler. Is there anything I am missing...?

A: Make sure you run your application in dev or test environment. Even though the cookbook states that collect is enabled by default, I had to set it explicitly to activate the profiler. At least in version 2.7. Here's the configuration I use:
# app/config/dev/config.yml
framework:
    # activate profiler in framework
    profiler:
        collect: true

# configure profiler
web_profiler:
    # display the web debug toolbar at the bottom of pages with a summary of profiler info
    toolbar: true

    # gives you the opportunity to look at the collected data before following the redirect
    intercept_redirects: false

    # Exclude AJAX requests in the web debug toolbar for specified paths
    excluded_ajax_paths: ^/bundles|^/_wdt

Further reading:

*

*FrameworkBundle Configuration ("framework") profiler

*WebProfilerBundle Configuration ("web_profiler")

A: Make sure your app_dev.php or other entry point enables the debugging:
Debug::enable();

Also make sure your routing_dev.yml contains the profiler routes:
_profiler:
    resource: "@WebProfilerBundle/Resources/config/routing/profiler.xml"
    prefix:   /_profiler


text:
Q: How to pass an image data by implementing parcelable interface from one activity to another? i have a main activity and second activity. on click of image button in main activity, it directs to second activity and shows a 6 avatar image buttons. i should select one of them and display back onto main activity. Can someone help me do this by implementing parcelable interface to pass data between activities?
Thanks in Advance.

A: If you're passing a model back to your main activity you can convert your model automatically to implement the Parcelable interface via this tool.
If you're trying to pass back a large object in your intent you might get  TransactionTooLargeException thrown. It really just depends on the data you're passing.


text:
Q: Retrieve only left, right, propertyName from the javers Change class I am using the following code to retreive the changes made to a version in my API response
List<Change> versionChanges = javers.findChanges(jqlQuery.build()).groupByCommit()get(0).get()

It gave me the following
https://user-images.githubusercontent.com/10185101/122550135-f3223b00-d050-11eb-9cc8-72982808cd2e.png
But I don't want this entire data to go as my API response
I just want to isolate left, right, propertyName in my response
I am not able to find an API on Change.class that can do me so ..
How can I achieve this
Thank you

A: List<ChangesByCommit> changes = javers.findChanges(jqlQuery.build()).groupByCommit();
ValueChange valueChange = (ValueChange)changes.get(0).get().get(0);
String property = valueChange.getPropertyName();
Object originalValue = valueChange.getLeft();
Object newValue = valueChange.getRight();


text:
Q: Discord py, How to remove permissions using role metnion I want to remove the the role from the users in the server who have the corresponding role by using the role mention.
For example, '%remove_role@TEAM_A' removes 'TEAM_A' from the roles of people who have the role 'TEAM_A'.
I searched hard on Google, but I couldn't find an answer or a way to do it, so I made it myself, but I failed to complete it, so I wrote a question here.

*

*1st. %rmrole team name

*2nd. Check if the team name you entered is in 'role_list'.

*3rd. Remove the role of the team name entered from users on the server.

this is my code.
@bot.command()
async def rmrole(ctx, team_name):
    key = 0
    role = get(ctx.guild.roles, name=team_name)
    team_list = []
    print(role)
    # typo check
    role_list = ["TEAM_A", "TEAM_B", "TEAM_C", "TEAM_D"]
    if role in role_list:
        type_error = 1
    else:
        type_error = 0

    # remove_role
    empty = True
    if type_error == 1:
        for member in ctx.guild.members:
            if role in member.roles:
                await member.remove_roles(role)
                empty = False
        if empty:
            await ctx.send("anyone has this role.")
    else:
        await ctx.send("check the typos."

async def remove_role(ctx, role: discord.Role)

I was worried that if I write like this, users would get a lot of alarms.
Thus, in the body, I enter the name of the role in text, and I write  it in a way that scans the role in the code.
The '#remove_role' part was searched and found.
The code was executed, but the role was not removed.
I wonder where the wrong part is, and I need help to make what I want.

A: Your mistake is simple:
role_list = ["TEAM_A", "TEAM_B", "TEAM_C", "TEAM_D"]
if role in role_list:
    type_error = 1
else:
    type_error = 0

This code will always fail and lead to type_error = 0, as role is a discord.role.Role class and not a string. This means comparing the role you got via get and a string representing its name will always fail : and so, that the second part of your code that removes the role is never accessed. It works otherwise.
Instead, you want:
if role.name in role_list:
    type_error = 1
else:
    type_error = 0

Or better yet, this instead:
if role is None:
    return await ctx.send("Role doesn't exist")

...since I don't quite see the point of your code personally: if role = get(ctx.guild.roles, name=team_name) fails (i.e the role doesn't exist), role will be None, and you can easily check for it instead of comparing it against a hardcoded list.


text:
Q: How to route to static page with out change url path in asp.net mvc3 Basically,I'm trying to route to a static page like this:
http://127.0.0.1/mypage
=route to=>
A static page in my website folder maybe http://127.0.0.1/static/mypage.html
I have tried:
Add a route role:
routes.MapRoute("StaticPage", "{pagename}", new { controller = "Common", action = "StaticPage" });
Add an action in Common Controller:
 public ActionResult StaticPage(string pagename)
 {
     return Redirect("/static/" + pagename + ".html");
 }

But it will change the url and cause twice request, is there any other way(no iframe in view) to remain the url?

A: You could simply have your controller return the contents of the desired file like so:
public ActionResult StaticPage(String pageName) {
    return Content(GetFileContents("/static/" + pageName + ".html"));
}
public static string GetFileContents(string FileName)
{
   StreamReader sr = null;
   string FileContents = null;

   try
   {
      FileStream fs = new FileStream(FileName, FileMode.Open,
                                     FileAccess.Read);
      sr = new StreamReader(fs);
      FileContents = sr.ReadToEnd();
   }
   finally
   {
      if(sr != null)
      sr.Close();
   }

    return FileContents;
}

A: Write the file to the response and then return an EmptyResult.
public ActionResult StaticPage(string pagename)
{
    Response.WriteFile(Url.Content(string.Format("/static/{0}.html", pagename)));
    return new EmptyResult();
}


text:
Q: How to Regexextract whole words that contain a mixture of text and numbers in Google Sheets I am trying to make this formula work for a mixture of text and numbers. It works for text that contain 4 numbers only. How can I manipule this to match specific words e.g Text Text 50 or even random 2020 text.
I need to hardcode the words into the formula or using INDIRECT cell reference.
The formula I got.
=ArrayFormula(IF(A:A="",,TRIM(IFERROR(REGEXEXTRACT(A:A,"^([øa-zA-Z-\/ ]+)"))&IFERROR(REGEXEXTRACT(A:A," [0-9]{4}")))))

I simpler terms I want the formula to extract these specific words as they are without trimming them. This formula works for other strings except ones that are a mixture of numbers and text.
I tried to edit my formula like this but I wasn't successful.
=ArrayFormula(IF(A:A="",,TRIM(IFERROR(REGEXEXTRACT(A:A,"^([[:Text Text 50:]][[:random 2020 text:]][øa-zA-Z-\/ ]+)"))&IFERROR(REGEXEXTRACT(A:A," [0-9]{4}")))))

The link to my spreadsheet - https://docs.google.com/spreadsheets/d/1BYW-QzqRA8vIBWazDSZhbUZ_TCbVAPYSI-1hFthfrew/edit?usp=sharing

A: If you enter the texts you are looking for in a separate column (say into E1:E3), you can use this formula:
=IFERROR(ArrayFormula(REGEXEXTRACT(A:A,JOIN("|",E1:E3))),"")

If you want hardcode, just use:
=IFERROR(ArrayFormula(REGEXEXTRACT(A:A,"AC Reggiana 1919|B93 Copenhagen|Etar 1924 Veliko T..")),"")


text:
Q: How do you scale a button on Xcode 6 to fit different screen sizes using Autolayout? I am new to Xcode and learning about Autolayout. Having a pretty difficult time and think I've finally hit the wall and really need some guidance on the following.
So I created an image view with a .png background image that show button place holders to help me figure out the exact place I would like to place my button objects. So I pinned the image view on all four sides to 0 and it resized perfectly to different screen sizes. Now the problem came with the button. I dragged the button object out of the Object Library and placed it right on top of the image view, where the button place holder image lies. To the button, I gave constraints to its width and height, pinned the bottom and right, and Aspect Ratio to help resize accordingly to different screen sizes.
The first problem is that although the button is placed exactly where the image view shows, the button is located elsewhere, even though the image view is able to perfectly resize to different screen sizes. The second problem is that, although the button pins fine on all screens, the pinned lengths are staying static and not changing even though the screen goes bigger or smaller. The last problem is that the size of the button in itself is staying static as well even on different screen sizes.
Why is the button not able to resize (used Aspect Ratio but not working) and reposition in relative to different screen sizes? A guidance on this would be really appreciated! Been trying to figure this out for a whole day.

NEW UPDATE WITH TAKING OUT WIDTH AND HEIGHT CONSTRAINTS, LEAVING ASPECT RATIO ALONE:

A: you should remove  that width constraint to let the button resize just leading and trailing spaces are fine to increase it's width in different screen sizes


text:
Q: How do I not repeat the name of a generic data type when using it? public class MyPath {
    protected static Dictionary<string, object> Cache;
    void MyPath() {
        if (Cache.Count == 0) {
            var jspath = "path.json";
            // The code below repeats the type name:
            Cache = JsonConvert.DeserializeObject<Dictionary<string, object>>(File.ReadAllText(jspath)));
            ...

So, how can I fetch the type from the static class member rather than repeating myself when I'm deserializing the object by writing Dictionary?

A: If you would like to avoid repeating the type name, you can write a static generic method that captures the type of Cache:
private static void ReadFromJson<T>(ref T cache, string jspath) {
    cache = JsonConvert.DeserializeObject<T>(File.ReadAllText(jspath)));
}

You can use this method as follows:
if (Cache.Count == 0) {
    var jspath = "path.json";
    ReadFromJson(ref Cache, jspath);
    ...


text:
Q: Can't unset session during paypal ipn response I need to unset my session variables, when PayPal returns IPN.
The simplest script is the following
<?php
session_start();
unset($_SESSION['my_item']);
?>

Paypal sends IPN, all works fine, but after request my session variable save it's value.
What can be a problem?
Thanks
UPDATE
As mentioned, when ipn sends request, it's already another session, so i can do the following.
Before send user to paypal, set custom variable to current

session_id();

When paypal sends ipn, i can change current session to previus session, and clear it.
session_id($_POST[custom]);
session_start();
session_destroy(); //works fine

A: The problem here is that the IPN notification is not associated with the correct session.
The IPN is effectively a new session - it does not present the same session cookies that your client does, because you have not set them. Sessions are unique to a client, and the paypal gateway is a different client to that of your user.
You will need to bounce this information through a database. There is no sensible, easy way to have the IPN receiver directly modify the user's session data.

A: You should be checking for a specific post variable.  $_POST will always be set, even if just an empty array.
<?php
session_start();
if(isset($_POST['name'])) {
    unset($_SESSION['my_item']);
}
?>

A: I've already write the update, but it will be batter, if i write the solution as answer.
If i send session_id to paypal, and when it returns it back, i can set my current session to it's vallue, and delete it.
session_id($_POST[custom]); //$_POST[custom] is user's session id
session_start();
session_destroy();

A: Should your conditional be:
if(isset($_POST['ipn'])){
  ...do something
}

Then this should work:
if(isset($_POST['ipn'])){
  unset($_SESSION['my_item']);
}


text:
Q: C# Verifying data (signed with RSA private key) with public key using BouncyCastle and with help from a stackoverflow question I got this:
        using System.Net.Sockets;
        using System.Security.Cryptography;
        using Org.BouncyCastle.Crypto.Parameters;
        using Org.BouncyCastle.OpenSsl;

...
        TcpClient client = new TcpClient("127.0.0.1", 1337);
        NetworkStream stream = client.GetStream();

        StreamWriter writer= new StreamWriter(stream);
        StreamReader reader = new StreamReader(stream);

        writer.WriteLine("hello");
        writer.AutoFlush = true;

        string response = Convert.FromBase64String(reader.ReadToEnd()).ToString();

        RSACryptoServiceProvider RCP;
        var x = new PemReader(File.OpenText(pubkey));
        var y = (RsaKeyParameters)x.ReadObject();

        RCP = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create();

        var pa = new RSAParameters();
        pa.Modulus = y.Modulus.ToByteArray();
        pa.Exponent = y.Exponent.ToByteArray();

        RCP.ImportParameters(pa);
        byte[] test = RCP.Decrypt(response, true);

Now, obviously Decrypt will fail, as since I'm trying to decrypt something which was signed (not "encrypted") and definately not by the same "key". I'm confused since I thought I should use a method like VerifyData(), but this returns a bool and takes arguments I'm not sure I have.
What I wish to accomplish is the C# equivalent of openssl rsautl -verify -inkey public.pem -pubin. That is, "decrypt" with the pubkey to verify the contents of said message.
Am I on the right track here?

*

*Mik

A: Actually a decrypt of a signature should never fail unless you specified the wrong encoding parameters - a signature is simply the private-key encrypted hash of the data (typically SHA1); the only benefit of using the verify routine is that it decrypts the block and does the hash comparison work for you, if you wanted to be bloody minded you could instead do a decrypt operation with your public key and compare the hash bytes yourself.
I'm not actually sure what response is in the context of your program; you should only be passing the RSA data to it, if you're also feeding it the data that was signed in the first place you are doing it wrong - similarly, do check if that function actually accepts a string, in my experience BouncyCastle generally expects a byte[]
I'd recommend using SignerUtilities.GetSigner() - it takes a string arg to tell it what sort of signature you're using, I would imagine "SHA1WithRSA" to be right for you.


text:
Q: CSV - ERROR: BoundsError: and Feather - ERROR: InexactError: - Julia programming I'm very new to Julia Programming.
I have a folder of CSV files (14) that I join to one big data frame and I'm trying to save the big CSV. (rows - 262673020 x columns - 77) when I use CSV.write - I get this ERROR: BoundsError: attempt to access 4194304-element Array{UInt8,1} at index [1:4194305].
So I tried to save it into a feather file but I getting this ERROR: InexactError: trunc(Int32, 2147483662) - This error looks to be reaching some 32 max. but not sure why
I'm not sure what is going on just need some help understand what to do.
Package version -
Julia Version 1.5.2, -
Glob v1.3.0, -
CSV v0.5.23, -
Tables v0.2.11, -
Feather v0.5.4
Update to Package -
Julia Version 1.5.2 -
CSV 0.7.7 -
DataFrames v0.21.8 -
Glob v1.3.0 -
Tables v1.1.0 -
Feather v0.5.6 -
using Glob, CSV, Tables, Feather

fileDirectory = "location/CSV"
files = glob("*.csv", fileDirectory)

list_df = [DataFrame(CSV.read(f)) for f in files]
Join_DF = join(list_df[3], list_df[4], list_df[5], list_df[6], list_df[7], list_df[8], list_df[9], list_df[10], list_df[11], list_df[12], list_df[13], list_df[14], on = :INC_KEY, kind = :outer)

Feather.write("location/join_files.feather", Join_DF)
# ERROR: InexactError: trunc(Int32, 2147483662)

CSV.write("location/join_files.csv", Join_DF)
# ERROR: BoundsError: attempt to access 4194304-element Array{UInt8,1} at index [1:4194305].

CSV -
Stacktrace:
 [1] throw_boundserror(::Array{UInt8,1}, ::Tuple{UnitRange{Int64}}) at ./abstractarray.jl:541
 [2] checkbounds at ./abstractarray.jl:506 [inlined]
 [3] view at ./subarray.jl:158 [inlined]
 [4] writecell(::Array{UInt8,1}, ::Int64, ::Int64, ::IOStream, ::Int64, ::CSV.Options{UInt8,UInt8,Nothing,Tuple{}}) at /Users/.julia/packages/CSV/4GOjG/src/write.jl:147
 [5] #64 at /Users/.julia/packages/CSV/4GOjG/src/write.jl:182 [inlined]
 [6] macro expansion at /Users/.julia/packages/Tables/FXXeK/src/utils.jl:54 [inlined]
 [7] eachcolumn at /Users/.julia/packages/Tables/FXXeK/src/utils.jl:48 [inlined]
[8] writerow(::Array{UInt8,1}, ::Base.RefValue{Int64}, ::Int64, ::IOStream, ::Tables.Schema{(
[9] #55 at /Users/.julia/packages/CSV/4GOjG/src/write.jl:80 [inlined]
[10] (::CSV.var"#62#63"{CSV.var"#55#56"{Bool,Tables.Schema{(
[12] open(::Function, ::String, ::String) at ./io.jl:323
 [13] with at /Users/.julia/packages/CSV/4GOjG/src/write.jl:139 [inlined]
 [14] #write#54 at /Users/.julia/packages/CSV/4GOjG/src/write.jl:73 [inlined]
 [15] write(::Tables.Schema{(
 [16] write(::String, ::DataFrame; delim::Char, quotechar::Char, openquotechar::Nothing, closequotechar::Nothing, escapechar::Char, newline::Char, decimal::Char, dateformat::Nothing, quotestrings::Bool, missingstring::String, kwargs::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}) at /Users/.julia/packages/CSV/4GOjG/src/write.jl:60
 [17] write(::String, ::DataFrame) at /Users/.julia/packages/CSV/4GOjG/src/write.jl:53
 [18] top-level scope at none:1

Feather -
ERROR: InexactError: trunc(Int32, 2147483662)
Stacktrace:
 [1] throw_inexacterror(::Symbol, ::Type{Int32}, ::Int64) at ./boot.jl:558
 [2] checked_trunc_sint at ./boot.jl:580 [inlined]
 [3] toInt32 at ./boot.jl:617 [inlined]
 [4] Int32 at ./boot.jl:707 [inlined]
 [5] convert at ./number.jl:7 [inlined]
 [6] setindex! at ./array.jl:847 [inlined]
 [7] offsets(::Type{Int32}, ::Type{UInt8}, ::PooledArrays.PooledArray{Union{Missing, String},UInt32,1,Array{UInt32,1}}) at /Users/.julia/packages/Arrow/q3tEJ/src/lists.jl:300
 [8] Arrow.NullableList{String,Int32,P} where P<:Arrow.AbstractPrimitive(::Type{UInt8}, ::PooledArrays.PooledArray{Union{Missing, String},UInt32,1,Array{UInt32,1}}) at /Users/.julia/packages/Arrow/q3tEJ/src/lists.jl:243
 [9] NullableList at /Users/.julia/packages/Arrow/q3tEJ/src/lists.jl:251 [inlined]
 [10] arrowformat at /Users/.julia/packages/Arrow/q3tEJ/src/arrowvectors.jl:242 [inlined]
 [11] getarrow(::PooledArrays.PooledArray{Union{Missing, String},UInt32,1,Array{UInt32,1}}) at /Users/.julia/packages/Feather/y64Pt/src/sink.jl:40
 [12] write(::IOStream, ::DataFrame; description::String, metadata::String) at /Users/.julia/packages/Feather/y64Pt/src/sink.jl:18
 [13] #20 at /Users/.julia/packages/Feather/y64Pt/src/sink.jl:32 [inlined]
 [14] open(::Feather.var"#20#21"{String,String,DataFrame}, ::String, ::Vararg{String,N} where N; kwargs::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}) at ./io.jl:325
 [15] open at ./io.jl:323 [inlined]
 [16] #write#19 at /Users/.julia/packages/Feather/y64Pt/src/sink.jl:31 [inlined]
 [17] write(::String, ::DataFrame) at /Users/.julia/packages/Feather/y64Pt/src/sink.jl:31
 [18] top-level scope at none:1


text:
Q: UnityWebRequest returns HTTP Status 408 while calling Bing Speech API I am trying to invoke the Microsoft Bing Text to Speech API in Unity3D.
This API requires an accessToken and other parameters that will be passed in the request headers.
First of all, in order to get the accessToken, I have sent a POST request to the Token API, after that, I have sent the other parameters in the request headers and it worked perfectly (returns a Wav audioclip) in Postman, like so:

To make this in Unity, I have used the UnityWebRequest Class to send two POST requests (sequentially) and then recieve the Audio Response.
using System.Collections;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.Networking;

public class TextToSpeech : MonoBehaviour
{
    public AudioSource audioSource;
    public static readonly string accessUri = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    public static readonly string synthesizeUri = "https://speech.platform.bing.com/synthesize";
    public string textToSpeak = "Oh yeah! Finally Dorot is speaking.";
    private static string accessToken;
    private static readonly string apiKey = "MY API KEY";
    private string postStringData;

    public TextToSpeech (string textToSpeak)
    {
        this.textToSpeak = textToSpeak;
    }

    public void Speak()
    {
        audioSource = gameObject.GetComponent<AudioSource>();
        StartCoroutine(RequestToken(apiKey));
    }

    private string GenerateSsml(string textToSpeak)
    {
        var ssmlDoc = new XDocument(
                          new XElement("speak",
                              new XAttribute("version", "1.0"),
                              new XAttribute(XNamespace.Xml + "lang", "en-US"),
                              new XElement("voice",
                                  new XAttribute(XNamespace.Xml + "lang", "en-US"),
                                  new XAttribute(XNamespace.Xml + "gender", "Male"),
                                  new XAttribute("name", "Microsoft Server Speech Text to Speech Voice (en-US, BenjaminRUS)"),
                                  textToSpeak)));
        return ssmlDoc.ToString();
    }

    public IEnumerator RequestToken(string apiKey)
    {
        var tokenRequest = UnityWebRequest.Post(accessUri, "data");
        tokenRequest.SetRequestHeader("Ocp-Apim-Subscription-Key", apiKey);

        var tokenResponse = tokenRequest.SendWebRequest();
        yield return tokenResponse;

        if (tokenRequest.isHttpError)
        {
            Debug.LogError("HTTP Error: " + tokenRequest.error + " Code: " + tokenRequest.responseCode);
        }
        else
        {
            postStringData = GenerateSsml(textToSpeak);
            accessToken = tokenRequest.downloadHandler.text;
            Debug.Log("Access token: " + accessToken);

            StartCoroutine(Synthesize(postStringData, accessToken));
        }
    }

    public IEnumerator Synthesize(string text, string token)
    {
        var synReq = UnityWebRequest.Post(synthesizeUri, text);
        synReq.SetRequestHeader("Content-Type", "application/ssml+xml");
        synReq.SetRequestHeader("X-Microsoft-OutputFormat", "riff-16khz-16bit-mono-pcm");
        synReq.SetRequestHeader("X-Search-AppId", "07D3234E49CE426DAA29772419F436CA");
        synReq.SetRequestHeader("X-Search-ClientID", "1ECFAE91408841A480F00935DC390960");
        synReq.SetRequestHeader("User-Agent", "Dorot");
        synReq.SetRequestHeader("Authorization", "Bearer " + token);

        var synRes = synReq.SendWebRequest();
        yield return synRes;

        if (synReq.isHttpError)
        {
            Debug.LogError("HTTP Error: " + synReq.error + " Code: " + synReq.responseCode + " isNetworkError: " + synReq.isNetworkError + " isDone: " + synReq.isDone);
        }
        else
        {
            AudioClip cc = DownloadHandlerAudioClip.GetContent(synReq);
            audioSource.clip = cc;
            audioSource.Play();
        }
    }
}

As result, the first API returned correctly the Token. But, the second returned HTTP Code status 408, . Like so :

How can I solve this problem? Thanks.

A: Found the solution.
According to this answer, UnityWebRequest has chunkedTransfer set to true by default. So you need to do:
synReq.chunkedTransfer = false;

BTW: you could write a unit test for this by following this guide: http://www.invisiblerock.com/unity-test-runner (it's what I did to try this out)


text:
Q: Separate line where can be more character in perl I would like to cut these line

John Smith !! NewYork ! 01123 ! 3012-1-315-2164
Alexander Goblin -- WA ------ 9752 - 53-76-132-310
Bittner Albin    Cered   3123    26-1-278-127

There can be - ! \t between the words
I tried like below, but It's not working
while(<FILE>) {
        if($_=~m/(\w+\s\w+)((\t) | (\s!+\s) | (\s-+\s))(\w+)((\t) | (\s!+\s) | (\s-+\s)(\d+)((\t) | (\s!+\s) | (\s-
                (\d\d-\d\d-\d+-\d+)/){
                        print $1."\n";
        }
}

I think this is the problem : ((\t) | (\s!+\s) | (\s-+\s))

A: If you want to extract the first two words, you can use
if (m/(\w+\s+\w+)/) {
    print "$1\n";
}

If you want to split those lines to its field, you can use
my @field = split /\s+!+\s+ | \s+-+\s+ | \t+ /x;

Here is the full example:
#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my @record;
while (<DATA>) {
    chomp;
    if (m/(\w+\s+\w+)/) {
        print "$1\n";
    }

    my @field = split /\s+!+\s+ | \s+-+\s+ | \t+ /x;
    push @record, \@field;
}

print Dumper(\@record);

__DATA__
John Smith !! NewYork ! 01123 ! 3012-1-315-2164
Alexander Goblin -- WA ------ 9752 - 53-76-132-310
Bittner Albin   Cered   3123    26-1-278-127

Note: the separator of the last line in the above code is \t, not three/four spaces.

Output of the above program:
$ perl t.pl
John Smith
Alexander Goblin
Bittner Albin
$VAR1 = [
          [
            'John Smith',
            'NewYork',
            '01123',
            '3012-1-315-2164'
          ],
          [
            'Alexander Goblin',
            'WA',
            '9752',
            '53-76-132-310'
          ],
          [
            'Bittner Albin',
            'Cered',
            '3123',
            '26-1-278-127'
          ]
        ];


text:
Q: Component Exception in React Native I am getting an error saying:

As the error suggest I thought it had something to do with the exports in AppTextInput.js but everything looks alright in the file(this component is used in other files such as for SignIn, ignOut and ConfirmSignUp):
import React from 'react';
import {View, StyleSheet, TextInput} from 'react-native';
import {MaterialCommunityIcons} from 'react-native-vector-icons/MaterialCommunityIcons';

function AppTextInput({leftIcon, ...otherProps}) {
  return (
    <View style={styles.container}>
      {leftIcon && (
        <MaterialCommunityIcons
          name={leftIcon}
          size={20}
          color="#6e6869"
          style={styles.icon}
        />
      )}
      <TextInput
        style={styles.input}
        placeholderTextColor="#6e6869"
        {...otherProps}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#f9f9f9',
    borderRadius: 25,
    flexDirection: 'row',
    padding: 15,
    marginVertical: 10,
  },
  icon: {
    marginRight: 10,
  },
  input: {
    width: '80%',
    fontSize: 18,
    color: '#101010',
  },
});

export default AppTextInput;

The Source on the other hand says the error is coming from App.js at line 28 but I cannot find the error here(the file is much longer but I just included the source from the logs).

function App() {
  const [isUserLoggedIn, setUserLoggedIn] = useState('initializing');

  async function checkAuthState() {
    try {
      await Auth.currentAuthenticatedUser();
      console.log('User is signed in');
      setUserLoggedIn('loggedIn');
    } catch (err) {
      console.log('User is not signed in');
      setUserLoggedIn('loggedOut');
    }
  }
  useEffect(() => {
    checkAuthState();
  }, []);

  const AuthenticationNavigator = props => {
    return (
      <AuthenticationStack.Navigator headerMode="none">
        <AuthenticationStack.Screen
          name="SignIn"
          component={SignIn}></AuthenticationStack.Screen>
        <AuthenticationStack.Screen name="SignUp" component={SignUp} />
        <AuthenticationStack.Screen
          name="ConfirmSignUp"
          component={ConfirmSignUp}
        />
      </AuthenticationStack.Navigator>
    );
  };

  const AppNavigator = props => {
    return (
      <AppStack.Navigator>
        <AppStack.Screen name="Home" component={Home}></AppStack.Screen>
      </AppStack.Navigator>
    );
  };
  const Initializing = () => {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <ActivityIndicator size="large" color="tomato" />
      </View>
    );
  };

  function updateAuthState(isUserLoggedIn) {
    setUserLoggedIn(isUserLoggedIn);
  }

  return (
    <NavigationContainer>
      {isUserLoggedIn === 'initializing' && <Initializing />}
      {isUserLoggedIn === 'loggedIn' && (
        <AppNavigator updateAuthState={updateAuthState} />
      )}
      {isUserLoggedIn === 'loggedOut' && (
        <AuthenticationNavigator updateAuthState={updateAuthState} />
      )}
    </NavigationContainer>
  );
}

export default App;

Here is the Call Stack as well:

A: Your App.js component does not render anything, that why exception throw error.
After review your update, I think you are import something does not existing
import {MaterialCommunityIcons} from 'react-native-vector-icons/MaterialCommunityIcons';
It should be
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';


text:
Q: Run golang online and save it to an online file What my local program does right now is connect to a websocket and updates a local file with a json whenever a message is received.
Is there a way to run the golang program online and then update and save the file as a json file online that I will be able to see? I'm not sure but I think I would need a web server?
For example, the program would generate a website like this https://www.reddit.com/r/all.json ?

A: Typically most websites generate JSON responses directly into the HTTP request, they don't write the results into a file that is then served over HTTP.
You will need some kind of server that is exposed to the Internet either way. I would recommend you reading about how to use the HTTP server built into Go, so you don't need to write the results into a file: https://golang.org/doc/articles/wiki/. Once you gain a better understand on how web applications work, you can use higher level web frameworks that can help you be more productive, such as gin: https://github.com/gin-gonic/gin.
If you would still really like to write the results in a file and serve that file, you may as well use Go as the web server, and use https://golang.org/pkg/net/http/#ServeFile.
Example code of doing this:
package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/myfile.json", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "path/to/myfile.json")
    })

    // Serve on HTTP port (80)
    log.Fatal(http.ListenAndServe(":80", nil))
}


text:
Q: How to access data from a transitive relationship? Lets say I have 3 tables defined within SQLAlchemy: Task, Job, Log where Task defines some kind of task that can be executed, Job defines the concrete values of an executed task and Log stores some information about every execution. So each Log knows its job ID and each job knows its task ID:
class Task(DeclarativeBase):
    __tablename__ = 'task'

    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    # ...

    jobs = relationship("Job", backref="task")

class Job(DeclarativeBase):
    __tablename__ = 'job'

    id = Column(Integer, primary_key=True)
    task_id = Column(Integer, ForeignKey("task.id"), nullable=False)
    # ...

    logs = relationship("Log", backref="job")

class Log(DeclarativeBase):
    __tablename__ = 'name'

    id = Column(Integer, primary_key=True)
    job_id = Column(Integer, ForeignKey("job.id"), nullable=False)
    # ...

In our GUI we list all Log entries in order so our costumers can review them. However we need to filter them now and we want to filter them by task name. My naive approach was a new method in our LogDAO
class DAO(object):
    def __init__(self, session, model):
        """ :param session: The database session that is used for data access
            :param model: The db model class
        """
        self.session = session
        self.model = model

class LogDAO(DAO):
    def __init__(self, session):
        super(LogDAO, self).__init__(session, Log)

    # ...
    def with_task_name(task_name):
        self.session.query(self.model.job.task.name == task_name)

self.model.job exists but self.model.job.task does not. Is there any other elegant way to filter Log entries by Task name?

A: Found this solution:
class LogDAO(DAO):
    # ...
    def with_task_name(task_name):
        return self.session.query(Log)
            .join(Log.job)
            .join(Job.task)
            .filter(Task.name == task_name)


text:
Q: How to get/set the number of threads WCF uses to handle requests in parallel? How do I get and set the number of threads allowed in a WCF server thread pool to handle incoming requests in parallel?
I am using a WebHttpBinding.

A: You get them via the ServiceThrottlingBehavior class, The defaults are as follows
.NET 3.0/3.5

*

*MaxConcurrentSessions: 10

*MaxConcurrentCalls: 16

*MaxConcurrentInstances: 26

.NET 4.0+

*

*MaxConcurrentSessions: 100 * ProcessorCount

*MaxConcurrentCalls: 16 * ProcessorCount

*MaxConcurrentInstances: MaxConcurrentSessions + MaxConcurrentCalls

The thing you are most interested in is MaxConcurrentInstances as that is what would consume a thread. Normally if you where to configure this you would set it up in your app.config file
<configuration>
  <appSettings>
    <!-- use appSetting to configure base address provided by host -->
    <add key="baseAddress" value="http://localhost:8080/ServiceMetadata" />
  </appSettings>
  <system.serviceModel>
    <services>
      <service
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="Throttled" >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior  name="Throttled">
          <serviceThrottling
            maxConcurrentCalls="1"
            maxConcurrentSessions="1"
            maxConcurrentInstances="1"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Looking up via code is much more difficult to do (I could not figure out how, I normally just use configuration files)


text:
Q: Value of type '(CreateCompanyTableViewController) -> () -> CreateCompanyTableViewController' has no member 'newStakeholders'? I have created a new Datasource for my dynamic UITable "NewUser List" Embed nn static view cell. my problem with  var dataSource = NewUserDataSource(newStakeholders: self.newStakeholders)
give me this error

Value of type '(CreateCompanyTableViewController) -> () ->
CreateCompanyTableViewController' has no member 'newStakeholders'

class CreateCompanyTableViewController: UITableViewController {
    @IBOutlet weak var lblNumberOfUser: UILabel!
    var newStakeholders: [ReadOrganizationStakeholder] = []

    @IBOutlet weak var companyUsersTableView: UITableView!
    var dataSource = NewUserDataSource(newStakeholders: self.newStakeholders)

    override func viewDidLoad() {
        super.viewDidLoad()
        lblNumberOfUser.text = "\(newStakeholders.count) Users"
        companyUsersTableView.dataSource = dataSource
        companyUsersTableView.delegate = dataSource as! UITableViewDelegate
    }
}

class NewUserDataSource: NSObject, UITableViewDataSource {
    // We keep this public and mutable, to enable our data
    // source to be updated as new data comes in.
    var newStakeholders: [ReadOrganizationStakeholder]

    init(newStakeholders: [ReadOrganizationStakeholder]) {
        self.newStakeholders = newStakeholders
    }

    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return newStakeholders.count
    }

    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let stakeholders = newStakeholders[indexPath.row]
        let cell = tableView.dequeueReusableCell(
            withIdentifier: "newUserTableViewCell",
            for: indexPath
        ) as! NewUserTableViewCell

        cell.lblUsername.text  = stakeholders.fullName
        cell.lblEmail.text = stakeholders.emailAddress

        return cell
    }
}

A: In that line you are using self outside of a method.
Move that line to viewDidLoad() or to a new init method.


text:
Q: UPDATE table whith specific condition I have 2 tables - products  and product_categories.
These tables JOIN ON products.product_id = product_categories.product_id .
I want to UPDATE field published in table products which have condition product_categories.product_categories = 100 .

A: Try this
UPDATE bjvui_virtuemart_products as prod
  INNER JOIN bjvui_virtuemart_product_categories as cat
  ON prod.virtuemart_product_id =cat.virtuemart_product_id
SET prod.published ={value}
WHERE cat.virtuemart_category_id=100

A: Use UPDATE with JOIN
UPDATE TABLEA a
JOIN TABLEB b ON a.join_colA = b.join_colB
SET a.columnToUpdate = [something]
WHERE a.someColumn = [some_value]

For your case
UPDATE bjvui_virtuemart_products AS p
INNER JOIN bjvui_virtuemart_product_categories AS c ON
p.virtuemart_product_id = c.virtuemart_product_id
SET p.published = "your_value"
WHERE c.virtuemart_category_id = 100;


text:
Q: Relationship between users and items tables in a database I have two tables in a database: A users_table and a items_table. I need a way to be able to define which items each user gets access to. I thought to create a third table containing: 'user_id', 'item_id', and 'has_access' columns.
The problem I am having is that the users_table as well as the items_table have 'active' columns that can change. Users can only get access to items that are active. Items can only be assigned to users that are active. Thus when a user/item is set to inactive all of the records in the third table that refer to that user/item should be set to inactive. Same goes for when a user/item gets deleted in their respective tables.
When a new user gets added they should automatically get assigned all of the items (has_access = false). When a new item gets added to the items_table, all users should automatically get assigned the new item (again, with column has_access set to false).
The reason for this is I want to simply be able to make a SQl query such as SELECT * FROM users-items_table WHERE user_id='someId', and use the information returned to build up a profile for the user containing the items they have access to.
How would I set up the relationship between the tables to achieve this?

A: The UserItems table doesn't need an HasAccess field. If a record exists in this table for a combination of UserId and ItemId, it means the user has access to the item. If you want to revoke access, delete the record.
So I would definately advise against this:

When a new user gets added they should automatically get assigned all
  of the items (has_access = false). When a new item gets added to the
  items_table, all users should automatically get assigned the new item
  (again, with column has_access set to false).

Assigning an item to a user is as simple as adding a record in the UserItems table.
INSERT INTO UserItems (userId, itemId) VALUES (123, 456);

To query, you simply join the tables together. Don't forget to check for active items. Something like:
SELECT * FROM Item
   INNER JOIN UserItems ON Item.Id = UserItems.ItemId
   WHERE UserItems.UserId = 123
      AND Item.IsActive = true;

This will return all active items that are assigned to a user.
If you want to see, for example, all users that have a certain item assigned, turn the query around:
SELECT * FROM User
   INNER JOIN UserItems ON User.Id = UserItems.UserId
   WHERE UserItems.ItemId = 456
      AND User.IsActive = true;

As a sidenote, don't name your tables users_table or items_table. The convention is to use User and Item. For join tables, the convention is to make the second part plural: UserItems.


text:
Q: With nvd3.js/d3.js, how can you have a scatter or line chart with discrete/non-numeric/non-time-series X-Axis values? For example, I want a scatter chart that looks like:
   100|        X                                           o
      |                                      o
    60|
      |        o             X               X
    40|
      |
    20|                      o                             X
      |
     0|______________________________________________________________
             Apples        Carrots        Dragons        Monkies

Where X and o are different sets of data

A: The key is to use an ordinal sale for the x axis. Ordinal scales are constructed by calling d3.scale.ordinal(). The domain would be an array of your titles (you can use the native map method on your array of data to pull out the titles dynamically). The range needs to by an array of the same length as the domain array, specifying each xcoordinate in pixels that will correspond to the titles.
See this example here: http://tributary.io/inlet/5788637
You can fork it and try adding a yScale (in this case it will be constructed by d3.scale.linear since it is a continous number scale) and making a y axis following a similar pattern as the x axis.


text:
Q: How to show FTP server list in ListBox using MFC I want to make an FTP server client using MFC.
Server connection has been successful.
How do I print a list of FTP server files and diretory in the list box??
Any advice would be appreciated with a simple example.
CInternetSession m_Session;
CFtpConnection* m_pConnection;
CFtpFileFind* m_pFileFind;
CListBox m_List;
CString m_strIP, m_strID, m_strPass;

void CMFC_FTPDlg::ConnectFTP()
{
    GetDlgItemText(IDC_EDIT_IP, m_strIP);
    GetDlgItemText(IDC_EDIT_ID, m_strID);
    GetDlgItemText(IDC_EDIT_PASS, m_strPass);
    m_nPort = GetDlgItemInt(IDC_EDIT_PORT);

    m_pConnection = m_Session.GetFtpConnection(m_strIP, m_strID, m_strPass, m_nPort);

    if(!m_pConnection)
    {
        AfxMessageBox("ERROR : Disconnected!!");
        m_pConnection = NULL;
        m_bContinue = FALSE;
        return;
    }
    else
    {
        AfxMessageBox("Connected!!");
        m_bContinue = TRUE;
    }
}

void CMFC_FTPDlg::ShowList()
{
    int nResult;
    nResult = m_pConnection->SetCurrentDirectory("test");
}

A: Per the documentation, Steps in a Typical FTP Client Application, you need to use the CFtpFileFind class, which has FindFile() and FindNextFile() methods for enumerating an FTP server's files.
You already have a CFtpFileFind* m_pFileFind variable declared, but you are not using it.
Try this:
void CMFC_FTPDlg::ShowList()
{
    int nResult;
    nResult = m_pConnection->SetCurrentDirectory("test");

    CFtpFileFind finder(m_pConnection);
    BOOL bWorking = finder.FindFile(_T("*"));
    while (bWorking)
    {
        bWorking = finder.FindNextFile();
        // use finder.GetFileURL() or finder.GetFileName() as needed...
    }
}


text:
Q: Drools attributes explanations I have a question about 2 Drools attributes - salience and no-loop
salience:
rule "Hello World"
    salience -10
    when
        $m : Message( status == Message.HELLO, $myMessage : message )
    then
        System.out.println( $myMessage );
        $m.setMessage( "Goodbye cruel world" );
        $m.setStatus( Message.GOODBYE );
        update( $m );
end

rule "GoodBye"
    when
        Message( status == Message.GOODBYE, $myMessage : message )
    then
        System.out.println( $myMessage );
end

We should expect the "GoodBye" rule to be fired first(since its salience is higher) however that doesn't happen and instead the "Hello World" rule gets fired up first and only then "GoodBye"
no-loop:
I understand that this attribute prevent from a rule to be executed to the same fact which will cause an infinite loop. My question is about an example about this attribute that I don't quite understand:
rule "interest calculation"
no-loop
when
$account : Account( )
then
modify($account) {
setBalance((long)($account.getBalance() * 1.03));
}
end

If there wasn't "no-loop" why that will cause an infinite loop?

A: Re salience: Logic always beats salience. If Message.status is initially set to Message.HELLO, the other rule doesn't qualify and "Hello World" is executed.
Re no-loop: A modify/update simply means that re-evaluation of everything begins from scratch as far as the modified fact is concerned. So, Account is updated, goes back to square one, and reevaluation creates another activation of this trivially matching rule.


text:
Q: Proposal kernel for guided particle filter I want to use a guided particle filter in a PMCMC algorithm and therefore need to compute the proposal kernel. This is given by
\begin{equation}
M_{opt}^t(x_{t-1}, dxt) = \frac{f_t(y_t|x_t)}{\int_{\mathcal{X}}f_t(y_t|x')P_t(x_{t-1}, dx')}P_t(x_{t-1},dx_t).
\end{equation}
My model consists of
\begin{equation}
X_t|X_{t-1}=x_{t-1}\sim\mathcal{N}(x_{t-1}+\mu(x_{t-1})*dt, \sigma(x_{t-1})\sqrt{dt}).
\end{equation}
And $f_t(y_t|x_t)=\mathcal{N}_2(x_t, \sigma_y)$ with $\sigma_y=\sigma*\mathcal{I}_2$
So both are Gaussian and I guessed that I might be able to get the optimal proposal in a closed form. However, I fail in computing the denominator of the above formula.
Anyone knows how to compute it or am I wrong and it is not available in a closed form ? Then, has anyone a suggestion how to approximate it?
Thanks!


text: Q: Ascending order of big group I have a file with around 200 numbers that need to be pun in ascending order then separated into even and odd, from an earlier question here I have fixed the even and odd code but I need to make it ascending order.


text:
Q: Heap Overflow And Stack Overflow examples I need help in understanding heap and stack overflow, so it would be a lot helpful if I had few examples to understand the concept well

A: As the comments point out, there is a lot written about this on the internet already.  Still, I am fan of doing hands-on research so here is some sample code (below) to get you started.  I hope you find the following thought provoking... it is one thing to get an a simple answer, I think you'll find working through the data points so you understand what the answers mean more satisfying.
The sample code (see below) is hardwired in main() to call either stress_heap() or stress_stack().
It pretty much dies so hard on my system that the catch blocks aren't helpful for reporting the results, so I added some intermediate print statements to show what is going on.
Here are some charts (my first time posting images, so I hope it works).
"cnt" represents the number of times stress_heap() or stress_stack() has been called.  The memory values free & total are from the Java Runtime class.  (total is how much the host system has granted the particular Java instance to work with, while free is how much of that total memory is avaialable for creating additional objects).

The key thing for you to understand is available memory (heap) vs stack size.
In Java all object instances live in heap.
Object references (and primitives) are passed as params directly in the stack, which don't use the heap.
Some questions to consider: when you can answer these you'll have a better understanding of heap vs. stack.

*

*Why did the count for stress_heap() get so much larger than
stress_stack() ?

*Why does total memory increase for stress_heap() but
not for stress_stack() ?

*Why does free memory increase AND
decrease for stress_heap() but not for stress_stack() ?

Here is sample output that the above charts are based on (redundant lines omitted):
output, compiled for stress_heap()
$ java Stress
stress_heap() cnt=100000 free=264613280 total=381157376
stress_heap() cnt=200000 free=450105464 total=661127168
stress_heap() cnt=300000 free=343009208 total=661127168
stress_heap() cnt=400000 free=589030360 total=1009778688
stress_heap() cnt=500000 free=485900632 total=1009778688
...45 lines deleted...
stress_heap() cnt=5100000 free=327236008 total=5656018944
stress_heap() cnt=5200000 free=214346344 total=5656018944
stress_heap() cnt=5300000 free=115567888 total=5656018944
stress_heap() cnt=5400000 free=16789432 total=5656018944
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Stress.stress_heap(Stress.java:14)
    at Stress.main(Stress.java:45)
$

output, compiled for stress_stack()
$ java Stress
stress_stack_recurse() cnt=100 free=377151576 total=381157376
stress_stack_recurse() cnt=200 free=377151576 total=381157376
...114 lines deleted...
stress_stack_recurse() cnt=11700 free=377151576 total=381157376
stress_stack_recurse() cnt=11800 free=377151576 total=381157376
Exception in thread "main" java.lang.StackOverflowError
    at java.util.Arrays.copyOf(Arrays.java:2367)
    at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
    at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415)
    at java.lang.StringBuilder.append(StringBuilder.java:132)
    at Stress.stress_stack_recurse(Stress.java:34)
    at Stress.stress_stack_recurse(Stress.java:36)
...1,015 lines deleted...
    at Stress.stress_stack_recurse(Stress.java:36)
    at Stress.stress_stack_recurse(Stress.java:36)
$

Stress.java - example program
Depending on the system you run this on you may need to adjust the output intervals (the count thresholds) up or down.
I encourage you to modify stress_stack_recurse() to add additional primitive arguments, something like:
stress_stack_recurse1( int a ) { ... stress_stack_recurse(a+1); }
stress_stack_recurse4( int a, int b, int c, int d )  { ... stress_stack_recurse4(a+1, b+1, c+1, d+1); }

I think you'll want to modify arguments so compiler doesn't optimize them out, may need to add them to the conditional print to ensure they're used in the method body.
The goal here is to see how high cnt gets before failing based on number of arguments.
A similar research item would be to change the size value in stress_heap() and see how long that runs to 1024*16 (16kb) or 1024*1024 (1mb) size chunks.
import java.util.*;
public class Stress {

   static Runtime runtime = Runtime.getRuntime();
   static long cnt = 0;

   public static void stress_heap() {
      int size = 1024; // start with 1kb
      // research question: what happens to cnt as you modify size ?
      List<byte[]> a = new ArrayList<>(); // keep a list of byte arrays.
      System.out.println("stress_heap(): size="+size);
      try {
         while( true ) {
            byte[] b = new byte[size];
            a.add( b );
            ++cnt; // only increment if successful.
            if( 0 == (cnt % 100000) ) {
               // Question: does this output display at the same tempo?
               // Or does it get faster (or slower) as the program runs?
               System.out.println("stress_heap() cnt="+cnt+" free="+runtime.freeMemory()+" total="+runtime.totalMemory() );
            }
         }
      } catch( Exception e ) {
         // Sometimes fails so hard it doesn't reach this catch block.
         System.out.println("stress_heap(): problem, cnt="+cnt+", exception="+e);
      }
   }

   public static void stress_stack_recurse( ) {
      ++cnt;
      if( 0 == (cnt % 100) ) {
         // Question: why does stress_stack_recurse() fail at such a low value count compared to stress_heap() ?
         // Question: does this output display at the same tempo?
         System.out.println("stress_stack_recurse() cnt="+cnt+" free="+runtime.freeMemory()+" total="+runtime.totalMemory() );
      }
      stress_stack_recurse( );
   }

   public static void stress_stack( ) {
      // want the
      try {
         stress_stack_recurse( );
      } catch( Exception e ) {
         // Sometimes fails so hard it doesn't reach this catch block.
         System.out.println("stress_stack(): problem, cnt="+cnt+", exception="+e);
      }
   }

   public static void main( String[] args ) {
      //stress_heap();
      stress_stack();
   }
}

For bonus points, you could try passing in new byte arrays allocated in stress_stack() - any object really, but byte arrays seem easiest to reason about memory usage with.
That could look something like this (this is untested code):
   public static void main( String[] args ) {
      //stress_heap();
      //stress_stack();
      byte[] b = new byte[1024];
      stress_both( b);
   }

   public static void stress_both( byte[] b ) {
      ++cnt;
      if( 0 == (cnt % 100) ) {
         System.out.println("stress_both() cnt="+cnt+" b.length="+b.length+" free="+runtime.freeMemory()+" total="+runtime.totalMemory() );
      }
      byte[] yetAnotherByteArray = new byte[1024];
      stress_stack_recurse( yetAnotherByteArray );

   }
}


text:
Q: Is there a simple way to upload a Tab delimited file to SQL Server without using BCP? After using BCP for a year and fooling around with character encoding (x-UTF-16LE-BOM? Really?) we want a better solution. I have worked with Oracle and it is as simple as selecting a table and uploading the file.
Is there anything that can do that with SQL Server?

*

*BCP must use x-UTF-16LE-BOM or it chokes.

*BULK INSERT requires the file to be on the SQL Server instance (really?)

I have Microsoft SQL Server Management Studio but it doesn't seem able to do it.
Any help? We are in the Azure Cloud and I want it simple!


text:
Q: Passing domain-specific objects to a domain-specific task in jBPM 6 workbench I've been struggling with this for a few days and haven't had much luck. In jBPM 6 workbench running on jboss wildfly, I'm trying to invoke a custom work item handler and pass in an instance of a domain-specific object.
Here's my process so far:

*

*Define a domain-specific class acme.datamodel.UserBio in an external jar: datamodel.jar.

*Upload "datamodel.jar" to jbpm-console via the "Artifact repository"->Upload feature.

*Create a new repository in jbpm-console and create a new jbpm project.

*Add datamodel.jar as a dependency to my jbpm project via the Project editor.

*Create a new process in the jbpm project.

*Create a new process variable of type acme.datamodel.UserBio.

*Create a new work item definition for my domain-specific task (Greeting.wid) like so:
import org.drools.core.process.core.datatype.impl.type.StringDataType;
import org.drools.core.process.core.datatype.impl.type.ObjectDataType;
[
  [
    "name" : "Greeting",
    "parameters" : [
        "UserBio" : new ObjectDataType("acme.datamodel.UserBio")
    ],
    "results" : [
        "Result" : new ObjectDataType("java.util.Map")
    ],
    "displayName" : "Greeting",
    "icon" : "../../../global/defaultservicenodeicon.png"
  ]
]

*Add the domain-specific task (Greeting) to my process workflow.

*Map the process variable from step 5 as the input parameter for the Greeting task.

*Define my custom work item handler in an external jar (workitems.jar) like so:
package acme.workitem.greeting;

import java.util.Map;

import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.internal.runtime.StatefulKnowledgeSession;

import acme.datamodel.UserBio;

public class GreetingWorkItemHandler implements WorkItemHandler {

        private StatefulKnowledgeSession ksession;

    public GreetingWorkItemHandler(StatefulKnowledgeSession ksession) {
            this.ksession = ksession;
        }

    public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) {

        // Extract required parameters
        UserBio bio = (UserBio) workItem.getParameter("UserBio");

        // Do something

        // Notify manager that work item has been completed and return results
        Map<String, Object> results = new HashMap<String, Object>();
        workItemManager.completeWorkItem(workItem.getId(), results);
    }

    public void abortWorkItem(WorkItem workItem, WorkItemManager workItemManager) {
        // Can't abort a greeting work item handler
    }
}

*Copy workitems.jar to the jbpm-installer/dependencies directory.

*Edit jbpm-installer/conf/META-INF/CustomWorkItemHandlers.conf and add the following line:
"Greeting" : new acme.workitem.greeting.GreetingWorkItemHandler(ksession)

*Re-install jbpm demo (i.e. jbpm-console) and restart jboss.

*Load jbpm-console in a browser, start an instance of my process and attempt to invoke the domain-specific task.
After all this, when the domain-specific task is loaded and the custom work item handler is invoked, I get the following error in jbpm-console but nothing displayed in my jboss log:
Unexpected error encountered : java.lang.NoClassDefFoundError:acme/datamodel/UserBio

Are custom work item handlers not loaded with the same classloader as the process instances that invoke them?
I've tried adding the datamodel.jar into my workitems.jar under the META-INF/lib directory but that didn't seem to change anything.
Do I need to add datamodel.jar as a dependency to the Greeting.wid? How do I define the location of the jar file when it's already been uploaded to jbpm-console? Do I just copy datamodel.jar to the dependencies directory like I did for the workitems.jar and re-install the jbpm-console? Won't this cause potential collisions with the version uploaded to the jbpm-console in step 2?
These are just some of the things I've been wrestling with over the past few days. All the examples I've seen for dealing with custom work item handlers only ever seem to pass in primitives, never more complicated objects.
If anyone can explain where I've gone wrong or point me to better examples I'd very much appreciate it.

A: I was able to successfully invoke the custom work item handler by deploying the datamodel jar along with the workitem jar. A few more details can be found here.


text:
Q: Possible to get "per Page" Tab View counts via Insights API / FQL? In the Insights FQL documentation I see the application_tab_views metric listed, but it appears to only show the total Tab impressions over all of the pages the Application is installed on.
The "object_id" in the query is an Application Id, not a Page Id. I don't see a way to add additional "where" conditions to limit it to a specific page. Also, I don't see this metric listed in Pages Insights API.
I am wondering if it's possible to query the number of application tab views on a per-Page basis? Through the regular API or FQL?
In the Page Insights dashboard you can see Facebook is collecting this data (on the "Reach" sub-tab):

A: My client also wanted these statistics - my solution was to parse the signed_request that the tab receives, the current page_id is in the data and I managed those statistics in my own database.  The data is in a parameter called page. From the documentation :

page : A JSON object containing the page id string, the liked boolean if the
  user has liked the page, the admin boolean if the user is an admin.
  Only available if your app is an iframe loaded in a Page tab.


text:
Q: Constructor Calls For Class inheriting from vector Confusion In the following code, I am creating a Vector class that inherits from the standard vector class. I am confused as to why in main, my Vector object doesn't call the derived class constructor when I include the following line
using vector<T>::vector;

but when I don't include it, it calls my derived class constructor as expected. What is the reason for this? I haven't been able to replicate the problem with toy code, so that would be very much appreciated.
#include <iostream>
#include <vector>
using namespace std;

template <class T>
class Vector : public vector<T>
{
    vector <T> x;
    //using vector<T>::vector;
    public:
    Vector(vector <T> x)
    {
        this->x = x;
        for (auto i: this->x)
            cout << i << " ";
    }

};

int main() {
    Vector <int> x({1,2,3,4,5});
    return 0;
}

A: You pass {1,2,3,4,5} (which is not a std::vector) as the argument to Vector. Since std::vector provides a better match for that type, and you asked to reuse its constructors, it is constructed directly.
If you pass a std::vector<int>{1,2,3,4,5} instead, your constructor gets called.
Note also, that your example code constructs 2 std::vectors as part of Vector (the inherited one and the member x) and using namespace std is considered bad practice.


text:
Q: Unable to load script from assets index.android.bundle (Linux) I followed these steps to generate unsigned apk file.
Actually I managed to successfully generate the apk file and when I copy it to my device install and run it, I get red screen with an error:

unable to load script from assets index.android.bundle

Can someone help me what is wrong?
ps. I found kind of similar issue here, albeit it was for windows, but the suggestion in the answer (highest voted one) uses different commands to generate apk file compared to the one I used before(my first link), so I am not sure I should follow that advice.